hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
sequencelengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
sequencelengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
sequencelengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
5acc4ab4d9834f6261945e202b17ad0eaa29e43f
394
cpp
C++
src/State.cpp
JoanStinson/AI_Decisions
22632090c80b4a12e0f1049b4e6c78be3d024b2a
[ "MIT" ]
3
2021-03-31T03:42:42.000Z
2021-12-13T03:03:03.000Z
src/State.cpp
JoanStinson/AI_Decisions
22632090c80b4a12e0f1049b4e6c78be3d024b2a
[ "MIT" ]
null
null
null
src/State.cpp
JoanStinson/AI_Decisions
22632090c80b4a12e0f1049b4e6c78be3d024b2a
[ "MIT" ]
1
2021-12-13T03:02:55.000Z
2021-12-13T03:02:55.000Z
#include "State.h" State::State() { bankPosition = Vector2D(208, 624); homePosition = Vector2D(624, 624); minePosition = Vector2D(272, 112); saloonPosition = Vector2D(1040, 624); } State::~State() { delete agent; } void State::Init(Agent * agent, Uint32 delayTime) { this->agent = agent; this->delayTime = delayTime; } void State::Quit(State * state) { agent->SwitchState(state); }
17.909091
51
0.682741
JoanStinson
5ace0782dec3b99ee0a5f4f46b0d1c899d9277ad
2,326
cpp
C++
graph-source-code/362-E/8343555.cpp
AmrARaouf/algorithm-detection
59f3028d2298804870b32729415d71eec6116557
[ "MIT" ]
null
null
null
graph-source-code/362-E/8343555.cpp
AmrARaouf/algorithm-detection
59f3028d2298804870b32729415d71eec6116557
[ "MIT" ]
null
null
null
graph-source-code/362-E/8343555.cpp
AmrARaouf/algorithm-detection
59f3028d2298804870b32729415d71eec6116557
[ "MIT" ]
null
null
null
//Language: GNU C++ #include <iostream> #include <cstdio> #include <cstring> #include <cmath> #include <algorithm> #include <climits> #include <vector> #include <queue> #include <cstdlib> #include <string> #include <set> #include <stack> #define LL long long #define pii pair<int,int> #define INF 0x3f3f3f3f using namespace std; const int maxn = 110; struct arc { int to,flow,cost,next; arc(int x = 0,int y = 0,int z = 0,int nxt = -1) { to = x; flow = y; cost = z; next = nxt; } }; arc e[10000]; int head[maxn],d[maxn],p[maxn],S,T,n,k,tot; bool in[maxn]; void add(int u,int v,int flow,int cost) { e[tot] = arc(v,flow,cost,head[u]); head[u] = tot++; e[tot] = arc(u,0,-cost,head[v]); head[v] = tot++; } bool spfa() { queue<int>q; for(int i = 0; i <= n; ++i) { d[i] = INF; p[i] = -1; in[i] = false; } d[S] = 0; q.push(S); while(!q.empty()) { int u = q.front(); q.pop(); in[u] = false; for(int i = head[u]; ~i; i = e[i].next) { if(e[i].flow && d[e[i].to] > d[u] + e[i].cost) { d[e[i].to] = d[u] + e[i].cost; p[e[i].to] = i; if(!in[e[i].to]){ in[e[i].to] = true; q.push(e[i].to); } } } } return p[T] > -1; } int solve() { int cost = 0,flow = 0; while(spfa()) { int theMin = INF; for(int i = p[T]; ~i; i = p[e[i^1].to]) theMin = min(theMin,e[i].flow); if(cost + d[T]*theMin > k) return flow + (k - cost)/d[T]; flow += theMin; cost += d[T]*theMin; for(int i = p[T]; ~i; i = p[e[i^1].to]) { e[i].flow -= theMin; e[i^1].flow += theMin; } } return flow; } int main() { while(~scanf("%d %d",&n,&k)) { memset(head,-1,sizeof(head)); S = 0; T = n-1; int tmp; for(int i = tot = 0; i < n; ++i) for(int j = 0; j < n; ++j) { scanf("%d",&tmp); if(tmp) { add(i,j,tmp,0); add(i,j,k,1); } } printf("%d\n",solve()); } return 0; }
23.029703
65
0.410146
AmrARaouf
5ace2172fa2ef85d29199534b22ab9249c590b0d
1,792
hpp
C++
tools/json-ast-exporter/src/json_utils.hpp
TheoKant/cclyzer-souffle
dfcd01daa592a2356e36aaeaa9c933305c253cba
[ "MIT" ]
63
2016-02-06T21:06:40.000Z
2021-11-16T19:58:27.000Z
tools/json-ast-exporter/src/json_utils.hpp
TheoKant/cclyzer-souffle
dfcd01daa592a2356e36aaeaa9c933305c253cba
[ "MIT" ]
11
2019-05-23T20:55:12.000Z
2021-12-08T22:18:01.000Z
tools/json-ast-exporter/src/json_utils.hpp
TheoKant/cclyzer-souffle
dfcd01daa592a2356e36aaeaa9c933305c253cba
[ "MIT" ]
14
2016-02-21T17:12:36.000Z
2021-09-26T02:48:41.000Z
#ifndef JSON_UTILS_HPP__ #define JSON_UTILS_HPP__ #include <string> #include <clang-c/Index.h> #include <jsoncons/json.hpp> namespace cclyzer { namespace ast_exporter { namespace jsonexport { typedef jsoncons::json json_t; // Recording routines void record_extent( json_t &, CXCursor ); void record_extent(json_t &, CXSourceRange ); void record_kind( json_t &, CXCursor ); void record_spelling( json_t &, CXCursor ); void record_tokens( json_t &, CXCursor, CXTranslationUnit ); void record_token( json_t & , CXToken, CXTranslationUnit ); // AST Node properties namespace node { const std::string FILE = "file"; const std::string KIND = "kind"; const std::string DATA = "data"; const std::string START_LINE = "start_line"; const std::string START_COLUMN = "start_column"; const std::string START_OFFSET = "start_offset"; const std::string END_LINE = "end_line"; const std::string END_COLUMN = "end_column"; const std::string END_OFFSET = "end_offset"; const std::string TOKENS = "tokens"; const std::string TREE = "ast"; } // Lexical Token Properties namespace lex_token { const std::string KIND = "kind"; const std::string DATA = "data"; const std::string FILE = "file"; const std::string LINE = "line"; const std::string COLUMN = "column"; const std::string OFFSET = "offset"; } } } } #endif /* JSON_UTILS_HPP__ */
32
72
0.541853
TheoKant
62c26d2c087b23d3802b9a3ea8eeba0faf253fea
601
cpp
C++
238-product-of-array-except-self/238-product-of-array-except-self.cpp
dishanp/LeetCode-World
6c49c8731dae772fb7bc47f777a4d3b3e01dd70e
[ "MIT" ]
null
null
null
238-product-of-array-except-self/238-product-of-array-except-self.cpp
dishanp/LeetCode-World
6c49c8731dae772fb7bc47f777a4d3b3e01dd70e
[ "MIT" ]
null
null
null
238-product-of-array-except-self/238-product-of-array-except-self.cpp
dishanp/LeetCode-World
6c49c8731dae772fb7bc47f777a4d3b3e01dd70e
[ "MIT" ]
null
null
null
class Solution { public: vector<int> productExceptSelf(vector<int>& nums) { int p=1; int ctr=0; int zp=1; for(int i:nums) { p*=i; if(i==0) ++ctr; if(ctr>1){ vector<int>ans(nums.size(),0); return ans; } if(i!=0) zp*=i; } vector<int>res; for(int i:nums) { if(i==0) res.push_back(zp); else res.push_back(p/i); } return res; } };
20.724138
54
0.344426
dishanp
62c7c24a915b70d87ec6da0b51c9364ddca01ca9
1,290
hpp
C++
engine/source/src/Engine_collision_listener.hpp
mateusgondim/Demos
6aa5da3a6c0e960d10811c9e71e9a0a746e8d6ab
[ "MIT" ]
5
2019-02-12T07:23:55.000Z
2020-06-22T15:03:36.000Z
engine/source/src/Engine_collision_listener.hpp
mateusgondim/Demos
6aa5da3a6c0e960d10811c9e71e9a0a746e8d6ab
[ "MIT" ]
null
null
null
engine/source/src/Engine_collision_listener.hpp
mateusgondim/Demos
6aa5da3a6c0e960d10811c9e71e9a0a746e8d6ab
[ "MIT" ]
2
2019-06-17T05:04:21.000Z
2020-04-22T09:05:57.000Z
#ifndef _ENGINE_COLLISION_LISTENER_HPP #define _ENGINE_COLLISION_LISTENER_HPP #include "Collision_listener.hpp" #include <cstdint> namespace physics_2d { class Body_2d; } namespace gom { class Game_object; } class Engine_collision_listener final : public physics_2d::Collision_listener { public: Engine_collision_listener(); void begin_body_collision(physics_2d::Body_2d * pbody_a, physics_2d::Body_2d * pbody_b) const override; void in_body_collision(physics_2d::Body_2d * pbody_a, physics_2d::Body_2d * pbody_b) const override; void end_body_collision(physics_2d::Body_2d * pbody_a, physics_2d::Body_2d * pbody_b) const override; private: void send_collision_event(gom::Game_object * pfrom_object, gom::Game_object * pto_object, std::uint32_t event_type) const; std::uint32_t m_begin_collision_id; std::uint32_t m_in_collision_id; std::uint32_t m_end_collision_id; std::uint32_t m_game_object_id; std::uint32_t m_game_object_handle_index; }; #endif // !_ENGINE_COLLISION_LISTENER_HPP
40.3125
80
0.633333
mateusgondim
62e13304ec181f0310e516012ce590692c08d901
816
cpp
C++
src/core/hooks/vmt.cpp
Metaphysical1/gamesneeze
59d31ee232bbcc80d29329e0f64ebdde599c37df
[ "MIT" ]
1,056
2020-11-17T11:49:12.000Z
2022-03-23T12:32:42.000Z
src/core/hooks/vmt.cpp
dweee/gamesneeze
99f574db2617263470280125ec78afa813f27099
[ "MIT" ]
102
2021-01-15T12:05:18.000Z
2022-02-26T00:19:58.000Z
src/core/hooks/vmt.cpp
dweee/gamesneeze
99f574db2617263470280125ec78afa813f27099
[ "MIT" ]
121
2020-11-18T12:08:21.000Z
2022-03-31T07:14:32.000Z
#include "vmt.hpp" #include <stdint.h> #include <unistd.h> #include <sys/mman.h> int pagesize = sysconf(_SC_PAGE_SIZE); int pagemask = ~(pagesize-1); int unprotect(void* region) { mprotect((void*) ((intptr_t)region & pagemask), pagesize, PROT_READ|PROT_WRITE|PROT_EXEC); return PROT_READ|PROT_EXEC; } void protect(void* region, int protection) { mprotect((void*) ((intptr_t)region & pagemask), pagesize, protection); } void* VMT::hook(void* instance, void* hook, int offset) { intptr_t vtable = *((intptr_t*)instance); intptr_t entry = vtable + sizeof(intptr_t) * offset; intptr_t original = *((intptr_t*) entry); int originalProtection = unprotect((void*)entry); *((intptr_t*)entry) = (intptr_t)hook; protect((void*)entry, originalProtection); return (void*)original; }
29.142857
94
0.689951
Metaphysical1
62e8b82ae340868a4bdd8ab29df1733b2677d8a7
6,723
hpp
C++
include/boost/numpy/dstream/detail/caller.hpp
IceCube-SPNO/BoostNumpy
66538c0b6e38e2f985e0b44d8191c878cea0332d
[ "BSL-1.0" ]
6
2015-01-07T17:29:40.000Z
2019-03-28T15:18:27.000Z
include/boost/numpy/dstream/detail/caller.hpp
IceCube-SPNO/BoostNumpy
66538c0b6e38e2f985e0b44d8191c878cea0332d
[ "BSL-1.0" ]
2
2017-04-12T19:01:21.000Z
2017-04-14T16:18:38.000Z
include/boost/numpy/dstream/detail/caller.hpp
IceCube-SPNO/BoostNumpy
66538c0b6e38e2f985e0b44d8191c878cea0332d
[ "BSL-1.0" ]
2
2018-01-15T07:32:24.000Z
2020-10-14T02:55:55.000Z
/** * $Id$ * * Copyright (C) * 2014 - $Date$ * Martin Wolf <[email protected]> * This file has been adopted from <boost/python/detail/caller.hpp>. * * @file boost/numpy/dstream/detail/caller.hpp * @version $Revision$ * @date $Date$ * @author Martin Wolf <[email protected]> * * @brief This file defines the caller template that is used as the caller * implementation for boost::python of boost::numpy generalized universal * functions. * * This file is 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). */ #if !defined(BOOST_PP_IS_ITERATING) #ifndef BOOST_NUMPY_DSTREAM_DETAIL_CALLER_HPP_INCLUDED #define BOOST_NUMPY_DSTREAM_DETAIL_CALLER_HPP_INCLUDED #include <boost/preprocessor/cat.hpp> #include <boost/preprocessor/dec.hpp> #include <boost/preprocessor/if.hpp> #include <boost/preprocessor/iterate.hpp> #include <boost/preprocessor/facilities/intercept.hpp> #include <boost/preprocessor/repetition/enum_trailing_params.hpp> #include <boost/preprocessor/repetition/enum_trailing_binary_params.hpp> #include <boost/preprocessor/repetition/repeat.hpp> #include <boost/mpl/int.hpp> #include <boost/mpl/next.hpp> #include <boost/mpl/size.hpp> // For this dedicated caller, we use function templates from the boost::python // caller. #include <boost/python/detail/caller.hpp> #include <boost/numpy/limits.hpp> namespace boost { namespace numpy { namespace dstream { namespace detail { template <unsigned> struct invoke_arity; template <unsigned> struct caller_arity; // The +1 is for the class instance and the +2 is for the possible automatically // added extra arguments ("out" and "nthreads"). // The minimum input arity is forced to be 1 instead of 0 because a vectorized // function with no input is just non-sense. #define BOOST_PP_ITERATION_PARAMS_1 \ (3, (1, BOOST_NUMPY_LIMIT_INPUT_ARITY + 1 + 2, <boost/numpy/dstream/detail/caller.hpp>)) #include BOOST_PP_ITERATE() template <class Callable> struct caller_base_select { // Note: arity includes the class type if Callable::f_t is a member function // pointer. BOOST_STATIC_CONSTANT(unsigned, arity = boost::mpl::size<typename Callable::signature_t>::value - 1); typedef typename caller_arity<arity>::template impl<Callable> type; }; template <class Callable> struct caller : caller_base_select<Callable>::type { typedef typename caller_base_select<Callable>::type base; caller(Callable ca) : base(ca) {} }; }// namespace detail }// namespace dstream }// namespace numpy }// namespace boost #endif // ! BOOST_NUMPY_DSTREAM_DETAIL_CALLER_HPP_INCLUDED #else #define N BOOST_PP_ITERATION() template <> struct invoke_arity<N> { template <class RC, class Callable BOOST_PP_ENUM_TRAILING_PARAMS_Z(1, N, class AC)> inline static PyObject* invoke(RC const& rc, Callable const & ca BOOST_PP_ENUM_TRAILING_BINARY_PARAMS_Z(1, N, AC, & ac)) { return rc( ca(BOOST_PP_ENUM_BINARY_PARAMS_Z(1, N, ac, () BOOST_PP_INTERCEPT)) ); } }; template <> struct caller_arity<N> { template <class Callable> struct impl { // Since we will always take Python objects as arguments and return // Python objects, we will always use the default_call_policies as call // policies. typedef python::default_call_policies call_policies_t; impl(Callable ca) : m_callable(ca) {} PyObject* operator()(PyObject* args_, PyObject*) // eliminate // this // trailing // keyword dict { call_policies_t call_policies; typedef typename boost::mpl::begin<typename Callable::signature_t>::type first; //typedef typename first::type result_t; typedef typename python::detail::select_result_converter<call_policies_t, python::object>::type result_converter_t; typedef typename call_policies_t::argument_package argument_package_t; // Create argument from_python converter objects c#. argument_package_t inner_args(args_); #define BOOST_NUMPY_NEXT(init, name, n) \ typedef BOOST_PP_IF(n,typename boost::mpl::next< BOOST_PP_CAT(name,BOOST_PP_DEC(n)) >::type, init) name##n; #define BOOST_NUMPY_ARG_CONVERTER(n) \ BOOST_NUMPY_NEXT(typename boost::mpl::next<first>::type, arg_iter,n) \ typedef python::arg_from_python<BOOST_DEDUCED_TYPENAME BOOST_PP_CAT(arg_iter,n)::type> BOOST_PP_CAT(c_t,n); \ BOOST_PP_CAT(c_t,n) BOOST_PP_CAT(c,n)(python::detail::get(boost::mpl::int_<n>(), inner_args)); \ if(!BOOST_PP_CAT(c,n).convertible()) { \ return 0; \ } #define BOOST_NUMPY_DEF(z, n, data) \ BOOST_NUMPY_ARG_CONVERTER(n) BOOST_PP_REPEAT(N, BOOST_NUMPY_DEF, ~) #undef BOOST_NUMPY_DEF #undef BOOST_NUMPY_ARG_CONVERTER #undef BOOST_NUMPY_NEXT // All converters have been checked. Now we can do the // precall part of the policy. // Note: The precall of default_call_policies does nothing at all as // of boost::python <=1.55 but we keep this call for forward // compatibility and to follow the interface definition. if(!call_policies.precall(inner_args)) return 0; PyObject* result = invoke_arity<N>::invoke( python::detail::create_result_converter(args_, (result_converter_t*)0, (result_converter_t*)0) , m_callable BOOST_PP_ENUM_TRAILING_PARAMS(N, c) ); // Note: the postcall of default_call_policies does nothing at all // as of boost::python <=1.55 but we keep this call for // forward compatibility and to follow the interface // definition. return call_policies.postcall(inner_args, result); } static unsigned min_arity() { return N; } private: Callable m_callable; }; }; #undef N #endif // BOOST_PP_IS_ITERATING
34.834197
125
0.62844
IceCube-SPNO
62ecbe261582bd004825d91639ba33c012f6258a
2,604
cpp
C++
SysLib/Demand/Files/Matrix_File.cpp
kravitz/transims4
ea0848bf3dc71440d54724bb3ecba3947b982215
[ "NASA-1.3" ]
2
2018-04-27T11:07:02.000Z
2020-04-24T06:53:21.000Z
SysLib/Demand/Files/Matrix_File.cpp
idkravitz/transims4
ea0848bf3dc71440d54724bb3ecba3947b982215
[ "NASA-1.3" ]
null
null
null
SysLib/Demand/Files/Matrix_File.cpp
idkravitz/transims4
ea0848bf3dc71440d54724bb3ecba3947b982215
[ "NASA-1.3" ]
null
null
null
//********************************************************* // Matrix_File.cpp - Matrix File Input/Output //********************************************************* #include "Matrix_File.hpp" //----------------------------------------------------------- // Matrix_File constructors //----------------------------------------------------------- Matrix_File::Matrix_File (Access_Type access, Format_Type format) : Db_Header (access, format) { Setup (); } Matrix_File::Matrix_File (char *filename, Access_Type access, Format_Type format) : Db_Header (access, format) { Setup (); Open (filename); } //----------------------------------------------------------- // Matrix_File destructor //----------------------------------------------------------- Matrix_File::~Matrix_File (void) { } //----------------------------------------------------------- // Setup //----------------------------------------------------------- void Matrix_File::Setup (void) { File_Type ("Matrix File"); File_ID ("Matrix"); Period_Flag (false); org = des = period = data = 0; } //--------------------------------------------------------- // Create_Fields //--------------------------------------------------------- bool Matrix_File::Create_Fields (void) { if (Dbase_Format () == VERSION3) { Header_Lines (0); } Add_Field ("ORG", INTEGER, 5); Add_Field ("DES", INTEGER, 5); if (Period_Flag ()) { Add_Field ("PERIOD", INTEGER, 3); } Add_Field ("DATA", INTEGER, 10); return (Set_Field_Numbers ()); } //----------------------------------------------------------- // Set_Field_Numbers //----------------------------------------------------------- bool Matrix_File::Set_Field_Numbers (void) { //---- required fields ---- org = Required_Field ("ORG", "ORIGIN", "FROM", "FROM_ZONE", "I"); des = Required_Field ("DES", "DESTINATION", "TO", "TO_ZONE", "J"); if (!org || !des) return (false); //---- optional fields ---- period = Optional_Field ("PERIOD", "INTERVAL"); period_flag = (period != 0); data = Optional_Field ("DATA", "TRIPS"); if (data == 0) { if (Num_Fields () > 2 && org == 1 && des == 2) { if (period == 3) { data = 4; } else { data = 3; } } else { Required_Field ("DATA", "TRIPS"); return (false); } } return (true); } //----------------------------------------------------------- // Default_Definition //----------------------------------------------------------- bool Matrix_File::Default_Definition (void) { if (Dbase_Format () == VERSION3) { Create_Fields (); return (Write_Def_Header (NULL)); } else { return (false); } }
22.448276
84
0.422043
kravitz
62eed194e14ec20219bfcc92913587fb6ffc1fd7
9,451
cc
C++
dcmtk-master2/dcmsr/libsrc/dsrtpltn.cc
happymanx/Weather_FFI
a7f9bf8f1bda2b50c9d9a875c08fccf58379ad9f
[ "MIT" ]
null
null
null
dcmtk-master2/dcmsr/libsrc/dsrtpltn.cc
happymanx/Weather_FFI
a7f9bf8f1bda2b50c9d9a875c08fccf58379ad9f
[ "MIT" ]
null
null
null
dcmtk-master2/dcmsr/libsrc/dsrtpltn.cc
happymanx/Weather_FFI
a7f9bf8f1bda2b50c9d9a875c08fccf58379ad9f
[ "MIT" ]
null
null
null
/* * * Copyright (C) 2015-2018, J. Riesmeier, Oldenburg, Germany * All rights reserved. See COPYRIGHT file for details. * * This software and supporting documentation are maintained by * * OFFIS e.V. * R&D Division Health * Escherweg 2 * D-26121 Oldenburg, Germany * * * Module: dcmsr * * Author: Joerg Riesmeier * * Purpose: * classes: DSRIncludedTemplateTreeNode * */ #include "dcmtk/config/osconfig.h" /* make sure OS specific configuration is included first */ #include "dcmtk/dcmsr/dsrtypes.h" #include "dcmtk/dcmsr/dsrtpltn.h" #include "dcmtk/dcmsr/dsrstpl.h" #include "dcmtk/dcmsr/dsrxmld.h" DSRIncludedTemplateTreeNode::DSRIncludedTemplateTreeNode(const DSRSharedSubTemplate &referencedTemplate, const E_RelationshipType defaultRelType) : DSRDocumentTreeNode(defaultRelType, VT_includedTemplate), ReferencedTemplate(referencedTemplate) { if (ReferencedTemplate) { /* store template identification of the referenced template */ DSRDocumentTreeNode::setTemplateIdentification(ReferencedTemplate->getTemplateIdentifier(), ReferencedTemplate->getMappingResource(), ReferencedTemplate->getMappingResourceUID()); } } DSRIncludedTemplateTreeNode::DSRIncludedTemplateTreeNode(const DSRIncludedTemplateTreeNode &node) : DSRDocumentTreeNode(node), ReferencedTemplate(node.ReferencedTemplate) { } DSRIncludedTemplateTreeNode::~DSRIncludedTemplateTreeNode() { } OFBool DSRIncludedTemplateTreeNode::operator==(const DSRDocumentTreeNode &node) const { /* call comparison operator of base class (includes check of value type) */ OFBool result = DSRDocumentTreeNode::operator==(node); if (result) { /* it's safe to cast the type since the value type has already been checked */ result = (ReferencedTemplate.get() == OFstatic_cast(const DSRIncludedTemplateTreeNode &, node).ReferencedTemplate.get()); } return result; } OFBool DSRIncludedTemplateTreeNode::operator!=(const DSRDocumentTreeNode &node) const { /* call comparison operator of base class (includes check of value type) */ OFBool result = DSRDocumentTreeNode::operator!=(node); if (!result) { /* it's safe to cast the type since the value type has already been checked */ result = (ReferencedTemplate.get() != OFstatic_cast(const DSRIncludedTemplateTreeNode &, node).ReferencedTemplate.get()); } return result; } DSRIncludedTemplateTreeNode *DSRIncludedTemplateTreeNode::clone() const { return new DSRIncludedTemplateTreeNode(*this); } void DSRIncludedTemplateTreeNode::clear() { DSRDocumentTreeNode::clear(); ReferencedTemplate.reset(); } OFBool DSRIncludedTemplateTreeNode::isValid() const { return DSRDocumentTreeNode::isValid() && hasValidValue(); } OFBool DSRIncludedTemplateTreeNode::hasValidValue() const { /* check whether the reference to the included template is valid */ return ReferencedTemplate ? OFTrue : OFFalse; } OFBool DSRIncludedTemplateTreeNode::isShort(const size_t /*flags*/) const { return !hasValidValue(); } OFCondition DSRIncludedTemplateTreeNode::print(STD_NAMESPACE ostream &stream, const size_t flags) const { stream << "# INCLUDE "; /* check whether template identification is set */ if (hasTemplateIdentification()) { OFString templateIdentifier, mappingResource; getTemplateIdentification(templateIdentifier, mappingResource); stream << "TID " << templateIdentifier << " (" << mappingResource << ")"; } else { /* no details on the template available */ stream << "<unknown template>"; } /* check whether default relationship type is specified */ if (getRelationshipType() != RT_unknown) stream << " with default relationship type " << relationshipTypeToDefinedTerm(getRelationshipType()); /* print annotation (optional) */ if (hasAnnotation() && (flags & PF_printAnnotation)) stream << " \"" << getAnnotation().getText() << "\""; return EC_Normal; } OFCondition DSRIncludedTemplateTreeNode::writeXML(STD_NAMESPACE ostream &stream, const size_t flags) const { OFCondition result = EC_Normal; /* write content of included template in XML format (if non-empty) */ if (hasValidValue() && !ReferencedTemplate->isEmpty()) { OFString templateIdentifier, mappingResource; /* output details on beginning of included template (if enabled) */ if (hasTemplateIdentification() && (flags & XF_addCommentsForIncludedTemplate)) { getTemplateIdentification(templateIdentifier, mappingResource); stream << "<!-- BEGIN: included template TID " << templateIdentifier << " (" << mappingResource << ") -->" << OFendl; } /* write content of referenced document subtree */ result = ReferencedTemplate->writeXML(stream, flags); /* output details on end of included template (if available, see above) */ if (!templateIdentifier.empty() && !mappingResource.empty()) stream << "<!-- END: included template TID " << templateIdentifier << " (" << mappingResource << ") -->" << OFendl; } return result; } OFCondition DSRIncludedTemplateTreeNode::setValue(const DSRSharedSubTemplate &referencedTemplate) { ReferencedTemplate = referencedTemplate; /* currently, no checks are performed */ return EC_Normal; } // protected methods OFCondition DSRIncludedTemplateTreeNode::read(DcmItem & /*dataset*/, const DSRIODConstraintChecker * /*constraintChecker*/, const size_t /*flags*/) { /* invalid: cannot read document with included templates */ return SR_EC_CannotProcessIncludedTemplates; } OFCondition DSRIncludedTemplateTreeNode::write(DcmItem & /*dataset*/, DcmStack * /*markedItems*/) { /* invalid: cannot write document with included templates */ return SR_EC_CannotProcessIncludedTemplates; } OFCondition DSRIncludedTemplateTreeNode::readXML(const DSRXMLDocument & /*doc*/, DSRXMLCursor /*cursor*/, const E_DocumentType /*documentType*/, const size_t /*flags*/) { /* invalid: cannot read document with included templates */ return SR_EC_CannotProcessIncludedTemplates; } OFCondition DSRIncludedTemplateTreeNode::renderHTML(STD_NAMESPACE ostream & /*docStream*/, STD_NAMESPACE ostream & /*annexStream*/, const size_t /*nestingLevel*/, size_t & /*annexNumber*/, const size_t /*flags*/) const { /* invalid: cannot render document with included templates */ return SR_EC_CannotProcessIncludedTemplates; } OFCondition DSRIncludedTemplateTreeNode::setConceptName(const DSRCodedEntryValue & /*conceptName*/, const OFBool /*check*/) { /* invalid: no concept name allowed */ return EC_IllegalCall; } OFCondition DSRIncludedTemplateTreeNode::setObservationDateTime(const OFString & /*observationDateTime*/, const OFBool /*check*/) { /* invalid: no observation date/time allowed */ return EC_IllegalCall; } OFCondition DSRIncludedTemplateTreeNode::setObservationDateTime(const DcmElement & /*delem*/, const unsigned long /*pos*/, const OFBool /*check*/) { /* invalid: no observation date/time allowed */ return EC_IllegalCall; } OFCondition DSRIncludedTemplateTreeNode::setObservationDateTime(DcmItem & /*dataset*/, const DcmTagKey & /*tagKey*/, const unsigned long /*pos*/, const OFBool /*check*/) { /* invalid: no observation date/time allowed */ return EC_IllegalCall; } OFCondition DSRIncludedTemplateTreeNode::setObservationUID(const OFString & /*observationUID*/, const OFBool /*check*/) { /* invalid: no observation unique identifier allowed */ return EC_IllegalCall; } OFCondition DSRIncludedTemplateTreeNode::setTemplateIdentification(const OFString & /*templateIdentifier*/, const OFString & /*mappingResource*/, const OFString & /*mappingResourceUID*/, const OFBool /*check*/) { /* invalid: no manual setting of template identification allowed */ return EC_IllegalCall; }
35.799242
129
0.611575
happymanx
62f8a945d1122a19d6a5aba08b02631a769d9347
2,742
cpp
C++
texture_handler.cpp
paracelso93/rocket-simulator
746469b2ffea032bed5793ef499eba0cd443240d
[ "MIT" ]
null
null
null
texture_handler.cpp
paracelso93/rocket-simulator
746469b2ffea032bed5793ef499eba0cd443240d
[ "MIT" ]
null
null
null
texture_handler.cpp
paracelso93/rocket-simulator
746469b2ffea032bed5793ef499eba0cd443240d
[ "MIT" ]
null
null
null
#include "texture_handler.h" TextureHandler* TextureHandler::mInstance = nullptr; bool TextureHandler::add_texture(const std::string& filePath, texture_t& id, SDL_Renderer* renderer) { id = std::hash<std::string>()(filePath); if (mTextures.find(id) != mTextures.end()) { return true; } SDL_Surface* sur = IMG_Load(filePath.c_str()); LOG(sur, "load surface " + filePath); SDL_Texture* tex = SDL_CreateTextureFromSurface(renderer, sur); LOG(tex, "create texture " + filePath); mTextures[id] = tex; int w, h; SDL_QueryTexture(mTextures[id], nullptr, nullptr, &w, &h); //mSizes[id] = Vector2<float>(w, h); mSizes.insert(std::pair<texture_t, Vector2<float> >(id, Vector2<float>(w, h))); mSizes.insert(std::pair<texture_t, Vector2<float> >(id, Vector2<float>(0, 0))); return true; } SDL_Texture* TextureHandler::get_texture(texture_t id) { if (mTextures.find(id) != mTextures.end()) { return mTextures[id]; } std::cerr << "Unable to load " << std::to_string(id) << std::endl; return nullptr; } void TextureHandler::render(SDL_Renderer* renderer, texture_t id, const Vector2<float>& position, const Vector2<float>& scale, float rotation, const Vector2<float>& center, SDL_RendererFlip flip) { if (mTextures.find(id) == mTextures.end()) { std::cerr << "texture " << std::to_string(id) << " doesn't exists!" << std::endl; return; } SDL_Rect src; src.x = mPositions[id].x; src.y = mPositions[id].y; src.w = mSizes[id].x; src.h = mSizes[id].y; SDL_Rect dst; dst.x = position.x; dst.y = position.y; dst.w = mSizes[id].x * scale.x; dst.h = mSizes[id].y * scale.y; SDL_Point cen; cen.x = center.x; cen.y = center.y; SDL_RenderCopyEx(renderer, mTextures[id], &src, &dst, rotation, &cen, flip); } void TextureHandler::set_src_rect(texture_t id, const Vector2<float>& src) { if (mTextures.find(id) == mTextures.end()) { std::cerr << "texture " << std::to_string(id) << " doesn't exists!" << std::endl; return; } mSizes[id] = src; } void TextureHandler::set_src_position(texture_t id, const Vector2<float>& src) { if (mTextures.find(id) == mTextures.end()) { std::cerr << "texture " << std::to_string(id) << " doesn't exists!" << std::endl; return; } mPositions[id] = src; } bool TextureHandler::point_in_texture(const Vector2<float>& point, const Vector2<float>& position, texture_t id) { if (mTextures.find(id) == mTextures.end()) { std::cerr << "texture " << std::to_string(id) << " doesn't exists!" << std::endl; return false; } int w, h; SDL_QueryTexture(mTextures[id], nullptr, nullptr, &w, &h); return point_in_rectangle(point, position, Vector2<float>(static_cast<float>(w), static_cast<float>(h))); }
30.808989
197
0.659373
paracelso93
62fbaca3bfaa78e541b1665b57744139a23cba24
1,223
cpp
C++
318. Maximum Product of Word Lengths.cpp
rajeev-ranjan-au6/Leetcode_Cpp
f64cd98ab96ec110f1c21393f418acf7d88473e8
[ "MIT" ]
3
2020-12-30T00:29:59.000Z
2021-01-24T22:43:04.000Z
318. Maximum Product of Word Lengths.cpp
rajeevranjancom/Leetcode_Cpp
f64cd98ab96ec110f1c21393f418acf7d88473e8
[ "MIT" ]
null
null
null
318. Maximum Product of Word Lengths.cpp
rajeevranjancom/Leetcode_Cpp
f64cd98ab96ec110f1c21393f418acf7d88473e8
[ "MIT" ]
null
null
null
// Solution 1. Straight forward, 165ms class Solution { public: int maxProduct(vector<string>& words) { int maxlen = 0; for(int i = 0; i < words.size(); i++) for(int j = i + 1; j < words.size(); j++){ if(words[i].size() * words[j].size() <= maxlen) continue; if(noCommon(words[i], words[j])) maxlen = max(maxlen, (int)(words[i].size() * words[j].size())); } return maxlen; } bool noCommon(string& a, string& b){ for(auto x: a) for(auto y: b) if(x == y) return false; return true; } }; // Solution 2. Bit Manipulation, 43ms class Solution { public: int maxProduct(vector<string>& words) { int maxlen = 0; vector<int>val(words.size()); for(int i = 0; i < words.size(); i++) for(auto c: words[i]) val[i] |= (1 << (c - 'a')); for(int i = 0; i < words.size(); i++) for(int j = i + 1; j < words.size(); j++) if((val[i] & val[j]) == 0 && words[i].size() * words[j].size() > maxlen) maxlen = max(maxlen, (int)(words[i].size() * words[j].size())); return maxlen; } };
32.184211
112
0.472608
rajeev-ranjan-au6
62fdd32bf4578aadeef43d6531ee0cdb52538338
2,264
hh
C++
include/io/ssl.hh
king1600/Valk
b376a0dcce522ae03ced7d882835e4dea98df86e
[ "MIT" ]
null
null
null
include/io/ssl.hh
king1600/Valk
b376a0dcce522ae03ced7d882835e4dea98df86e
[ "MIT" ]
null
null
null
include/io/ssl.hh
king1600/Valk
b376a0dcce522ae03ced7d882835e4dea98df86e
[ "MIT" ]
null
null
null
#pragma once #include <boost/asio.hpp> #include <boost/asio/ssl.hpp> #include <boost/asio/ip/tcp.hpp> namespace io { namespace asio = boost::asio; namespace ssl = asio::ssl; typedef asio::ip::tcp tcp; typedef boost::system::error_code error_code; static const error_code Success = boost::system::errc::make_error_code( boost::system::errc::success); class Timer { private: asio::deadline_timer timer; std::function<void(Timer*)> timer_cb; public: void *data; Timer(asio::io_service& service); void cancel(); void async(const long ms, const std::function<void(Timer*)> &cb); }; class Service { private: std::shared_ptr<tcp::resolver> resolver; std::shared_ptr<ssl::context> ssl_ctx; std::shared_ptr<asio::io_service> loop; public: Service(); void Run(); ssl::context& getContext(); asio::io_service& getService(); Timer* createTimer(); Timer* spawn(const long ms, void *data, const std::function<void(Timer*)> &cb); void Resolve(const std::string &host, int port, std::function<void(const error_code&, tcp::resolver::iterator)> cb); }; class SSLClient { private: Service &service; bool connected = false; std::vector<char> builder; std::array<char, 8192> buffer; std::shared_ptr<ssl::stream<tcp::socket>> sock; std::function<void(const error_code&)> on_close; std::function<void(const error_code&)> on_connect; std::function<void(const std::vector<char>&)> on_read; void _read_handler(const error_code&, std::size_t); void _connect_handler(const error_code&, tcp::resolver::iterator, std::function<void(const error_code&)> callback); void _connect(const tcp::endpoint&, tcp::resolver::iterator&, std::function<void(const error_code&)> callback); public: SSLClient(Service& loop); void Connect(const std::string& host, int port); void Send(const char* data, const std::size_t len); void Close(const error_code& err, bool callback = true); const bool isConnected() const; void onClose(std::function<void(const error_code&)>); void onConnect(std::function<void(const error_code&)>); void onRead(std::function<void(const std::vector<char>&)>); }; }
28.3
83
0.673587
king1600
1a058f089c816fe656fccfdf5b0d50e4ca781b28
2,870
cpp
C++
src/CAN/CANMotor_PSOC.cpp
huskyroboticsteam/Resurgence
649f78103b6d76709fdf55bb38d08c0ff50da140
[ "Apache-2.0" ]
3
2021-12-23T23:31:42.000Z
2022-02-16T07:17:41.000Z
src/CAN/CANMotor_PSOC.cpp
huskyroboticsteam/Resurgence
649f78103b6d76709fdf55bb38d08c0ff50da140
[ "Apache-2.0" ]
2
2021-11-22T05:33:43.000Z
2022-01-23T07:01:47.000Z
src/CAN/CANMotor_PSOC.cpp
huskyroboticsteam/Resurgence
649f78103b6d76709fdf55bb38d08c0ff50da140
[ "Apache-2.0" ]
null
null
null
#include "CAN.h" #include "CANMotor.h" #include "CANUtils.h" #include <chrono> #include <cmath> #include <condition_variable> #include <mutex> #include <queue> #include <thread> #include <vector> extern "C" { #include "../HindsightCAN/CANCommon.h" #include "../HindsightCAN/CANMotorUnit.h" #include "../HindsightCAN/CANPacket.h" } using namespace std::chrono_literals; using std::chrono::milliseconds; namespace can::motor { namespace { using clock = std::chrono::steady_clock; using timepoint_t = std::chrono::time_point<clock>; struct telemschedule_t { timepoint_t nextSendTime; milliseconds telemPeriod; deviceserial_t serial; }; bool operator<(const telemschedule_t& t1, const telemschedule_t& t2) { return t1.nextSendTime < t2.nextSendTime; } std::priority_queue<telemschedule_t> telemetrySchedule; bool startedMotorThread = false; bool newMotorAdded = false; std::condition_variable motorsCV; std::mutex motorsMutex; // protects telemetrySchedule, startedMotorThread, newMotorAdded void motorThreadFn() { while (true) { std::unique_lock lock(motorsMutex); if (telemetrySchedule.empty()) { motorsCV.wait(lock, [] { return newMotorAdded; }); newMotorAdded = false; } else { auto now = clock::now(); auto ts = telemetrySchedule.top(); if (ts.nextSendTime <= now) { telemetrySchedule.pop(); pullMotorPosition(ts.serial); telemetrySchedule.push( {ts.nextSendTime + ts.telemPeriod, ts.telemPeriod, ts.serial}); } else { motorsCV.wait_until(lock, ts.nextSendTime, [] { return newMotorAdded; }); newMotorAdded = false; } } } } void startMonitoringMotor(deviceserial_t motor, std::chrono::milliseconds period) { { std::unique_lock lock(motorsMutex); if (!startedMotorThread) { startedMotorThread = true; std::thread motorThread(motorThreadFn); motorThread.detach(); } telemetrySchedule.push({clock::now(), period, motor}); newMotorAdded = true; } motorsCV.notify_one(); } } // namespace void initEncoder(deviceserial_t serial, bool invertEncoder, bool zeroEncoder, int32_t pulsesPerJointRev, std::optional<std::chrono::milliseconds> telemetryPeriod) { auto motorGroupCode = static_cast<uint8_t>(devicegroup_t::motor); CANPacket p; AssembleEncoderInitializePacket(&p, motorGroupCode, serial, sensor_t::encoder, invertEncoder, zeroEncoder); sendCANPacket(p); std::this_thread::sleep_for(1000us); AssembleEncoderPPJRSetPacket(&p, motorGroupCode, serial, pulsesPerJointRev); sendCANPacket(p); std::this_thread::sleep_for(1000us); if (telemetryPeriod) { startMonitoringMotor(serial, telemetryPeriod.value()); } } void pullMotorPosition(deviceserial_t serial) { CANPacket p; AssembleTelemetryPullPacket(&p, static_cast<uint8_t>(devicegroup_t::motor), serial, static_cast<uint8_t>(telemtype_t::angle)); sendCANPacket(p); } } // namespace can::motor
27.596154
91
0.74216
huskyroboticsteam
1a05fd4f32bf7ac9e3f364b003d152b41f41516b
2,184
cpp
C++
Hello 2019/c.cpp
anirudha-ani/Codeforces
6c7f64257939d44b1c2ec9dd202f1c9f899f1cad
[ "Apache-2.0" ]
null
null
null
Hello 2019/c.cpp
anirudha-ani/Codeforces
6c7f64257939d44b1c2ec9dd202f1c9f899f1cad
[ "Apache-2.0" ]
null
null
null
Hello 2019/c.cpp
anirudha-ani/Codeforces
6c7f64257939d44b1c2ec9dd202f1c9f899f1cad
[ "Apache-2.0" ]
null
null
null
#include <bits/stdc++.h> using namespace std ; int main() { stack <char> data; char input[500005]; int n ; scanf("%d", &n); map <int , int> marking ; int balanced= 0 ; long long int ans = 0 ; for(int i = 0 ; i < n ; i++) { scanf("%s", input); int k = 0 ; int score = 0 ; stack <char> store ; //cout <<"HE" << endl ; while(input[k] != '\0') { //cout << input[k] << endl ; if(input[k] == '(') { store.push(input[k]); //cout << "1" << endl ; } else { if(!store.empty() && store.top() == '(') { store.pop(); //cout << "2" << endl; } else { store.push(input[k]); //cout << "3" << endl ; } } //cout << k << endl ; k++; } if(store.size() == 0) { balanced++; } else { bool possible = true; char init = store.top() ; store.pop(); if(init == '(') { score++; } else score--; //cout << "HERE" << endl ; while(!store.empty()) { if(store.top() != init) { possible = false ; break; } else if(store.top() == '(') { score++; } else score--; store.pop(); } if(!possible) continue; else if(marking[score * -1] > 0) { marking[score * -1] = marking[score * -1] - 1 ; ans++ ; } else { marking[score] = marking[score] + 1 ; } } } ans += balanced/2; printf("%lld\n", ans); return 0 ; }
24
64
0.287088
anirudha-ani
1a0823730e616552e21f820c37d0889c43151bc6
1,769
cpp
C++
codes/POJ/poj3468.cpp
JeraKrs/ACM
edcd61ec6764b8cd804bf1538dfde53d0ff572b5
[ "Apache-2.0" ]
null
null
null
codes/POJ/poj3468.cpp
JeraKrs/ACM
edcd61ec6764b8cd804bf1538dfde53d0ff572b5
[ "Apache-2.0" ]
null
null
null
codes/POJ/poj3468.cpp
JeraKrs/ACM
edcd61ec6764b8cd804bf1538dfde53d0ff572b5
[ "Apache-2.0" ]
null
null
null
#include <cstdio> #include <cstring> #include <algorithm> using namespace std; #define lson(x) ((x)<<1) #define rson(x) (((x)<<1)+1) const int maxn = 100005; typedef long long ll; struct Node { int l, r; ll sum, add; void set (int l, int r, ll sum, ll add) { this->l = l; this->r = r; this->sum = sum; this->add = add; } void maintain (ll v) { sum += (r - l + 1) * v; add += v; } }nd[maxn * 4]; int N, Q, A[maxn]; void pushup (int u) { nd[u].sum = nd[lson(u)].sum + nd[rson(u)].sum; } void pushdown(int u) { if (nd[u].add) { nd[lson(u)].maintain(nd[u].add); nd[rson(u)].maintain(nd[u].add); nd[u].add = 0; } } void build (int u, int l, int r) { nd[u].l = l; nd[u].r = r; nd[u].add = 0; if (l == r) { nd[u].sum = A[l]; return; } int mid = (l + r) / 2; build(lson(u), l, mid); build(rson(u), mid + 1, r); pushup(u); } ll query(int u, int l, int r) { if (l <= nd[u].l && nd[u].r <= r) return nd[u].sum; pushdown(u); ll ret = 0; int mid = (nd[u].l + nd[u].r) / 2; if (l <= mid) ret += query(lson(u), l, r); if (r > mid) ret += query(rson(u), l, r); pushup(u); return ret; } void modify (int u, int l, int r, int v) { if (l <= nd[u].l && nd[u].r <= r) { nd[u].maintain(v); return; } pushdown(u); int mid = (nd[u].l + nd[u].r) / 2; if (l <= mid) modify(lson(u), l, r, v); if (r > mid) modify(rson(u), l, r, v); pushup(u); } int main () { while (scanf("%d%d", &N, &Q) == 2) { for (int i = 1; i <= N; i++) scanf("%d", &A[i]); build(1, 1, N); int l, r, v; char order[5]; for (int i = 0; i < Q; i++) { scanf("%s%d%d", order, &l, &r); if (order[0] == 'Q') printf("%lld\n", query(1, l, r)); else { scanf("%d", &v); modify(1, l, r, v); } } } return 0; }
16.229358
47
0.487846
JeraKrs
1a0ed3e7186d638471d1b6fd0a646abe72bf17ce
871
cpp
C++
Binary Tree/Ancestors_Of_A_Node.cpp
susantabiswas/placementPrep
22a7574206ddc63eba89517f7b68a3d2f4d467f5
[ "MIT" ]
19
2018-12-02T05:59:44.000Z
2021-07-24T14:11:54.000Z
Binary Tree/Ancestors_Of_A_Node.cpp
susantabiswas/placementPrep
22a7574206ddc63eba89517f7b68a3d2f4d467f5
[ "MIT" ]
null
null
null
Binary Tree/Ancestors_Of_A_Node.cpp
susantabiswas/placementPrep
22a7574206ddc63eba89517f7b68a3d2f4d467f5
[ "MIT" ]
13
2019-04-25T16:20:00.000Z
2021-09-06T19:50:04.000Z
//Print all the ancestors of a given node #include<iostream> using namespace std; struct Node { int data; Node *left; Node *right; }; //creates a node Node* create(int data) { try { Node *node=new Node; node->data=data; node->left=NULL; node->right=NULL; return node; } catch(bad_alloc xa) { cout<<"Memory overflow!!"; return NULL; } } //prints all the ancestors of a gievn key node bool printAncestors(Node *root,int key) { if(root==NULL) return false; if(root->data==key) return true; if(printAncestors(root->left,key)||printAncestors(root->right,key)) { cout<<root->data<<" "; return true; } else false; } int main() { Node *root=create(1); root->left=create(2); root->right=create(3); root->left->left=create(4); root->right->right=create(6); root->left->right=create(5); if(printAncestors(root,4)); return 0; }
14.278689
68
0.657865
susantabiswas
1a0ff312380fc1200503bb7f17cbbec9408ee287
404
hpp
C++
examples/rucksack/testbed/include/sge/rucksack/testbed/object_impl_fwd.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
2
2016-01-27T13:18:14.000Z
2018-05-11T01:11:32.000Z
examples/rucksack/testbed/include/sge/rucksack/testbed/object_impl_fwd.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
null
null
null
examples/rucksack/testbed/include/sge/rucksack/testbed/object_impl_fwd.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
3
2018-05-11T01:11:34.000Z
2021-04-24T19:47:45.000Z
// Copyright Carl Philipp Reh 2006 - 2019. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef SGE_RUCKSACK_TESTBED_OBJECT_IMPL_FWD_HPP_INCLUDED #define SGE_RUCKSACK_TESTBED_OBJECT_IMPL_FWD_HPP_INCLUDED namespace sge::rucksack::testbed { class object_impl; } #endif
23.764706
61
0.759901
cpreh
1a10a79e16490f9837cc80b4d97b6cc4c35fa011
835
cpp
C++
streambox/WinKeyReducer/WinKeyReducerEval-yahoo-winbundle.cpp
chenzongxiong/streambox
76f95780d1bf6c02731e39d8ac73937cea352b95
[ "Unlicense" ]
3
2019-07-03T14:03:31.000Z
2021-12-19T10:18:49.000Z
streambox/WinKeyReducer/WinKeyReducerEval-yahoo-winbundle.cpp
chenzongxiong/streambox
76f95780d1bf6c02731e39d8ac73937cea352b95
[ "Unlicense" ]
6
2020-02-17T12:01:30.000Z
2021-12-09T22:02:33.000Z
streambox/WinKeyReducer/WinKeyReducerEval-yahoo-winbundle.cpp
chenzongxiong/streambox
76f95780d1bf6c02731e39d8ac73937cea352b95
[ "Unlicense" ]
2
2020-12-03T04:41:18.000Z
2021-01-11T21:44:42.000Z
// // Created by manuelrenz on 12.04.18. // #include "WinKeyReducerEval.h" /* ----------------------------------------- * specialized for yahoo -- using normal hashtable * NB: we have to do full specialization per C++ * ----------------------------------------- */ // using MyWinKeyReduerEval = WinKeyReducerEval<std::pair<uint64_t, long>, /* kv in */ // WinKeyFragLocal_Std, WinKeyFrag_Std, /* internal map format */ // std::pair<uint64_t, long>, /* kvout */ // WindowsBundle /* output bundle */ // >; using MyWinKeyReduerEval = WinKeyReducerEval<std::pair<uint64_t, uint64_t>, /* kv in */ WinKeyFragLocal_Std, WinKeyFrag_Std, /* internal map format */ std::pair<uint64_t, uint64_t>, /* kvout */ WindowsBundle /* output bundle */ >; #include "WinKeyReducerEval-yahoo-common.h"
32.115385
87
0.590419
chenzongxiong
1a150466293290bde2678ab09e37514c5e673198
594
cpp
C++
LeetCode/0003.LongestSubstringWithoutRepeatingCharacters/LSWRC.cpp
luspock/algorithms
91644427f3f683481f911f6bc30c9eeb19934cdd
[ "MIT" ]
1
2017-12-24T07:51:07.000Z
2017-12-24T07:51:07.000Z
LeetCode/0003.LongestSubstringWithoutRepeatingCharacters/LSWRC.cpp
luspock/algorithms
91644427f3f683481f911f6bc30c9eeb19934cdd
[ "MIT" ]
null
null
null
LeetCode/0003.LongestSubstringWithoutRepeatingCharacters/LSWRC.cpp
luspock/algorithms
91644427f3f683481f911f6bc30c9eeb19934cdd
[ "MIT" ]
null
null
null
#include <unordered_map> #include <iostream> #include <string> int lengthOfLongestSubstring(std::string s){ std::unordered_map<char, int> smap; int n = s.length(); int max_length = 0; if(n<2){ return n; } for(int i=0,j=0;j<n;++j){ char c = s.at(j); if(smap.count(c)){ i=smap[c]>i?smap[c]:i; } smap[c]=j+1; max_length = max_length<(j-i+1)?(j-i+1):max_length; } return max_length; }; int main(int argc, char **argv){ std::string test_s = "pwwerkw"; std::cout<< test_s<<"\n"; std::cout<<lengthOfLongestSubstring(test_s)<<"\n"; return 0; };
20.482759
54
0.60101
luspock
1a19c14e380f519b3eedb83c76f7ee7dcd473c07
57
hpp
C++
src/boost_fusion_view_filter_view_filter_view.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
10
2018-03-17T00:58:42.000Z
2021-07-06T02:48:49.000Z
src/boost_fusion_view_filter_view_filter_view.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
2
2021-03-26T15:17:35.000Z
2021-05-20T23:55:08.000Z
src/boost_fusion_view_filter_view_filter_view.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
4
2019-05-28T21:06:37.000Z
2021-07-06T03:06:52.000Z
#include <boost/fusion/view/filter_view/filter_view.hpp>
28.5
56
0.824561
miathedev
1a1bf305dff57f8ef966632556b29af27fdd2b66
1,162
cpp
C++
gesture-sensor.cpp
memorial-ece/arduino-seeed
170875ab65aff1a00e05fe2a5eb4c8049ea82525
[ "BSD-2-Clause" ]
null
null
null
gesture-sensor.cpp
memorial-ece/arduino-seeed
170875ab65aff1a00e05fe2a5eb4c8049ea82525
[ "BSD-2-Clause" ]
null
null
null
gesture-sensor.cpp
memorial-ece/arduino-seeed
170875ab65aff1a00e05fe2a5eb4c8049ea82525
[ "BSD-2-Clause" ]
null
null
null
#include "gesture-sensor.h" #include "Gesture_PAJ7620/paj7620.h" /** Initialiazes gesture sensor **/ unsigned int gestureInit() { paj7620Init(); } /** Reads gesture sensor and returns value of gesture (or 0 if no gesture detected) For more info see: http://wiki.seeedstudio.com/Grove-Gesture_v1.0/ @returns data = 0 if no gesture detected, otherwise the value of one of the constants below Up Gesture, data = GES_UP_FLAG Down Gesture, data = GES_DOWN_FLAG Left Gesture, data = GES_LEFT_FLAG Right Gesture, data = GES_RIGHT_FLAG Forward Gesture, data = GES_FORWARD_FLAG Backward Gesture, data = GES_BACKWARD_FLAG Clockwise Gesture, data = GES_CLOCKWISE_FLAG Count Clockwise Gesture, data = GES_COUNT_CLOCKWISE_FLAG Wave Gesture, data = GES_WAVE_FLAG */ unsigned int gestureRead() { unsigned char gestureData = 0; // Read Bank_0_Reg_0x43/0x44 for gesture result. paj7620ReadReg(0x43, 1, &gestureData); // When different gestures be detected, the variable 'data' will be set to different values by paj7620ReadReg(0x43, 1, &data). if (gestureData == 0) //check for wave paj7620ReadReg(0x44, 1, &gestureData); return gestureData; }
29.05
170
0.754733
memorial-ece
1a21833b125a42eaea4adc2df9fbb966b754a605
2,744
cpp
C++
bitreverse.cpp
k9bao/tools
18b52767f4e6c9e5001462d828b1bba69c3832a0
[ "Apache-2.0" ]
null
null
null
bitreverse.cpp
k9bao/tools
18b52767f4e6c9e5001462d828b1bba69c3832a0
[ "Apache-2.0" ]
null
null
null
bitreverse.cpp
k9bao/tools
18b52767f4e6c9e5001462d828b1bba69c3832a0
[ "Apache-2.0" ]
null
null
null
#include <cstring> #include <ctime> #include <fstream> #include <iostream> using namespace std; void usage() { cout << "para is error." << endl; cout << "example: a.out in out pwd" << endl; } std::chrono::steady_clock::time_point now() { return std::chrono::steady_clock::now(); } long long subSecond(std::chrono::steady_clock::time_point before) { return std::chrono::duration_cast<std::chrono::seconds>(now() - before).count(); } int main(int argc, char **argv) { if (argc != 4) { usage(); return -1; } string file = argv[1]; long long totalSize = 0; ifstream in(file, ios::in | ios::in | ios::binary); if (in.is_open() == false) { cout << file << " is can not open.[read]" << endl; return -1; } else { in.seekg(0, ios_base::end); totalSize = in.tellg(); in.seekg(0, ios_base::beg); } string outFile = argv[2]; ofstream out(outFile, ios::out | ios::binary | ios::ate); if (out.is_open() == false) { cout << outFile << " is can not open.[write]" << endl; return -1; } long long pw; if (strlen(argv[3]) > 0) { pw = std::atoll(argv[3]); } else { usage(); return -1; } bool encode = true; unsigned long long curSize = 0; const int size = 4096; char buffer[size]; string head = "lahFv9y&RCluQl%r8bNzh#FiCml7!%tq"; auto count = in.read(buffer, head.size()).gcount(); if (count == head.size() && memcmp(buffer, head.c_str(), head.size()) != 0) { for (size_t i = 0; i < count; i++) { if (((curSize + i) % pw) != 0) { buffer[i] = ~buffer[i]; } } curSize += count; out.write(head.c_str(), head.size()); out.write(buffer, count); cout << "file is will encode" << endl; } else { cout << "file is will decode" << endl; encode = false; } auto curTime = now(); while (true) { if (in.good() == false) { break; } auto count = in.read(buffer, size).gcount(); for (size_t i = 0; i < count; i++) { if (((curSize + i) % pw) != 0) { buffer[i] = ~buffer[i]; } } curSize += count; if (count > 0) { out.write(buffer, count); } if (subSecond(curTime) >= 10) { curTime = now(); cout << "process is " << (double)curSize / totalSize << endl; } } if (in.eof() && out.good()) { cout << "process ok" << endl; return -1; } else { cout << "process fail" << endl; return -1; } in.close(); out.close(); return 0; }
25.64486
84
0.492347
k9bao
1a21cb2d3ab3b4f974a0062f92d74b4be234f1e9
1,560
cpp
C++
example_contests/fk_2014_beta/problems/rod/submissions/accepted/solution_2.cpp
ForritunarkeppniFramhaldsskolanna/epsilon
a31260ad33aba3d1846cda585840d7e7d2f2349c
[ "MIT" ]
6
2016-03-28T13:57:54.000Z
2017-07-25T06:04:05.000Z
example_contests/fk_2014_delta/problems/rod/solution_2.cpp
ForritunarkeppniFramhaldsskolanna/epsilon
a31260ad33aba3d1846cda585840d7e7d2f2349c
[ "MIT" ]
25
2015-01-23T18:02:35.000Z
2015-03-17T01:40:27.000Z
example_contests/fk_2014_delta/problems/rod/solution_2.cpp
ForritunarkeppniFramhaldsskolanna/epsilon
a31260ad33aba3d1846cda585840d7e7d2f2349c
[ "MIT" ]
3
2016-06-28T00:48:38.000Z
2017-05-25T05:29:25.000Z
#include <algorithm> #include <bitset> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> #include <cstring> #include <ctime> #include <fstream> #include <iomanip> #include <iostream> #include <list> #include <map> #include <queue> #include <set> #include <sstream> #include <stack> #include <string> #include <utility> #include <vector> using namespace std; #define all(o) (o).begin(), (o).end() #define allr(o) (o).rbegin(), (o).rend() const int INF = 2147483647; typedef long long ll; typedef pair<int, int> ii; typedef vector<int> vi; typedef vector<ii> vii; typedef vector<vi> vvi; typedef vector<vii> vvii; template <class T> int size(T &x) { return x.size(); } // assert or gtfo int main() { int n, m; scanf("%d %d\n", &n, &m); int **step = new int*[m]; for (int i = 0; i < m; i++) { step[i] = new int[n]; memset(step[i], 0, n << 2); } for (int i = 0; i < m; i++) { string line; getline(cin, line); for (int j = 0; j < n; j++) { if (2*j-1 >= 0 && line[2*j-1] == '-') assert(step[i][j] == 0), step[i][j] = -1; if (2*j+1 < size(line) && line[2*j+1] == '-') assert(step[i][j] == 0), step[i][j] = 1; } } char *res = new char[n]; for (int i = 0; i < n; i++) { int at = i; for (int r = 0; r < m; r++) { at += step[r][at]; } res[at] = 'A' + i; } for (int i = 0; i < n; i++) printf("%c", res[i]); printf("\n"); return 0; }
19.5
98
0.502564
ForritunarkeppniFramhaldsskolanna
1a2ef9f4e0f1a167b3ccd77dfee875e7e2e5f181
375
cpp
C++
tests/e2e/e2e_test_case.cpp
avs/odatacpp-client
c2af181468d345aef0c952a8a0182a1ff11b4b57
[ "MIT" ]
39
2015-01-22T08:13:28.000Z
2021-02-03T07:29:56.000Z
tests/e2e/e2e_test_case.cpp
avs/odatacpp-client
c2af181468d345aef0c952a8a0182a1ff11b4b57
[ "MIT" ]
20
2015-04-27T02:35:31.000Z
2021-01-20T16:47:23.000Z
tests/e2e/e2e_test_case.cpp
avs/odatacpp-client
c2af181468d345aef0c952a8a0182a1ff11b4b57
[ "MIT" ]
30
2015-01-29T21:23:57.000Z
2021-01-11T14:19:47.000Z
//--------------------------------------------------------------------- // <copyright file="e2e_test_case.cpp" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. // </copyright> //--------------------------------------------------------------------- #include "e2e_test_case.h"
53.571429
126
0.458667
avs
1a3481fd62fddf822dd050eb0f24ebee0a0dfd13
2,375
cpp
C++
DelProtect2Config/DelProtect2Config.cpp
pvthuyet/priority-booster
1f0036a4528b799a6ddd862787d4181a1d082917
[ "BSL-1.0" ]
3
2020-09-19T07:27:34.000Z
2022-01-02T21:10:38.000Z
DelProtect2Config/DelProtect2Config.cpp
pvthuyet/windows-kernel-programming
1f0036a4528b799a6ddd862787d4181a1d082917
[ "BSL-1.0" ]
null
null
null
DelProtect2Config/DelProtect2Config.cpp
pvthuyet/windows-kernel-programming
1f0036a4528b799a6ddd862787d4181a1d082917
[ "BSL-1.0" ]
null
null
null
// DelProtect2Config.cpp : This file contains the 'main' function. Program execution begins and ends there. // #include "stdafx.h" #include "..\DelProtect2\DelProtectCommon.h" #include <iostream> int Error(const char* text) { printf("%s (%d)\n", text, ::GetLastError()); return 1; } int PrintUsage() { printf("Usage: DelProtect2Config <option> [exename]\n"); printf("\tOption: add, remove or clear\n"); return 0; } int wmain(int argc, const wchar_t* argv[]) { if (argc < 2) { return PrintUsage(); } HANDLE hDevice = ::CreateFileW(USER_FILE_NAME, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, 0, nullptr); if (hDevice == INVALID_HANDLE_VALUE) return Error("Failed to open handle to device"); DWORD returned{ 0 }; BOOL success { FALSE }; bool badOption = false; if (::_wcsicmp(argv[1], L"add") == 0) { if (argc < 3) { return PrintUsage(); } success = ::DeviceIoControl(hDevice, IOCTL_DELPROTECT_ADD_EXE, (PVOID)argv[2], ((DWORD)::wcslen(argv[2]) + 1) * sizeof(WCHAR), nullptr, 0, &returned, nullptr); } else if (::_wcsicmp(argv[1], L"remove") == 0) { if (argc < 3) { return PrintUsage(); } success = ::DeviceIoControl(hDevice, IOCTL_DELPROTECT_REMOVE_EXE, (PVOID)argv[2], ((DWORD)::wcslen(argv[2]) + 1) * sizeof(WCHAR), nullptr, 0, &returned, nullptr); } else if (::_wcsicmp(argv[1], L"clear") == 0) { success = ::DeviceIoControl(hDevice, IOCTL_DELPROTECT_CLEAR, nullptr, 0, nullptr, 0, &returned, nullptr); } else { badOption = true; printf("Unknown option.\n"); PrintUsage(); } if (!badOption) { if (!success) { Error("Failed in operation"); } else { printf("Success.\n"); } } ::CloseHandle(hDevice); return 0; } // Run program: Ctrl + F5 or Debug > Start Without Debugging menu // Debug program: F5 or Debug > Start Debugging menu // Tips for Getting Started: // 1. Use the Solution Explorer window to add/manage files // 2. Use the Team Explorer window to connect to source control // 3. Use the Output window to see build output and other messages // 4. Use the Error List window to view errors // 5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project // 6. In the future, to open this project again, go to File > Open > Project and select the .sln file
26.988636
135
0.671579
pvthuyet
1a3e64646759c6e42fb554b1722fb23abd9fac41
907
hpp
C++
output/include/core/threading/read_write_lock.hpp
picofox/pilo
59e12c947307d664c4ca9dcc232b481d06be104a
[ "MIT" ]
1
2019-07-31T06:44:46.000Z
2019-07-31T06:44:46.000Z
src/pilo/core/threading/read_write_lock.hpp
picofox/pilo
59e12c947307d664c4ca9dcc232b481d06be104a
[ "MIT" ]
null
null
null
src/pilo/core/threading/read_write_lock.hpp
picofox/pilo
59e12c947307d664c4ca9dcc232b481d06be104a
[ "MIT" ]
null
null
null
#pragma once #include "core/coredefs.hpp" namespace pilo { namespace core { namespace threading { class read_write_lock { public: #ifdef WINDOWS read_write_lock() { ::InitializeSRWLock(&m_lock); } #else read_write_lock() { ::pthread_rwlock_init(&m_lock, NULL); } ~read_write_lock(); #endif void lock_read(); void lock_write(); bool try_lock_read(); bool try_lock_write(); void unlock_read(); void unlock_write(); protected: #ifdef WINDOWS SRWLOCK m_lock; #else pthread_rwlock_t m_lock; #endif }; } } }
18.895833
57
0.416759
picofox
1a412569050244cbdd0b2b246b2ecbf4c5c37b3a
164
hpp
C++
chaine/src/mesh/vertex/is_valid.hpp
the-last-willy/id3d
dc0d22e7247ac39fbc1fd8433acae378b7610109
[ "MIT" ]
null
null
null
chaine/src/mesh/vertex/is_valid.hpp
the-last-willy/id3d
dc0d22e7247ac39fbc1fd8433acae378b7610109
[ "MIT" ]
null
null
null
chaine/src/mesh/vertex/is_valid.hpp
the-last-willy/id3d
dc0d22e7247ac39fbc1fd8433acae378b7610109
[ "MIT" ]
null
null
null
#pragma once #include "proxy.hpp" #include "topology.hpp" namespace face_vertex { inline bool is_valid(VertexProxy vp) { return is_valid(topology(vp)); } }
11.714286
34
0.719512
the-last-willy
1a43b6233a940ecb5091f95246199e1d08b44a81
1,461
cpp
C++
leetcode/problems/easy/859-buddy-string.cpp
wingkwong/competitive-programming
e8bf7aa32e87b3a020b63acac20e740728764649
[ "MIT" ]
18
2020-08-27T05:27:50.000Z
2022-03-08T02:56:48.000Z
leetcode/problems/easy/859-buddy-string.cpp
wingkwong/competitive-programming
e8bf7aa32e87b3a020b63acac20e740728764649
[ "MIT" ]
null
null
null
leetcode/problems/easy/859-buddy-string.cpp
wingkwong/competitive-programming
e8bf7aa32e87b3a020b63acac20e740728764649
[ "MIT" ]
1
2020-10-13T05:23:58.000Z
2020-10-13T05:23:58.000Z
/* Buddy Strings https://leetcode.com/problems/buddy-strings/ Given two strings A and B of lowercase letters, return true if you can swap two letters in A so the result is equal to B, otherwise, return false. Swapping letters is defined as taking two indices i and j (0-indexed) such that i != j and swapping the characters at A[i] and A[j]. For example, swapping at indices 0 and 2 in "abcd" results in "cbad". Example 1: Input: A = "ab", B = "ba" Output: true Explanation: You can swap A[0] = 'a' and A[1] = 'b' to get "ba", which is equal to B. Example 2: Input: A = "ab", B = "ab" Output: false Explanation: The only letters you can swap are A[0] = 'a' and A[1] = 'b', which results in "ba" != B. Example 3: Input: A = "aa", B = "aa" Output: true Explanation: You can swap A[0] = 'a' and A[1] = 'a' to get "aa", which is equal to B. Example 4: Input: A = "aaaaaaabc", B = "aaaaaaacb" Output: true Example 5: Input: A = "", B = "aa" Output: false Constraints: 0 <= A.length <= 20000 0 <= B.length <= 20000 A and B consist of lowercase letters. */ class Solution { public: bool buddyStrings(string A, string B) { // aaa aaa 1 < 3 // abc abc 3 < 3 int n = A.size(); if(A==B) return (set<char>(A.begin(), A.end()).size() < n); int l = 0, r = n - 1; while(l < n && A[l] == B[l]) l++; while(r >= 0 && A[r] == B[r]) r--; if(l < r) swap(A[l], A[r]); return A == B; } };
26.089286
202
0.590691
wingkwong
1a49226dab9c37637f639d113eaa776ed9b030cf
1,352
hpp
C++
Programming Guide/Headers/Siv3D/RenderTexture.hpp
Reputeless/Siv3D-Reference
d58e92885241d11612007fb9187ce0289a7ee9cb
[ "MIT" ]
38
2016-01-14T13:51:13.000Z
2021-12-29T01:49:30.000Z
Programming Guide/Headers/Siv3D/RenderTexture.hpp
Reputeless/Siv3D-Reference
d58e92885241d11612007fb9187ce0289a7ee9cb
[ "MIT" ]
null
null
null
Programming Guide/Headers/Siv3D/RenderTexture.hpp
Reputeless/Siv3D-Reference
d58e92885241d11612007fb9187ce0289a7ee9cb
[ "MIT" ]
16
2016-01-15T11:07:51.000Z
2021-12-29T01:49:37.000Z
//----------------------------------------------- // // This file is part of the Siv3D Engine. // // Copyright (C) 2008-2016 Ryo Suzuki // // Licensed under the MIT License. // //----------------------------------------------- # pragma once # include "Texture.hpp" namespace s3d { class RenderTexture : public Texture { protected: struct _swapChain {}; RenderTexture(const _swapChain&); public: RenderTexture(); RenderTexture(uint32 width, uint32 height, TextureFormat format = TextureFormat::R8G8B8A8_Unorm, const MultiSampling& multiSampling = MultiSampling(1, 0)); explicit RenderTexture(const Size& size, TextureFormat format = TextureFormat::R8G8B8A8_Unorm, const MultiSampling& multiSampling = MultiSampling(1, 0)); RenderTexture(uint32 width, uint32 height, const ColorF& color, TextureFormat format = TextureFormat::R8G8B8A8_Unorm, const MultiSampling& multiSampling = MultiSampling(1, 0)); RenderTexture(const Size& size, const ColorF& color, TextureFormat format = TextureFormat::R8G8B8A8_Unorm, const MultiSampling& multiSampling = MultiSampling(1, 0)); void clear(const ColorF& color); void beginReset(); bool endReset(const Size& size, TextureFormat format = TextureFormat::R8G8B8A8_Unorm, const MultiSampling& multiSampling = MultiSampling(1, 0)); bool saveDDS(const FilePath& path) const; }; }
30.044444
178
0.699704
Reputeless
1a495c21c102171ec676f78c94de7d3c26d81452
2,096
cc
C++
src/graphics/bin/vulkan_loader/loader.cc
dreamboy9/fuchsia
4ec0c406a28f193fe6e7376ee7696cca0532d4ba
[ "BSD-2-Clause" ]
null
null
null
src/graphics/bin/vulkan_loader/loader.cc
dreamboy9/fuchsia
4ec0c406a28f193fe6e7376ee7696cca0532d4ba
[ "BSD-2-Clause" ]
56
2021-06-03T03:16:25.000Z
2022-03-20T01:07:44.000Z
src/graphics/bin/vulkan_loader/loader.cc
dreamboy9/fuchsia
4ec0c406a28f193fe6e7376ee7696cca0532d4ba
[ "BSD-2-Clause" ]
null
null
null
// Copyright 2021 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/graphics/bin/vulkan_loader/loader.h" #include <lib/fdio/directory.h> #include <lib/fdio/io.h> LoaderImpl::~LoaderImpl() { app_->RemoveObserver(this); } // static void LoaderImpl::Add(LoaderApp* app, const std::shared_ptr<sys::OutgoingDirectory>& outgoing) { outgoing->AddPublicService(fidl::InterfaceRequestHandler<fuchsia::vulkan::loader::Loader>( [app](fidl::InterfaceRequest<fuchsia::vulkan::loader::Loader> request) { auto impl = std::make_unique<LoaderImpl>(app); LoaderImpl* impl_ptr = impl.get(); impl_ptr->bindings_.AddBinding(std::move(impl), std::move(request), nullptr); })); } // LoaderApp::Observer implementation. void LoaderImpl::OnIcdListChanged(LoaderApp* app) { auto it = callbacks_.begin(); while (it != callbacks_.end()) { std::optional<zx::vmo> vmo = app->GetMatchingIcd(it->first); if (!vmo) { ++it; } else { it->second(*std::move(vmo)); it = callbacks_.erase(it); } } if (callbacks_.empty()) { app_->RemoveObserver(this); } } // fuchsia::vulkan::loader::Loader impl void LoaderImpl::Get(std::string name, GetCallback callback) { AddCallback(std::move(name), std::move(callback)); } void LoaderImpl::ConnectToDeviceFs(zx::channel channel) { app_->ServeDeviceFs(std::move(channel)); } void LoaderImpl::GetSupportedFeatures(GetSupportedFeaturesCallback callback) { fuchsia::vulkan::loader::Features features = fuchsia::vulkan::loader::Features::CONNECT_TO_DEVICE_FS | fuchsia::vulkan::loader::Features::GET; callback(features); } void LoaderImpl::AddCallback(std::string name, fit::function<void(zx::vmo)> callback) { std::optional<zx::vmo> vmo = app_->GetMatchingIcd(name); if (vmo) { callback(*std::move(vmo)); return; } callbacks_.emplace_back(std::make_pair(std::move(name), std::move(callback))); if (callbacks_.size() == 1) { app_->AddObserver(this); } }
32.75
100
0.689885
dreamboy9
1a55fef6e547e747fbd7704e3b90f38d875e7382
1,831
cc
C++
selfdrive/common/testparams/test_params.cc
lukeadams/openpilot
c3bd28c2d5029749c47ee03440b3cc509f786968
[ "MIT" ]
null
null
null
selfdrive/common/testparams/test_params.cc
lukeadams/openpilot
c3bd28c2d5029749c47ee03440b3cc509f786968
[ "MIT" ]
null
null
null
selfdrive/common/testparams/test_params.cc
lukeadams/openpilot
c3bd28c2d5029749c47ee03440b3cc509f786968
[ "MIT" ]
null
null
null
#include "selfdrive/common/params.h" #include <cstring> static const char* const kUsage = "%s: read|write|read_block params_path key [value]\n"; int main(int argc, const char* argv[]) { if (argc < 4) { printf(kUsage, argv[0]); return 0; } Params params(argv[2]); const char* key = argv[3]; if (strcmp(argv[1], "read") == 0) { char* value; size_t value_size; int result = params.read_db_value(key, &value, &value_size); if (result >= 0) { fprintf(stdout, "Read %zu bytes: ", value_size); fwrite(value, 1, value_size, stdout); fprintf(stdout, "\n"); free(value); } else { fprintf(stderr, "Error reading: %d\n", result); return -1; } } else if (strcmp(argv[1], "write") == 0) { if (argc < 5) { fprintf(stderr, "Error: write value required\n"); return 1; } const char* value = argv[4]; const size_t value_size = strlen(value); int result = params.write_db_value(key, value, value_size); if (result >= 0) { fprintf(stdout, "Wrote %s to %s\n", value, key); } else { fprintf(stderr, "Error writing: %d\n", result); return -1; } } else if (strcmp(argv[1], "read_block") == 0) { char* value; size_t value_size; params.read_db_value_blocking(key, &value, &value_size); fprintf(stdout, "Read %zu bytes: ", value_size); fwrite(value, 1, value_size, stdout); fprintf(stdout, "\n"); free(value); } else { printf(kUsage, argv[0]); return 1; } return 0; } // BUILD: // $ gcc -I$HOME/one selfdrive/common/test_params.c selfdrive/common/params.c selfdrive/common/util.c -o ./test_params // $ seq 0 100000 | xargs -P20 -I{} ./test_params write /data/params DongleId {} && sleep 0.1 & // $ while ./test_params read /data/params DongleId; do sleep 0.05; done
29.063492
118
0.607318
lukeadams
1a5b1fb2d6c86019f43255d5c217e30395d9c968
7,517
cpp
C++
src/com/cyosp/mpa/api/rest/v1/MPAOFactory.cpp
cyosp/MPA
f640435c483dcbf7bfe7ff7887a25e6c76612528
[ "BSD-3-Clause" ]
null
null
null
src/com/cyosp/mpa/api/rest/v1/MPAOFactory.cpp
cyosp/MPA
f640435c483dcbf7bfe7ff7887a25e6c76612528
[ "BSD-3-Clause" ]
null
null
null
src/com/cyosp/mpa/api/rest/v1/MPAOFactory.cpp
cyosp/MPA
f640435c483dcbf7bfe7ff7887a25e6c76612528
[ "BSD-3-Clause" ]
null
null
null
/* * MPAOFactory.cpp * * Created on: 21 March 2015 * Author: cyosp */ #include <com/cyosp/mpa/api/rest/v1/MPAOFactory.hpp> namespace mpa_api_rest_v1 { // Initialize static member MPAOFactory * MPAOFactory::mpaofactory = NULL; MPAOFactory * MPAOFactory::getInstance() { if( mpaofactory == NULL ) mpaofactory = new MPAOFactory(); return mpaofactory; } MPAOFactory::MPAOFactory() { //tokenList = new map<string, Token>(); } // Return NULL if URL is bad // GET // /mpa/res/logout // /mpa/res/accounts // /mpa/res/accounts/10 // /mpa/res/accounts/10/categories // /mpa/res/infos // /mpa/res/locales // POST // /mpa/res/users/login // /mpa/res/users/logout // /mpa/res/users/add // /mpa/res/users/0/del?version=0 // /mpa/res/users/10/upd?version=1 // /mpa/res/accounts/add // /mpa/res/accounts/20/del?version=1 // /mpa/res/accounts/20/upd?version=1 // /mpa/res/categories/add // /mpa/res/categories/30/del?version=1 mpa_api_rest_v1::MPAO * MPAOFactory::getMPAO(HttpRequestType requestType, const string& url, const map<string, string>& argvals) { mpa_api_rest_v1::MPAO * ret = NULL; // // Decode URL // ActionType actionType = NONE; vector<std::pair<string, int> > urlPairs; boost::smatch matches; const boost::regex startUrl("^/api/rest/v1(/.*)$"); if( boost::regex_match(url, matches, startUrl) ) { MPA_LOG_TRIVIAL(trace, "Match with start URL"); // Remove start of URL string urlToAnalyse = matches[1]; if( requestType == POST ) { const boost::regex actionTypeRegex("(.*)/([a-z]+)$"); if( boost::regex_match(urlToAnalyse, matches, actionTypeRegex) ) { MPA_LOG_TRIVIAL(trace, "Action type: " + matches[2]); // Remove URL action type urlToAnalyse = matches[1]; if( matches[2] == "login" ) { actionType = LOGIN; // Update URL in order to be compliant to the standard others urlToAnalyse = "/login/0"; } else if( matches[2] == "add" ) { actionType = ADD; // Update URL in order to be compliant to the standard others urlToAnalyse += "/0"; } else if( matches[2] == "del" ) actionType = DELETE; else if( matches[2] == "upd" ) actionType = UPDATE; const boost::regex urlPairRegex("^/([a-z]+)/([0-9]+)(.*)$"); // Fill vector starting by the beginning of URL while( boost::regex_match(urlToAnalyse, matches, urlPairRegex) ) { // Update URL string name = matches[1]; string idString = matches[2]; int id = atoi(idString); urlToAnalyse = matches[3]; MPA_LOG_TRIVIAL(trace, "Name: " + name + ", id: " + idString); urlPairs.push_back(std::pair<string, int>(name, id)); } MPA_LOG_TRIVIAL(trace, "End URL analyze"); } else MPA_LOG_TRIVIAL(trace, "URL doesn't match action type"); } else { MPA_LOG_TRIVIAL(trace, "URL to analyze: " + urlToAnalyse); // Manage URL like: GET /mpa/res/accounts const boost::regex urlStartRegex("^/([a-z]+)(.*)$"); while( boost::regex_match(urlToAnalyse, matches, urlStartRegex) ) { MPA_LOG_TRIVIAL(trace, "URL start match"); // Set values string name = matches[1]; string idString = ""; int id = 0; urlToAnalyse = matches[2]; MPA_LOG_TRIVIAL(trace, "New URL to analyze: " + urlToAnalyse); // Manage URL like: GET /mpa/res/accounts/10 const boost::regex urlIdRegex("^/([0-9]+)(.*)$"); // Fill vector starting by beginning of URL if( boost::regex_match(urlToAnalyse, matches, urlIdRegex) ) { MPA_LOG_TRIVIAL(trace, "URL ID match"); idString = matches[1]; id = atoi(idString); urlToAnalyse = matches[2]; } MPA_LOG_TRIVIAL(trace, "Name: " + name + ", id: " + idString); urlPairs.push_back(std::pair<string, int>(name, id)); } } // Manage case where URL doesn't match with an expected one if( urlPairs.size() > 0 ) { int lastPosition = urlPairs.size() - 1; string lastIdentifier = urlPairs[lastPosition].first; MPA_LOG_TRIVIAL(trace, "Last identifier: " + lastIdentifier); if( lastIdentifier == mpa_api_rest_v1::Login::URL_STRING_PATH_IDENTIFIER ) ret = new mpa_api_rest_v1::Login(requestType, actionType, argvals, urlPairs); else if( lastIdentifier == mpa_api_rest_v1::Logout::URL_STRING_PATH_IDENTIFIER ) ret = new mpa_api_rest_v1::Logout(requestType, actionType, argvals, urlPairs); else if( lastIdentifier == mpa_api_rest_v1::Account::URL_STRING_PATH_IDENTIFIER ) ret = new mpa_api_rest_v1::Account(requestType, actionType, argvals, urlPairs); else if( lastIdentifier == mpa_api_rest_v1::User::URL_STRING_PATH_IDENTIFIER ) ret = new mpa_api_rest_v1::User(requestType, actionType, argvals, urlPairs); else if( lastIdentifier == mpa_api_rest_v1::Info::URL_STRING_PATH_IDENTIFIER ) ret = new mpa_api_rest_v1::Info(requestType, actionType, argvals, urlPairs); else if( lastIdentifier == mpa_api_rest_v1::Locale::URL_STRING_PATH_IDENTIFIER ) ret = new mpa_api_rest_v1::Locale(requestType, actionType, argvals, urlPairs); else if( lastIdentifier == mpa_api_rest_v1::Category::URL_STRING_PATH_IDENTIFIER ) ret = new mpa_api_rest_v1::Category(requestType, actionType, argvals, urlPairs); else if( lastIdentifier == mpa_api_rest_v1::Provider::URL_STRING_PATH_IDENTIFIER ) ret = new mpa_api_rest_v1::Provider(requestType, actionType, argvals, urlPairs); else if( lastIdentifier == mpa_api_rest_v1::Operation::URL_STRING_PATH_IDENTIFIER ) ret = new mpa_api_rest_v1::Operation(requestType, actionType, argvals, urlPairs); } else MPA_LOG_TRIVIAL(info, "Bad URL"); } else MPA_LOG_TRIVIAL(trace, "Doesn't match with POST start URL"); return ret; } map<string, string> & MPAOFactory::getTokenList() { return tokenList; } }
37.585
101
0.518159
cyosp
1a5cad6550b20dbdefcd13178dd1e94768258ae2
3,141
cc
C++
src/tests/functionspace/test_reduced_halo.cc
twsearle/atlas
a1916fd521f9935f846004e6194f80275de4de83
[ "Apache-2.0" ]
67
2018-03-01T06:56:49.000Z
2022-03-08T18:44:47.000Z
src/tests/functionspace/test_reduced_halo.cc
twsearle/atlas
a1916fd521f9935f846004e6194f80275de4de83
[ "Apache-2.0" ]
93
2018-12-07T17:38:04.000Z
2022-03-31T10:04:51.000Z
src/tests/functionspace/test_reduced_halo.cc
twsearle/atlas
a1916fd521f9935f846004e6194f80275de4de83
[ "Apache-2.0" ]
33
2018-02-28T17:06:19.000Z
2022-01-20T12:12:27.000Z
/* * (C) Copyright 2013 ECMWF. * * This software is licensed under the terms of the Apache Licence Version 2.0 * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. * In applying this licence, ECMWF does not waive the privileges and immunities * granted to it by virtue of its status as an intergovernmental organisation * nor does it submit to any jurisdiction. */ #include <algorithm> #include <array> #include <string> #include <vector> #include "atlas/functionspace/EdgeColumns.h" #include "atlas/functionspace/NodeColumns.h" #include "atlas/grid/StructuredGrid.h" #include "atlas/mesh/HybridElements.h" #include "atlas/mesh/Mesh.h" #include "atlas/mesh/Nodes.h" #include "atlas/meshgenerator.h" #include "atlas/parallel/mpi/mpi.h" #include "tests/AtlasTestEnvironment.h" using namespace atlas::functionspace; using namespace atlas::grid; using namespace atlas::meshgenerator; namespace atlas { namespace test { template <typename Container> Container reversed(const Container& a) { Container a_reversed = a; std::reverse(a_reversed.begin(), a_reversed.end()); return a_reversed; } static std::array<bool, 2> false_true{false, true}; //----------------------------------------------------------------------------- CASE("halo nodes") { Grid grid("O8"); std::vector<int> halos{0, 1, 2, 3, 4}; std::vector<int> nodes{560, 592, 624, 656, 688}; for (bool reduce : false_true) { SECTION(std::string(reduce ? "reduced" : "increased")) { Mesh mesh = StructuredMeshGenerator().generate(grid); EXPECT(mesh.nodes().size() == nodes[0]); for (int h : (reduce ? reversed(halos) : halos)) { NodeColumns fs(mesh, option::halo(h)); if (mpi::comm().size() == 1) { EXPECT(fs.nb_nodes() == nodes[h]); } } } } } //----------------------------------------------------------------------------- CASE("halo edges") { Grid grid("O8"); std::vector<int> halos{0, 1, 2, 3, 4}; std::vector<int> edges{1559, 1649, 1739, 1829, 1919}; for (bool reduce : false_true) { for (bool with_pole_edges : false_true) { int pole_edges = with_pole_edges ? StructuredGrid(grid).nx().front() : 0; SECTION(std::string(reduce ? "reduced " : "increased ") + std::string(with_pole_edges ? "with_pole_edges" : "without_pole_edges")) { Mesh mesh = StructuredMeshGenerator().generate(grid); EXPECT(mesh.edges().size() == 0); for (int h : (reduce ? reversed(halos) : halos)) { EdgeColumns fs(mesh, option::halo(h) | option::pole_edges(with_pole_edges)); if (mpi::comm().size() == 1) { EXPECT(fs.nb_edges() == edges[h] + pole_edges); } } } } } } //----------------------------------------------------------------------------- } // namespace test } // namespace atlas int main(int argc, char** argv) { return atlas::test::run(argc, argv); }
32.05102
96
0.559058
twsearle
1a61d1a6a96afadc80416f46aaf1e217616dc71f
4,176
cpp
C++
Plugins/SPARK_PL/src/RenderingAPIs/PixelLight/SPK_PLLineRenderer.cpp
ktotheoz/pixellight
43a661e762034054b47766d7e38d94baf22d2038
[ "MIT" ]
83
2015-01-08T15:06:14.000Z
2021-07-20T17:07:00.000Z
Plugins/SPARK_PL/src/RenderingAPIs/PixelLight/SPK_PLLineRenderer.cpp
PixelLightFoundation/pixellight
43a661e762034054b47766d7e38d94baf22d2038
[ "MIT" ]
27
2019-06-18T06:46:07.000Z
2020-02-02T11:11:28.000Z
Plugins/SPARK_PL/src/RenderingAPIs/PixelLight/SPK_PLLineRenderer.cpp
naetherm/PixelLight
d7666f5b49020334cbb5debbee11030f34cced56
[ "MIT" ]
40
2015-02-25T18:24:34.000Z
2021-03-06T09:01:48.000Z
/*********************************************************\ * File: SPK_PLLineRenderer.cpp * * * Copyright (C) 2002-2013 The PixelLight Team (http://www.pixellight.org/) * * This file is part of PixelLight. * * 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. \*********************************************************/ //[-------------------------------------------------------] //[ Includes ] //[-------------------------------------------------------] #include <PLMath/Math.h> // On Mac OS X I'am getting the compiler error "error: ‘isfinite’ was not declared in this scope" when not including this header, first... I'am not sure what SPARK is changing in order to cause this error... #include <PLCore/PLCore.h> PL_WARNING_PUSH PL_WARNING_DISABLE(4530) // "warning C4530: C++ exception handler used, but unwind semantics are not enabled. Specify /EHsc" // [HACK] There are missing forward declarations within the SPARK headers... namespace SPK { class Group; } #include <Core/SPK_Group.h> PL_WARNING_POP #include "SPARK_PL/RenderingAPIs/PixelLight/SPK_PLBuffer.h" #include "SPARK_PL/RenderingAPIs/PixelLight/SPK_PLLineRenderer.h" //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] namespace SPARK_PL { //[-------------------------------------------------------] //[ Protected definitions ] //[-------------------------------------------------------] const std::string SPK_PLLineRenderer::PLBufferName("SPK_PLLineRenderer_Buffer"); //[-------------------------------------------------------] //[ Public functions ] //[-------------------------------------------------------] /** * @brief * Destructor of SPK_PLLineRenderer */ SPK_PLLineRenderer::~SPK_PLLineRenderer() { } //[-------------------------------------------------------] //[ Public virtual SPK::BufferHandler functions ] //[-------------------------------------------------------] void SPK_PLLineRenderer::createBuffers(const SPK::Group &group) { // Create the SPK_PLBuffer instance m_pSPK_PLBuffer = static_cast<SPK_PLBuffer*>(group.createBuffer(PLBufferName, PLBufferCreator(GetPLRenderer(), 14, 0, SPK::TEXTURE_NONE), 0U, false)); } void SPK_PLLineRenderer::destroyBuffers(const SPK::Group &group) { group.destroyBuffer(PLBufferName); } //[-------------------------------------------------------] //[ Protected functions ] //[-------------------------------------------------------] /** * @brief * Constructor of SPK_PLLineRenderer */ SPK_PLLineRenderer::SPK_PLLineRenderer(PLRenderer::Renderer &cRenderer, float fLength, float fWidth) : SPK_PLRenderer(cRenderer), SPK::LineRendererInterface(fLength, fWidth), m_pSPK_PLBuffer(nullptr) { } //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] } // SPARK_PL
42.612245
232
0.534722
ktotheoz
1a680e179daa526101317eb8f2d21d4435439a12
1,803
cpp
C++
src/demo/main.cpp
Glockenspiel/Fibers4U
69dac46b0995164d16bdb048071f43909b1faf5f
[ "Apache-2.0" ]
1
2020-07-11T12:39:03.000Z
2020-07-11T12:39:03.000Z
src/demo/main.cpp
Glockenspiel/Fibers4U
69dac46b0995164d16bdb048071f43909b1faf5f
[ "Apache-2.0" ]
null
null
null
src/demo/main.cpp
Glockenspiel/Fibers4U
69dac46b0995164d16bdb048071f43909b1faf5f
[ "Apache-2.0" ]
null
null
null
#include "include/fbr.h" #include "Player.h" using namespace std; using namespace fbr; int main(){ Player *p = new Player(); BaseTask *printHP = new TaskArgs<>(&Player::printHp, p); TaskArgs<int> *taskArg = new TaskArgs<int>(&Player::addHp, p); int a = 20; taskArg->setArgs(a); TaskArgs<int, bool> *test = new TaskArgs<int, bool>(&Player::damage, p); int b = 5; bool isMagic=false; test->setArgs(b, isMagic); TaskArgsCopy<int, int, int> *move = new TaskArgsCopy<int, int, int>(&Player::move, p); int c = 0; move->setArgs(54, c, std::thread::hardware_concurrency()); Task *inputtask = new Task(&Player::taskInput, p); inputtask->setReuseable(true); Scheduler *scheduler = new Scheduler(0,4, taskArg,true,true); if (scheduler->getIsConstructed() == false){ return 0; } fbr::con_cout << "All workers ready! " << fbr::endl; Task *update = new Task(&Player::update, p); //wake up main thread Task *endTask = new Task(&Scheduler::wakeUpMain); Task *longTask = new Task(&Player::longTask, p); //run all task unsyncronized //example with vector //vector<BaseTask*> allTasks = { printHP, move, update,longTask }; //scheduler->runTasks(allTasks, priority::low); //example with variadic function Scheduler::runTasks(priority::low, 4, printHP, move, update, longTask); //scheduler->waitAllFibersFree(); //Scheduler::waitForCounter(0, inputtask); //Scheduler::waitForCounter(0, inputtask); //puts main thread to wait and doesn't cunsume cpu time //wakes up when endTask is run Scheduler::waitMain(); scheduler->close(); //system("pause"); //delete scheduler and display msg delete scheduler; //fbr::log << "here" << Log::endl; fbr::con_cout << "Scheduler deleted" << fbr::endl; SpinUntil *timer = new SpinUntil(); timer->wait(2); delete timer; }
25.757143
87
0.684415
Glockenspiel
1a6885151eed7a9c4445dd976ea5a82ec986cb63
898
cpp
C++
euler065.cpp
suihan74/ProjectEuler
0ccd2470206a606700ab5c2a7162b2a3d3de2f8d
[ "MIT" ]
null
null
null
euler065.cpp
suihan74/ProjectEuler
0ccd2470206a606700ab5c2a7162b2a3d3de2f8d
[ "MIT" ]
null
null
null
euler065.cpp
suihan74/ProjectEuler
0ccd2470206a606700ab5c2a7162b2a3d3de2f8d
[ "MIT" ]
null
null
null
#include <cstdint> #include <iostream> #include <utility> #include "continued_fraction.h" #include "largeint.h" using uInt = std::uint_fast32_t; using LInt = Euler::LargeInt<uInt>; using Fraction = std::pair<LInt, LInt>; // first: 分子, second: 分母 using namespace Euler::ContinuedFraction; int main(void) { constexpr uInt DEPTH_BOUND = 100; // 項目は1始まりで数える(1項目, 2項目, ...) Fraction frac = std::make_pair(1, 1); if (DEPTH_BOUND <= 1) { frac.first = napiers_term_at(0); } else { frac.second = napiers_term_at(DEPTH_BOUND - 1); } // 地道に分数計算 for (uInt i = 2; i <= DEPTH_BOUND; i++) { const uInt a = napiers_term_at(DEPTH_BOUND - i); frac.first += frac.second * a; if (i == DEPTH_BOUND) { continue; } // 1/(fr.f/fr.s) => fr.s/fr.f std::swap(frac.first, frac.second); } std::cout << "Euler065: " << frac.first.digits_sum() << std::endl; return 0; }
23.631579
68
0.635857
suihan74
1a69b234e05419fabf8a71196bb209069b6d6387
3,385
cpp
C++
src/mfx/dsp/wnd/XFadeShape.cpp
mikelange49/pedalevite
a81bd8a6119c5920995ec91b9f70e11e9379580e
[ "WTFPL" ]
null
null
null
src/mfx/dsp/wnd/XFadeShape.cpp
mikelange49/pedalevite
a81bd8a6119c5920995ec91b9f70e11e9379580e
[ "WTFPL" ]
null
null
null
src/mfx/dsp/wnd/XFadeShape.cpp
mikelange49/pedalevite
a81bd8a6119c5920995ec91b9f70e11e9379580e
[ "WTFPL" ]
null
null
null
/***************************************************************************** XFadeShape.cpp Author: Laurent de Soras, 2017 --- Legal stuff --- This program is free software. It comes without any warranty, to the extent permitted by applicable law. You can redistribute it and/or modify it under the terms of the Do What The Fuck You Want To Public License, Version 2, as published by Sam Hocevar. See http://sam.zoy.org/wtfpl/COPYING for more details. *Tab=3***********************************************************************/ #if defined (_MSC_VER) #pragma warning (1 : 4130 4223 4705 4706) #pragma warning (4 : 4355 4786 4800) #endif /*\\\ INCLUDE FILES \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ #include "fstb/Approx.h" #include "fstb/fnc.h" #include "fstb/ToolsSimd.h" #include "mfx/dsp/wnd/XFadeShape.h" #include <cassert> namespace mfx { namespace dsp { namespace wnd { /*\\\ PUBLIC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ void XFadeShape::set_duration (double duration, float fade_ratio) { assert (duration > 0); assert (fade_ratio > 0); assert (fade_ratio <= 1); if (duration != _duration || fade_ratio != _fade_ratio) { _duration = duration; _fade_ratio = fade_ratio; if (is_ready ()) { make_shape (); } } } void XFadeShape::set_sample_freq (double sample_freq) { assert (sample_freq > 0); _sample_freq = sample_freq; make_shape (); } bool XFadeShape::is_ready () const { return (_sample_freq > 0); } int XFadeShape::get_len () const { assert (_len > 0); return _len; } const float * XFadeShape::use_shape () const { assert (_len > 0); return (&_shape [0]); } /*\\\ PROTECTED \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ /*\\\ PRIVATE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ void XFadeShape::make_shape () { const int len = fstb::round_int (_sample_freq * _duration); if (len != _len) { _len = len; // +3 because we could read (or write) a full vector from the last // position const int len_margin = len + 3; _shape.resize (len_margin); #if 1 const float p = 0.25f / _fade_ratio; fstb::ToolsSimd::VectF32 x; fstb::ToolsSimd::VectF32 step; fstb::ToolsSimd::start_lerp (x, step, -p, p, len); const auto half = fstb::ToolsSimd::set1_f32 ( 0.5f ); const auto mi = fstb::ToolsSimd::set1_f32 (-0.25f); const auto ma = fstb::ToolsSimd::set1_f32 (+0.25f); for (int pos = 0; pos < len; pos += 4) { auto xx = x; xx = fstb::ToolsSimd::min_f32 (xx, ma); xx = fstb::ToolsSimd::max_f32 (xx, mi); auto v = fstb::Approx::sin_nick_2pi (xx); v *= half; v += half; fstb::ToolsSimd::store_f32 (&_shape [pos], v); x += step; } #else // Reference implementation const float p = 0.25f / _fade_ratio; const float dif = p * 2; const float step = dif * fstb::rcp_uint <float> (len); const float x = -p; for (int pos = 0; pos < len; ++pos) { const float xx = fstb::limit (x, -0.25f, +0.25f); const float v = fstb::Approx::sin_nick_2pi (xx) * 0.5f + 0.5f; _shape [pos] = v; x += step; } #endif } } } // namespace wnd } // namespace dsp } // namespace mfx /*\\\ EOF \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
19.454023
78
0.534417
mikelange49
1a6e268dde28804830c7cc3dcdd417023249b707
93
cpp
C++
Source/Nova/Game/NovaDestination.cpp
Sabrave/ShipBuilder
4610c16701ccb85d6f1e0de77f914e58bcf4de7e
[ "BSD-3-Clause" ]
17
2022-02-19T05:39:33.000Z
2022-03-01T01:56:19.000Z
Source/Nova/Game/NovaDestination.cpp
Frank1eJohnson/ShipBuilder
4610c16701ccb85d6f1e0de77f914e58bcf4de7e
[ "BSD-3-Clause" ]
null
null
null
Source/Nova/Game/NovaDestination.cpp
Frank1eJohnson/ShipBuilder
4610c16701ccb85d6f1e0de77f914e58bcf4de7e
[ "BSD-3-Clause" ]
null
null
null
// Nova project - Gwennaël Arbona #include "NovaDestination.h" #include "Nova/Nova.h"
15.5
34
0.688172
Sabrave
1a6f4a155ba3def3a2ad336ba461a65aed37ae45
5,536
cpp
C++
src/core.cpp
xiroV/ninja-castle-game
92b5adde81e68cc98c6a696d6b3f6837a17499ca
[ "MIT" ]
null
null
null
src/core.cpp
xiroV/ninja-castle-game
92b5adde81e68cc98c6a696d6b3f6837a17499ca
[ "MIT" ]
null
null
null
src/core.cpp
xiroV/ninja-castle-game
92b5adde81e68cc98c6a696d6b3f6837a17499ca
[ "MIT" ]
null
null
null
#include"core.h" Collision::Collision() {} void Collision::init(std::string filename) { std::ifstream inFile; this->center_point = glm::vec2(22.5, 31.0); this->player_position.push_back(glm::vec4(0, 0, 0, 0)); this->player_position.push_back(glm::vec4(0, 0, 0, 0)); std::vector<unsigned int> vertex_indices, normal_indices; std::vector<glm::vec3> temp_v; std::vector<glm::vec3> temp_vn; bool read = true; inFile.open(filename); if(!inFile) { std::cout << "Can't open collision file " << filename << std::endl; exit(1); } // Read floor std::string ch; while(inFile >> ch && read) { if(ch == "v") { glm::vec3 vertex; inFile >> vertex.x; inFile >> vertex.y; inFile >> vertex.z; temp_v.push_back(vertex); } else if (ch == "o") { inFile >> ch; int s1 = ch.find("_"); if(ch.substr(0, s1) != "floor") { read = false; } } else if (ch == "vn") { glm::vec3 normal; inFile >> normal.x; inFile >> normal.y; inFile >> normal.z; temp_vn.push_back(normal); } else if (ch == "f") { unsigned int vertex_index[3], normal_index[3]; //unsigned int uv_index[3] for(int i = 0; i < 3; i++) { inFile >> ch; int s1 = ch.find("/"); vertex_index[i] = std::stoi(ch.substr(0, s1)); std::string ch2 = ch.substr(s1+1, ch.length()); int s2 = ch2.find("/"); /*if(s2 > 0) { uv_index[i] = std::stoi(ch.substr(s1, s2)); }*/ normal_index[i] = std::stoi(ch2.substr(s2+1, ch.length())); } vertex_indices.push_back(vertex_index[0]); vertex_indices.push_back(vertex_index[1]); vertex_indices.push_back(vertex_index[2]); normal_indices.push_back(normal_index[0]); normal_indices.push_back(normal_index[1]); normal_indices.push_back(normal_index[2]); } } // Done reading floor // Now processing floor indices for(unsigned int i=0; i < vertex_indices.size(); i++) { unsigned int vertex_index = vertex_indices[i]; unsigned int normal_index = normal_indices[i]; glm::vec3 v = temp_v[vertex_index-1]; this->floor_verts.push_back(v); glm::vec3 normal = temp_vn[normal_index-1]; this->floor_norms.push_back(normal); } inFile.close(); std::cout << "Collision map intialized" << std::endl; } bool Collision::on_floor(float x, float y) { for(unsigned int i = 0; i < this->floor_verts.size(); i+=3) { glm::vec2 p1, p2, p3; p1.x = this->floor_verts[i].x; p1.y = this->floor_verts[i].z; p2.x = this->floor_verts[i+1].x; p2.y = this->floor_verts[i+1].z; p3.x = this->floor_verts[i+2].x; p3.y = this->floor_verts[i+2].z; // Barycentric coordinates float alpha = ((p2.y - p3.y) * (x - p3.x) + (p3.x - p2.x) * (y - p3.y)) / ((p2.y - p3.y)*(p1.x - p3.x) + (p3.x - p2.x) * (p1.y - p3.y)); float beta = ((p3.y - p1.y) * (x - p3.x) + (p1.x - p3.x) * (y - p3.y)) / ((p2.y - p3.y)*(p1.x - p3.x) + (p3.x - p2.x)*(p1.y - p3.y)); float gamma = 1.0f - alpha - beta; if(alpha > 0.0 && beta > 0.0 && gamma > 0.0) { return true; } } return false; } bool Collision::wall_hit_x(float x, float y) { if(x > 10 && x < 34 && y > 18 && y < 45) { return false; } return !this->on_floor(x, y); } bool Collision::wall_hit_y(float x, float y) { if(x > 10 && x < 34 && y > 18 && y < 45) { return false; } return !this->on_floor(x, y); } float Collision::distance(glm::vec2 p1, glm::vec2 p2) { float distance = sqrt( pow(p1.x-p2.x, 2) + pow(p1.y-p2.y, 2) ); return distance; } float Collision::player_distance(unsigned int id) { glm::vec4 player = this->player_position[id]; glm::vec4 enemy = this->get_enemy_pos(id); // Calculate enemy ray float ray_x = enemy.x + (sin(enemy.w*PI/180) * CHAR_MOVE_SPEED); float ray_y = enemy.y + (cos(enemy.w*PI/180) * CHAR_MOVE_SPEED); float distance = sqrt( pow(player.x-ray_x, 2) + pow(player.y-ray_y, 2) + pow(player.z-enemy.z, 2) ); return distance; } bool Collision::player_collision(unsigned int player) { // Set to true if the player collided with enemy // Used to set velocities on knock-back for character if(this->player_distance(player) < 1.0) { return true; } return false; } // Method for players to report their position void Collision::report(unsigned int id, float x, float y, float z, float angle) { this->player_position[id].x = x; this->player_position[id].y = y; this->player_position[id].z = z; this->player_position[id].w = angle; } glm::vec4 Collision::get_enemy_pos(unsigned int player) { unsigned int enemy; if(player == 0) { enemy = 1; } else { enemy = 0; } return this->player_position[enemy]; } bool Collision::in_center(unsigned int id) { float distance = this->distance(glm::vec2(this->player_position[id].x, this->player_position[id].y), this->center_point); if(distance < 8.5) { return true; } return false; }
28.536082
144
0.53974
xiroV
2b2dd61a9b564be843b5a4a768fe43e64162ec90
6,944
hpp
C++
INCLUDE/ServiceConfiguration.hpp
SammyB428/WFC
64aee7c7953e38c8a418ba9530339e8f4faac046
[ "BSD-2-Clause" ]
1
2021-03-29T06:09:19.000Z
2021-03-29T06:09:19.000Z
INCLUDE/ServiceConfiguration.hpp
SammyB428/WFC
64aee7c7953e38c8a418ba9530339e8f4faac046
[ "BSD-2-Clause" ]
null
null
null
INCLUDE/ServiceConfiguration.hpp
SammyB428/WFC
64aee7c7953e38c8a418ba9530339e8f4faac046
[ "BSD-2-Clause" ]
null
null
null
/* ** Author: Samuel R. Blackburn ** Internet: [email protected] ** ** Copyright, 1995-2019, Samuel R. Blackburn ** ** "You can get credit for something or get it done, but not both." ** Dr. Richard Garwin ** ** BSD License follows. ** ** Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions ** are met: ** ** Redistributions of source code must retain the above copyright notice, ** this list of conditions and the following disclaimer. Redistributions ** in binary form must reproduce the above copyright notice, this list ** of conditions and the following disclaimer in the documentation and/or ** other materials provided with the distribution. Neither the name of ** the WFC 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. ** ** $Workfile: ServiceConfiguration.hpp $ ** $Revision: 12 $ ** $Modtime: 6/26/01 11:07a $ */ /* SPDX-License-Identifier: BSD-2-Clause */ #if ! defined( SERVICE_CONFIGURATION_CLASS_HEADER ) #define SERVICE_CONFIGURATION_CLASS_HEADER class CServiceConfigurationA { protected: DWORD m_TypeOfService{ 0 }; DWORD m_WhenToStart{ 0 }; DWORD m_ErrorControl{ 0 }; DWORD m_Tag{ 0 }; std::string m_NameOfExecutableFile; std::string m_LoadOrderGroup; std::string m_StartName; std::string m_DisplayName; std::vector<std::string> m_Dependencies; public: CServiceConfigurationA() noexcept; explicit CServiceConfigurationA( _In_ _QUERY_SERVICE_CONFIGA const& source ) noexcept; explicit CServiceConfigurationA( _In_ _QUERY_SERVICE_CONFIGA const * source ) noexcept; explicit CServiceConfigurationA( _In_ CServiceConfigurationA const& source ) noexcept; explicit CServiceConfigurationA( _In_ CServiceConfigurationA const * source ) noexcept; virtual ~CServiceConfigurationA() = default; virtual void Copy( _In_ _QUERY_SERVICE_CONFIGA const& source ) noexcept; virtual void Copy( _In_ _QUERY_SERVICE_CONFIGA const * source ) noexcept; virtual void Copy( _In_ CServiceConfigurationA const& source ) noexcept; virtual void Copy( _In_ CServiceConfigurationA const * source ) noexcept; virtual void Empty( void ) noexcept; virtual void GetDependencies( _Out_ std::vector<std::string>& dependencies ) const noexcept; virtual void GetDisplayName( _Out_ std::string& display_name ) const noexcept; virtual _Check_return_ DWORD GetErrorControl( void ) const noexcept; virtual void GetLoadOrderGroup( _Out_ std::string& load_order_group ) const noexcept; virtual void GetNameOfExecutableFile( _Out_ std::string& name_of_executable ) const noexcept; virtual void GetStartName( _Out_ std::string& start_name ) const noexcept; virtual _Check_return_ DWORD GetTag( void ) const noexcept; virtual _Check_return_ DWORD GetTypeOfService( void ) const noexcept; virtual _Check_return_ DWORD GetWhenToStart( void ) const noexcept; virtual _Check_return_ CServiceConfigurationA& operator=( _In_ CServiceConfigurationA const& source ) noexcept; virtual _Check_return_ CServiceConfigurationA& operator=( _In_ _QUERY_SERVICE_CONFIGA const& source ) noexcept; #if defined( _DEBUG ) && ! defined( WFC_NO_DUMPING ) virtual void Dump( CDumpContext& dump_context ) const; #endif // _DEBUG }; class CServiceConfigurationW { protected: DWORD m_TypeOfService{0}; DWORD m_WhenToStart{0}; DWORD m_ErrorControl{0}; DWORD m_Tag{0}; std::wstring m_NameOfExecutableFile; std::wstring m_LoadOrderGroup; std::wstring m_StartName; std::wstring m_DisplayName; std::vector<std::wstring> m_Dependencies; public: CServiceConfigurationW() noexcept; explicit CServiceConfigurationW( _In_ _QUERY_SERVICE_CONFIGW const& source ) noexcept; explicit CServiceConfigurationW( _In_ _QUERY_SERVICE_CONFIGW const * source ) noexcept; explicit CServiceConfigurationW( _In_ CServiceConfigurationW const& source ) noexcept; explicit CServiceConfigurationW( _In_ CServiceConfigurationW const * source ) noexcept; virtual ~CServiceConfigurationW(); virtual void Copy( _In_ _QUERY_SERVICE_CONFIGW const& source ) noexcept; virtual void Copy( _In_ _QUERY_SERVICE_CONFIGW const * source ) noexcept; virtual void Copy( _In_ CServiceConfigurationW const& source ) noexcept; virtual void Copy( _In_ CServiceConfigurationW const * source ) noexcept; virtual void Empty( void ) noexcept; virtual void GetDependencies( _Out_ std::vector<std::wstring>& dependencies ) const noexcept; virtual void GetDisplayName( _Out_ std::wstring& display_name ) const noexcept; inline constexpr _Check_return_ DWORD GetErrorControl(void) const noexcept { return(m_ErrorControl); } virtual void GetLoadOrderGroup( _Out_ std::wstring& load_order_group ) const noexcept; virtual void GetNameOfExecutableFile( _Out_ std::wstring& name_of_executable ) const noexcept; virtual void GetStartName( _Out_ std::wstring& start_name ) const noexcept; inline constexpr _Check_return_ DWORD GetTag(void) const noexcept { return(m_Tag); } inline constexpr _Check_return_ DWORD GetTypeOfService(void) const noexcept { return(m_TypeOfService); } inline constexpr _Check_return_ DWORD GetWhenToStart(void) const noexcept { return(m_WhenToStart); } virtual _Check_return_ CServiceConfigurationW& operator=( _In_ CServiceConfigurationW const& source ) noexcept; virtual _Check_return_ CServiceConfigurationW& operator=( _In_ _QUERY_SERVICE_CONFIGW const& source ) noexcept; #if defined( _DEBUG ) && ! defined( WFC_NO_DUMPING ) virtual void Dump( CDumpContext& dump_context ) const; #endif // _DEBUG }; #if defined( UNICODE ) #define CServiceConfiguration CServiceConfigurationW #else #define CServiceConfiguration CServiceConfigurationA #endif // UNICODE #endif // SERVICE_CONFIGURATION_CLASS_HEADER
45.986755
117
0.751296
SammyB428
2b3437df2442f79b844247273b091143e02b3108
3,341
cpp
C++
Game.cpp
JankoDedic/TappyPlane
79b047e6343aaaa41fdf1281e4db9dfbb95bb0d2
[ "MIT" ]
1
2018-02-28T14:21:14.000Z
2018-02-28T14:21:14.000Z
Game.cpp
djanko1337/TappyPlane
79b047e6343aaaa41fdf1281e4db9dfbb95bb0d2
[ "MIT" ]
null
null
null
Game.cpp
djanko1337/TappyPlane
79b047e6343aaaa41fdf1281e4db9dfbb95bb0d2
[ "MIT" ]
1
2020-07-13T08:56:55.000Z
2020-07-13T08:56:55.000Z
#include "Game.hpp" #include "RectangleFunctions.hpp" #include "Renderer.hpp" namespace TappyPlane { using namespace SDLW::Video; using namespace SDLW::Events; constexpr auto backgroundSpritesheetHandle = "background"; constexpr auto backgroundBounds = canvasBounds; constexpr auto backgroundScrollSpeed = 0.5f; constexpr auto groundSpritesheetHandle = "ground"; constexpr Rectangle groundBounds{0, canvasBounds.height() - 270, canvasBounds.width(), 270}; constexpr auto groundScrollSpeed = 2.0f; constexpr int spikePairDistance{420}; constexpr int spikesScrollSpeed{5}; constexpr auto getReadySpritesheetHandle = "getReady"; constexpr Rectangle getReadyBounds{canvasBounds.width() / 2 - 907 / 2, canvasBounds.height() / 2 - 163 / 2, 907, 163}; constexpr auto gameOverSpritesheetHandle = "gameOver"; constexpr Rectangle gameOverBounds{canvasBounds.width() / 2 - 934 / 2, canvasBounds.height() / 2 - 176 / 2, 934, 176}; Game::Game() : mGameState(State::GetReady) , mBackground(backgroundSpritesheetHandle, backgroundBounds, backgroundScrollSpeed) , mGround(groundSpritesheetHandle, groundBounds, groundScrollSpeed) , mSpikes(spikePairDistance, spikesScrollSpeed) , mGetReadySprite(getReadySpritesheetHandle, getReadyBounds) , mGameOverSprite(gameOverSpritesheetHandle, gameOverBounds) { } void Game::handleEvent(const Event& event) noexcept { if (event.type() == Event::Type::MouseButtonDown) { switch (mGameState) { case State::GetReady: start(); break; case State::InProgress: mPlane.jump(); break; case State::GameOver: reset(); break; default: break; } } } void Game::update() noexcept { if (mGameState != State::InProgress) { return; } mBackground.update(); mGround.update(); mSpikes.update(); mPlane.update(); if (hasPlaneCrashed()) { mBackground.pause(); mGround.pause(); mSpikes.pause(); mPlane.pause(); mGameState = State::GameOver; } } void Game::draw() const { mBackground.draw(); mPlane.draw(); mSpikes.draw(); mGround.draw(); if (mGameState == State::GetReady) { mGetReadySprite.draw(); } else if (mGameState == State::GameOver) { mGameOverSprite.draw(); } } void Game::start() { mBackground.play(); mSpikes.play(); mGround.play(); mPlane.play(); mGameState = State::InProgress; } void Game::reset() { mPlane.reset(); mSpikes.reset(); mGameState = State::GetReady; } static bool areColliding(const Plane& plane, const Spikes& spikes) { for (auto[first, last] = spikes.bounds(); first < last; ++first) { if (areIntersecting(plane.bounds(), first->topSpikeBounds) || areIntersecting(plane.bounds(), first->bottomSpikeBounds)) { return true; } } return false; } bool Game::hasPlaneCrashed() { return areColliding(mPlane, mSpikes) || didPlaneHitTheGround() || didPlaneHitTheCeiling(); } bool Game::didPlaneHitTheGround() { return areIntersecting(mPlane.bounds(), mGround.bounds()); } bool Game::didPlaneHitTheCeiling() { return topOf(mPlane.bounds()) < topOf(canvasBounds); } } // namespace TappyPlane
24.566176
75
0.657887
JankoDedic
2b3c6494fcf05fd98c75d47ed901c2fa1affe08f
24,449
cpp
C++
src/article.cpp
taviso/mpgravity
f6a2a7a02014b19047e44db76ae551bd689c16ac
[ "BSD-3-Clause" ]
9
2020-04-01T04:15:22.000Z
2021-09-26T21:03:47.000Z
src/article.cpp
taviso/mpgravity
f6a2a7a02014b19047e44db76ae551bd689c16ac
[ "BSD-3-Clause" ]
17
2020-04-02T19:38:40.000Z
2020-04-12T05:47:08.000Z
src/article.cpp
taviso/mpgravity
f6a2a7a02014b19047e44db76ae551bd689c16ac
[ "BSD-3-Clause" ]
null
null
null
/*****************************************************************************/ /* SOURCE CONTROL VERSIONS */ /*---------------------------------------------------------------------------*/ /* */ /* Version Date Time Author / Comment (optional) */ /* */ /* $Log: article.cpp,v $ /* Revision 1.1 2010/07/21 17:14:56 richard_wood /* Initial checkin of V3.0.0 source code and other resources. /* Initial code builds V3.0.0 RC1 /* /* Revision 1.3 2009/08/25 20:04:25 richard_wood /* Updates for 2.9.9 /* /* Revision 1.2 2009/08/16 21:05:38 richard_wood /* Changes for V2.9.7 /* /* Revision 1.1 2009/06/09 13:21:28 richard_wood /* *** empty log message *** /* /* Revision 1.7 2008/09/19 14:51:10 richard_wood /* Updated for VS 2005 /* /* */ /*****************************************************************************/ /********************************************************************************** Copyright (c) 2003, Albert M. Choy 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 Microplanet, Inc. 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. **********************************************************************************/ /////////////////////////////////////////////////////////////////////////// // article.cpp - The outer object relays requests to the // inner object. This module is mostly fluff. // #include "stdafx.h" #include "afxmt.h" #include "article.h" #include "utilstr.h" #include "codepg.h" #include "tglobopt.h" #include "rgcomp.h" #include "8859x.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char BASED_CODE THIS_FILE[] = __FILE__; #endif // live and die at global scope TMemShack TArticleHeader::m_gsMemShack(sizeof(TArticleHeader), "Hdr"); static CCriticalSection sArtCritical; extern ULONG String_base64_decode (LPTSTR pInBuf, int nInSz, LPTSTR pOutBuf, int nOutSz); extern ULONG String_QP_decode (LPCTSTR pInBuf, int nInSz, LPTSTR pOutBuf, int nOutSz); int magic_isohdr_translate (LPCTSTR text, CString & strOut); // Used for RFC 2047 decoding in headers class TAnsiCodePage { public: TAnsiCodePage() { // Old Wisdom // ISO-8859-1 == LATIN 1 == CP 1252 // ISO-8859-2 == LATIN 2 == CP 1250 } // this is used strictly for SUBJECT and FROM lines BOOL CanTranslate(LPCTSTR pszText, int & iType, GravCharset * & rpCharset) { int unusedLen = 0; int ret = this->FindISOString ( pszText, unusedLen, rpCharset ); if (0==ret) return FALSE; else { iType = ret; return TRUE; } } // =========================================================== // return 1 for QP, 2 for B64, 0 for 'can not handle it' // // update ln - offset to start of good data (after 8859-15?Q?) // // example: // =?iso-8859-1?q?this=20is=20some=20text?= BOOL FindISOString (LPCTSTR cpIn, int & ln, GravCharset * & rpCharset) { CString strcp = cpIn; strcp.MakeLower(); LPCTSTR cp = strcp; LPTSTR pRes = 0; pRes = (LPSTR)strstr (cp, "=?"); if (NULL == pRes) return FALSE; if (NULL == *(pRes+2)) return FALSE; else { CString charsetName; LPTSTR pTravel = pRes + 2; int n=0; LPTSTR pTxt = charsetName.GetBuffer(strcp.GetLength()); while (*pTravel && ('?' != *pTravel)) { *pTxt++ = *pTravel++; n++; } charsetName.ReleaseBuffer(n); // use the map for a fast lookup rpCharset = gsCharMaster.findByName( charsetName ); if (NULL == rpCharset) return FALSE; if (NULL == *pTravel) // pTravel should point to the ?q? or ?b? return FALSE; ASSERT('?' == *pTravel); ++pTravel; TCHAR cEncoding = *pTravel; int ret = 0; if (NULL == cEncoding) return 0; if ('q' == cEncoding) ret = 1; else if ('b' == cEncoding) ret = 2; else return ret; ++pTravel; // point to 2nd ? if ((NULL == *pTravel) || ('?' != *pTravel)) return 0; ++pTravel; // point to start of data ln = pTravel - cp; return ret; } } }; static TAnsiCodePage gsCodePage; /////////////////////////////////////////////////////////////////////////// // TPersist822Header // #if defined(_DEBUG) void TPersist822Header::Dump(CDumpContext& dc) const { TBase822Header::Dump( dc ); m_pRep->Dump (dc); dc << "TPersist822Hdr\n" ; } #endif /////////////////////////////////////////////////////////////////////////// // Destructor TPersist822Header::TPersist822Header() { m_pRep = 0; // the derived classes must instantiate the Inner representation } /////////////////////////////////////////////////////////////////////////// // copy-constructor TPersist822Header::TPersist822Header(const TPersist822Header& src) { m_pRep = src.m_pRep; m_pRep->AddRef (); } /////////////////////////////////////////////////////////////////////////// // Destructor TPersist822Header::~TPersist822Header() { try { ASSERT(m_pRep); m_pRep->DeleteRef (); } catch(...) { // catch everything - no exceptions can leave a destructor } } void TPersist822Header::copy_on_write() { if (m_pRep->iGetRefCount() == 1) return; // call virt function to make the right kind of object TPersist822HeaderInner * pCpyInner = m_pRep->duplicate(); TPersist822HeaderInner * pOriginal = m_pRep; m_pRep = pCpyInner; // I now have a fresh copy all to myself pOriginal->DeleteRef(); // you have 1 less client } /////////////////////////////////////////////////////////////////////////// // NOTE: ask Al before using this function // // 5-01-96 amc Created void TPersist822Header::PrestoChangeo_AddReferenceCount() { ASSERT(m_pRep); m_pRep->AddRef (); // you have 1 more client } void TPersist822Header::PrestoChangeo_DelReferenceCount() { ASSERT(m_pRep); m_pRep->DeleteRef (); // you have 1 less client } void TPersist822Header::SetNumber(LONG n) { copy_on_write(); m_pRep->SetNumber(n); } void TPersist822Header::SetLines (int lines) { copy_on_write(); m_pRep->SetLines ( lines ); } void TPersist822Header::SetLines (const CString& body) { copy_on_write(); m_pRep->SetLines ( body ); } void TPersist822Header::StampCurrentTime() { copy_on_write(); m_pRep->StampCurrentTime(); } void TPersist822Header::SetMimeLines(LPCTSTR ver, LPCTSTR type, LPCTSTR encode, LPCTSTR desc) { copy_on_write(); // the inner function is virtual m_pRep->SetMimeLines (ver, type, encode, desc); } void TPersist822Header::GetMimeLines(CString* pVer, CString* pType, CString* pCode, CString* pDesc) { // the inner function is virtual m_pRep->GetMimeLines (pVer, pType, pCode, pDesc); } void TPersist822Header::Serialize(CArchive & archive) { // the inner function is virtual m_pRep->Serialize ( archive ); } TPersist822Header & TPersist822Header::operator=(const TPersist822Header &rhs) { if (&rhs == this) return *this; m_pRep->DeleteRef(); // he has one less client m_pRep = rhs.m_pRep; // copy ptr m_pRep->AddRef (); // you have 1 more client return *this; } ///// end TPersist822Header /////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// // TArticleHeader // TArticleHeader::TArticleHeader() { // set object version m_pRep = new TArticleHeaderInner(TArticleHeaderInner::kVersion); } // Destructor TArticleHeader::~TArticleHeader() { /* empty */ } TArticleHeader& TArticleHeader::operator=(const TArticleHeader &rhs) { if (&rhs == this) return *this; TPersist822Header::operator=(rhs); return *this; } /////////////////////////////////////////////////////////////////////////// ULONG TArticleHeader::ShrinkMemPool() { if (true) { CSingleLock sLock(&sArtCritical, TRUE); ULONG u1 = TArticleHeader::m_gsMemShack.Shrink (); } ULONG u2 = TArticleHeaderInner::ShrinkMemPool(); return u2; } #if defined(_DEBUG) void TArticleHeader::Dump(CDumpContext& dc) const { // base class version TPersist822Header::Dump(dc); dc << "ArtHdr\n" ; } #endif ///// member functions void TArticleHeader::FormatExt(const CString& control, CString& strLine) { GetPA()->FormatExt (control, strLine); } void TArticleHeader::SetArticleNumber (LONG artInt) { copy_on_write(); m_pRep->SetNumber(artInt); } void TArticleHeader::SetDate(LPCTSTR date_line) { copy_on_write(); GetPA()->SetDate ( date_line ); } LPCTSTR TArticleHeader::GetDate(void) { return GetPA()->GetDate (); } void TArticleHeader::AddNewsGroup (LPCTSTR ngroup) { copy_on_write(); GetPA()->AddNewsGroup ( ngroup ); } void TArticleHeader::GetNewsGroups (CStringList* pList) const { GetPA()->GetNewsGroups ( pList ); } int TArticleHeader::GetNumOfNewsGroups () const { return GetPA()->GetNumOfNewsGroups (); } void TArticleHeader::ClearNewsGroups () { copy_on_write(); GetPA()->ClearNewsGroups (); } BOOL TArticleHeader::operator<= (const TArticleHeader & rhs) { return (*GetPA()) <= ( *(rhs.GetPA()) ); } void TArticleHeader::SetControl (LPCTSTR control) { copy_on_write(); GetPA()->SetControl ( control ); } LPCTSTR TArticleHeader::GetControl () { return GetPA()->GetControl (); } void TArticleHeader::SetDistribution(LPCTSTR dist) { copy_on_write(); GetPA()->SetDistribution (dist); } LPCTSTR TArticleHeader::GetDistribution() { return GetPA()->GetDistribution(); } void TArticleHeader::SetExpires(LPCTSTR dist) { copy_on_write(); GetPA()->SetExpires (dist); } LPCTSTR TArticleHeader::GetExpires() { return GetPA()->GetExpires(); } // user sets what groups to Followup-To void TArticleHeader::SetFollowup(LPCTSTR follow) { copy_on_write(); GetPA()->SetFollowup(follow); } LPCTSTR TArticleHeader::GetFollowup(void) const { return GetPA()->GetFollowup(); } void TArticleHeader::SetOrganization(LPCTSTR org) { copy_on_write(); GetPA()->SetOrganization(org); } LPCTSTR TArticleHeader::GetOrganization() { return GetPA()->GetOrganization(); } void TArticleHeader::SetKeywords(LPCTSTR keywords) { copy_on_write(); GetPA()->SetKeywords(keywords); } LPCTSTR TArticleHeader::GetKeywords(void) { return GetPA()->GetKeywords(); } void TArticleHeader::SetSender(LPCTSTR sndr) { copy_on_write(); GetPA()->SetSender(sndr); } LPCTSTR TArticleHeader::GetSender(void) { return GetPA()->GetSender(); } void TArticleHeader::SetReplyTo(LPCTSTR replyto) { copy_on_write(); GetPA()->SetReplyTo(replyto); } LPCTSTR TArticleHeader::GetReplyTo() { return GetPA()->GetReplyTo(); } void TArticleHeader::SetSummary(LPCTSTR sum) { copy_on_write(); GetPA()->SetSummary (sum); } LPCTSTR TArticleHeader::GetSummary(void) { return GetPA()->GetSummary(); } void TArticleHeader::SetXRef(LPCTSTR xref) { copy_on_write(); GetPA()->SetXRef(xref); } LPCTSTR TArticleHeader::GetXRef(void) { return GetPA()->GetXRef(); } // ------------------------------------------------------------------ // // void TArticleHeader::SetQPFrom (const CString & from) { copy_on_write(); // put it in GetPA()->SetFrom (from); } void TArticleHeader::SetFrom (const CString & from) { GetPA()->SetFrom (from); } CString TArticleHeader::GetFrom () { return GetPA()->GetFrom (); } const CString & TArticleHeader::GetOrigFrom(void) { return GetPA()->GetOrigFrom (); } void TArticleHeader::SetOrigFrom(const CString & f) { GetPA()->SetOrigFrom(f); } const CString & TArticleHeader::GetPhrase(void) { return GetPA()->GetPhrase(); } void TArticleHeader::SetMessageID (LPCTSTR msgid) { copy_on_write(); GetPA()->SetMessageID(msgid); } LPCTSTR TArticleHeader::GetMessageID(void) { return GetPA()->GetMessageID(); } int handle_2hex_digits (LPCTSTR cp, TCHAR & cOut) { BYTE e; TCHAR c, c2; if ((NULL == (c = cp[1])) || (NULL == (c2 = cp[2]))) return 1; if (!isxdigit (c)) /* must be hex! */ return 1; if (isdigit (c)) e = c - '0'; else e = c - (isupper (c) ? 'A' - 10 : 'a' - 10); c = c2; /* snarf next character */ if (!isxdigit (c)) /* must be hex! */ return 1; if (isdigit (c)) c -= '0'; else c -= (isupper (c) ? 'A' - 10 : 'a' - 10); cOut = TCHAR( BYTE( (e << 4) + c) ); /* merge the two hex digits */ return 0; } // ---------------------------------------------------------- // handle 2047 translation // struct T2047Segment { T2047Segment(LPCTSTR txt, bool fWS0) : fWS(fWS0), text(txt) { iEncodingType = 0; len = 0; } bool fWS; CString text; int iEncodingType; int len; }; typedef T2047Segment* P2047Segment; inline bool is_lwsp(TCHAR c) { if (' ' == c || '\t' == c) return true; else return false; } LPCTSTR read_ws_token (LPCTSTR pTrav, LPTSTR pToken) { while (*pTrav && is_lwsp(*pTrav)) *pToken++ = *pTrav++; *pToken = 0; return pTrav; } LPCTSTR read_black_token (LPCTSTR pTrav, LPTSTR pToken) { while (*pTrav && !is_lwsp(*pTrav)) *pToken++ = *pTrav++; *pToken = 0; return pTrav; } // ---------------------------------------------------------- int magic_hdr2047_segmentize ( LPCSTR subject, CTypedPtrArray<CPtrArray, P2047Segment> & listSegments, LPTSTR rcToken) { LPCTSTR pTrav = subject; while (*pTrav) { if (is_lwsp(*pTrav)) { pTrav = read_ws_token (pTrav, rcToken); listSegments.Add ( new T2047Segment(rcToken, true) ); } else { pTrav = read_black_token (pTrav, rcToken); listSegments.Add ( new T2047Segment(rcToken, false) ); } } return 0; } // ---------------------------------------------------------- // Example 1: // Subject: Hobbits v Sm=?ISO-8859-1?B?6Q==?=agol // This is incorrectly encoded // // Subject: =?Windows-1252?Q?Re:_Hobbits_v_Sm=E9agol?= // // this is better, since the encoded word is 1 ATOM (see rfc2047 section 5) // // HOWEVER, to be generous, I handle the top case now // int segment_2047_translate (T2047Segment * pS1, LPTSTR rcToken) { LPCTSTR cp = pS1->text; TCHAR c; int ret = 0; std::istrstream in_stream(const_cast<LPTSTR>(cp)); std::ostrstream out_stream(rcToken, 4096 * 4); std::vector<BYTE> vEncodedBytes; bool insideEncodedWord = false; int questionCount; while (in_stream.get(c)) { if (!insideEncodedWord) { if ('=' == c && '?' == TCHAR(in_stream.peek())) { insideEncodedWord = true; questionCount = 0; ret = 1; // set return to error } else { out_stream.put( c ); } } else { if (questionCount < 3) { if (c == '?') { questionCount++; } } else { if (c == '?' && TCHAR(in_stream.peek()) == '=') { in_stream.get(c); //eat = TCHAR rcDecoded[4024]; ULONG uLen; vEncodedBytes.push_back(0); LPTSTR psz=reinterpret_cast<LPTSTR>(&vEncodedBytes[0]); if (2 == pS1->iEncodingType) uLen = String_base64_decode (psz, vEncodedBytes.size()-1, rcDecoded, sizeof(rcDecoded)); else uLen = String_QP_decode (psz, vEncodedBytes.size()-1, rcDecoded, sizeof(rcDecoded)); for (int n = 0; n < uLen; ++n) out_stream.put (rcDecoded[n]); insideEncodedWord = false; vEncodedBytes.clear(); ret = 0; } else { vEncodedBytes.push_back((1 == pS1->iEncodingType && '_' == c) ? ' ' : c); } } } // end insideEW } // while // final cleanup if (0 == ret) { out_stream.put(0); pS1->text = rcToken; } return ret; } // ---------------------------------------------------------- int magic_hdr2047_translate (LPCSTR subject, CString & strOut) { TCHAR rcToken[4096 * 4]; CTypedPtrArray<CPtrArray, P2047Segment> listSegments; int iStat=0; magic_hdr2047_segmentize (subject, listSegments, rcToken); int sz = listSegments.GetSize(); int i; for (i = 0; i < sz; i++) { T2047Segment * pSeg = listSegments[i]; GravCharset * pCharsetDummy = 0; int encType = gsCodePage.FindISOString (pSeg->text, pSeg->len, pCharsetDummy); pSeg->iEncodingType = encType; } // drop LWSP segments in between encoded words for (i = 0; i < listSegments.GetSize(); i++) { T2047Segment* pS1 = listSegments[i]; if ((i+2) < listSegments.GetSize()) { T2047Segment* pS2 = listSegments[i+1]; T2047Segment* pS3 = listSegments[i+2]; if (pS1->iEncodingType && !pS1->text.IsEmpty() && pS2->fWS && pS3->iEncodingType && !pS3->text.IsEmpty()) { delete pS2; listSegments.RemoveAt (i+1); } } } // per segment translate for (i = 0; i < listSegments.GetSize(); i++) { T2047Segment* pS1 = listSegments[i]; if (pS1->iEncodingType) { iStat = segment_2047_translate (pS1, rcToken); if (iStat) break; } } // cleanup and build final string for (i = 0; i < listSegments.GetSize(); i++) { T2047Segment* pS1 = listSegments[i]; if (0 == iStat) strOut += pS1->text; delete pS1; } return iStat; } // ---------------------------------------------------------- int magic_isohdr_translate (LPCSTR subject, CString & strOut) { // do QP translation here // ex: // =?iso-8859-1?q?this=20is=20some=20text?= int iType = 0; GravCharset * pCharset = 0; if (FALSE == gsCodePage.CanTranslate(subject, iType, pCharset)) { // this may be untagged eight bit if ( using_hibit(subject) ) { int iSendCharset = gpGlobalOptions->GetRegCompose()->GetSendCharset(); GravCharset* pCharsetUser = gsCharMaster.findById( iSendCharset ); return CP_Util_Inbound (pCharsetUser, subject, lstrlen(subject), strOut); } else return 1; } CString strBytes; int stat = magic_hdr2047_translate (subject, strBytes); if (stat) return stat; // go from bytes to chars return CP_Util_Inbound ( pCharset, strBytes, strBytes.GetLength(), strOut); } // ---------------------------------------------------------- void TArticleHeader::SetQPSubject(LPCTSTR subject, LPCTSTR pszFrom) { copy_on_write(); CString strOut; // do QP translation here if (0 == magic_isohdr_translate (subject, strOut)) GetPA()->SetSubject(strOut); else GetPA()->SetSubject(subject); } void TArticleHeader::SetSubject(LPCTSTR subject) { copy_on_write(); GetPA()->SetSubject(subject); } LPCTSTR TArticleHeader::GetSubject (void) { return GetPA()->GetSubject(); } void TArticleHeader::GetDestList(TStringList* pList) const { GetPA()->GetDestList (pList); } void TArticleHeader::Format (CString& strLine) { GetPA()->Format(strLine); } int TArticleHeader::ParseFrom (CString& phrase, CString& address) { return GetPA()->ParseFrom(phrase, address); } void TArticleHeader::SetReferences (const CString& refs) { copy_on_write(); GetPA()->SetReferences (refs); } void TArticleHeader::SetCustomHeaders (const CStringList &sCustomHeaders) { copy_on_write(); GetPA()->SetCustomHeaders (sCustomHeaders); } const CStringList &TArticleHeader::GetCustomHeaders () const { return GetPA()->GetCustomHeaders(); } BOOL TArticleHeader::AtRoot(void) { return GetPA()->AtRoot(); } BOOL TArticleHeader::FindInReferences(const CString& msgID) { return GetPA()->FindInReferences(msgID); } int TArticleHeader::GetReferencesCount() { return GetPA()->GetReferencesCount(); } void TArticleHeader::CopyReferences(const TArticleHeader & src) { copy_on_write(); GetPA()->CopyReferences( *(src.GetPA()) ); } void TArticleHeader::ConstructReferences(const TArticleHeader & src, const CString& msgid) { GetPA()->ConstructReferences(*(src.GetPA()), msgid); } void TArticleHeader::GetDadRef(CString& str) { GetPA()->GetDadRef (str); } void TArticleHeader::GetFirstRef(CString& str) { GetPA()->GetFirstRef(str); } void TArticleHeader::GetReferencesWSList(CString& line) { GetPA()->GetReferencesWSList(line); } void TArticleHeader::GetReferencesStringList(CStringList* pList) { GetPA()->GetReferencesStringList(pList); } const TFlatStringArray &TArticleHeader::GetReferences () { return GetPA()->GetReferences(); } // end of TArticle Implementation /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// // TEmailHeader // TEmailHeader::TEmailHeader() { m_pRep = new TEmailHeaderInner(TEmailHeaderInner::kVersion); // object version is 1 } // Empty destructor TEmailHeader::~TEmailHeader() { /* empty */ } TEmailHeader& TEmailHeader::operator=(const TEmailHeader &rhs) { if (&rhs == this) return *this; TPersist822Header::operator=(rhs); // do normal stuff return *this; } void TEmailHeader::Set_InReplyTo (LPCTSTR irt) { copy_on_write(); GetPE()->Set_InReplyTo(irt); } LPCTSTR TEmailHeader::Get_InReplyTo () { return GetPE()->Get_InReplyTo(); } int TEmailHeader::GetDestinationCount(TBase822Header::EAddrType eAddr) { return GetPE()->GetDestinationCount(eAddr); } void TEmailHeader::ParseTo(const CString & to, TStringList * pOutList /* = 0 */, CStringList * pErrList /* = 0 */) { if (0 == pOutList) copy_on_write(); GetPE()->ParseTo (to, pOutList, pErrList); } void TEmailHeader::GetToText(CString& txt) { GetPE()->GetToText (txt); } // CC - store the comma separated list of addresses void TEmailHeader::ParseCC(const CString& comma_sep_CC_list, TStringList * pOutList /* = 0 */, CStringList * pErrList /* = 0 */) { if (0 == pOutList) copy_on_write(); GetPE()->ParseCC (comma_sep_CC_list, pOutList, pErrList); } // CC - get the displayable text, separated by commas void TEmailHeader::GetCCText(CString& txt) { GetPE()->GetCCText ( txt ); } // BCC - store the comma separated list of addresses void TEmailHeader::ParseBCC(const CString& comma_sep_BCC_list, TStringList * pOutList /* = 0 */, CStringList * pErrList /* = 0 */) { if (0 == pOutList) copy_on_write(); GetPE()->ParseBCC ( comma_sep_BCC_list, pOutList, pErrList ); } // BCC - get the displayable text, separated by commas void TEmailHeader::GetBCCText(CString& txt) { GetPE()->GetBCCText ( txt ); } void TEmailHeader::GetDestinationList (TBase822Header::EAddrType eAddr, TStringList * pstrList) const { GetPE()->GetDestinationList(eAddr, pstrList); } // end of file
24.4002
95
0.598961
taviso
2b3f56c43262005553a7666cdfa8b342238ac1bd
3,199
hpp
C++
attributes/attribute.hpp
5cript/electronpp
03e257d62f2b939544c5d1c2d8718e58f2d71e34
[ "MIT" ]
null
null
null
attributes/attribute.hpp
5cript/electronpp
03e257d62f2b939544c5d1c2d8718e58f2d71e34
[ "MIT" ]
null
null
null
attributes/attribute.hpp
5cript/electronpp
03e257d62f2b939544c5d1c2d8718e58f2d71e34
[ "MIT" ]
null
null
null
#pragma once #include "generic_attribute.hpp" #include "../util/observer.hpp" #include <emscripten/val.h> #include <functional> #include <iostream> namespace CppDom::Attributes { template <typename ValueT> class Attribute : public GenericAttribute { public: Attribute(std::string name, ValueT value) : name_{std::move(name)} , value_{std::move(value)} { } void setOn(emscripten::val& node) override { using emscripten::val; node.call<val>("setAttribute", val(name_), val(value_)); } Attribute* clone() const override { return new Attribute(name_, value_); } Attribute(Attribute const&) = default; Attribute(Attribute&&) = default; private: std::string name_; ValueT value_; }; class ComplexAttribute : public GenericAttribute { public: ComplexAttribute(std::function <void(emscripten::val&)> setOn) : GenericAttribute{} , setOn_{setOn} { } void setOn(emscripten::val& node) override { setOn_(node); } ComplexAttribute* clone() const override { return new ComplexAttribute(setOn_); } private: std::function <void(emscripten::val&)> setOn_; }; template <typename ValueT> class ReactiveAttribute : public GenericAttribute { public: ReactiveAttribute(std::string name, SharedObserver<ValueT> value) : name_{std::move(name)} , value_{std::move(value)} { value_.subscribe(this); } ~ReactiveAttribute() { value_.unsubscribe(this); } operator=(ReactiveAttribute const&) = delete; ReactiveAttribute(ReactiveAttribute const&) = delete; void setOn(emscripten::val& node) override { using emscripten::val; node.call<val>("setAttribute", val(name_), val(static_cast <ValueT&>(value_))); parent_ = &node; } void update() override { std::cout << "update reactive\n"; using emscripten::val; if (parent_ != nullptr) parent_->call<val>("setAttribute", val(name_), val(static_cast <ValueT&>(value_))); } ReactiveAttribute* clone() const override { return new ReactiveAttribute(name_, value_); } private: emscripten::val* parent_; std::string name_; SharedObserver<ValueT> value_; }; } #define MAKE_HTML_STRING_ATTRIBUTE(NAME) \ namespace CppDom::Attributes \ { \ struct NAME ## _ { \ Attribute <char const*> operator=(char const* val) \ { \ return {#NAME, std::move(val)}; \ } \ template <typename T> \ ReactiveAttribute <T> operator=(SharedObserver<T> observed) \ { \ return {#NAME, std::move(observed)}; \ } \ } NAME; \ }
26.438017
100
0.530166
5cript
2b422105b1d620f109831fd004da587a0acba6f1
3,431
cpp
C++
goldfilter/win32/msgpack_server.cpp
orinocoz/dripcap
096f464e8855da9882fbf0ec3294ff6d7e329dc9
[ "MIT" ]
5
2019-12-20T05:48:26.000Z
2021-10-13T12:32:50.000Z
goldfilter/win32/msgpack_server.cpp
orinocoz/dripcap
096f464e8855da9882fbf0ec3294ff6d7e329dc9
[ "MIT" ]
null
null
null
goldfilter/win32/msgpack_server.cpp
orinocoz/dripcap
096f464e8855da9882fbf0ec3294ff6d7e329dc9
[ "MIT" ]
2
2020-03-07T11:40:38.000Z
2022-01-24T22:37:40.000Z
#include "msgpack_server.hpp" #include <msgpack.hpp> typedef long ssize_t; typedef std::basic_string<TCHAR> tstring; inline void operator<<(tstring &t, const std::string &s) { #ifdef _UNICODE if (s.size() > 0) { t.resize(s.size() + 1); size_t length = 0; mbstowcs_s(&length, &t[0], t.size(), s.c_str(), _TRUNCATE); t.resize(length); } else { t.clear(); } #else t = s; #endif } class Reply : public ReplyInterface { public: Reply(HANDLE pipe, uint32_t id); bool write(const char *data, std::size_t length); uint32_t id() const; private: HANDLE hPipe; uint32_t callid; }; Reply::Reply(HANDLE pipe, uint32_t id) : hPipe(pipe), callid(id) { } bool Reply::write(const char *data, std::size_t len) { DWORD length = 0; WriteFile(hPipe, data, len, &length, NULL); return length > 0; } uint32_t Reply::id() const { return callid; } class MsgpackServer::Private { public: Private(); ~Private(); public: tstring path; std::unordered_map<std::string, MsgpackCallback> handlers; HANDLE hPipe; bool active; }; MsgpackServer::Private::Private() : active(false) { } MsgpackServer::Private::~Private() { } MsgpackServer::MsgpackServer(const std::string &path) : d(new Private()) { d->path << path; } MsgpackServer::~MsgpackServer() { delete d; } void MsgpackServer::handle(const std::string &command, const MsgpackCallback &func) { if (func) { d->handlers[command] = func; } else { d->handlers.erase(command); } } bool MsgpackServer::start() { auto spd = spdlog::get("console"); size_t const try_read_size = 256; d->hPipe = CreateNamedPipe(d->path.c_str(), PIPE_ACCESS_DUPLEX, PIPE_TYPE_BYTE, 1, try_read_size, try_read_size, 1000, NULL); if (d->hPipe == INVALID_HANDLE_VALUE) { spd->error("CreateNamedPipe() failed"); return false; } if (!ConnectNamedPipe(d->hPipe, NULL)) { spd->error("ConnectNamedPipe() failed"); return false; } msgpack::unpacker unp; d->active = true; while (d->active) { unp.reserve_buffer(try_read_size); DWORD actual_read_size = 0; if (!ReadFile(d->hPipe, unp.buffer(), try_read_size, &actual_read_size, NULL)) { spd->error("ReadFile() failed"); break; } unp.buffer_consumed(actual_read_size); msgpack::object_handle result; while (unp.next(result)) { msgpack::object obj(result.get()); spd->debug("recv: {}", obj); try { const auto &tuple = obj.as<std::tuple<std::string, uint32_t, msgpack::object>>(); const auto &it = d->handlers.find(std::get<0>(tuple)); if (it != d->handlers.end()) { Reply reply(d->hPipe, std::get<1>(tuple)); (it->second)(std::get<2>(tuple), reply); } } catch (const std::bad_cast &err) { spd->error("msgpack decoding error: {}", err.what()); } if (!d->active) break; } } CloseHandle(d->hPipe); return true; } bool MsgpackServer::stop() { if (d->active) { d->active = false; return true; } return false; }
21.179012
97
0.558146
orinocoz
2b423a2bbdd5dc4457462f2f23e00bd3dc3cf5b4
190
cpp
C++
flare_skia/src/skr_actor_star.cpp
taehyub/flare_cpp
7731bc0bcf2ce721f103586a48f74aa5c12504e8
[ "MIT" ]
14
2019-04-29T15:17:24.000Z
2020-12-30T12:51:05.000Z
flare_skia/src/skr_actor_star.cpp
taehyub/flare_cpp
7731bc0bcf2ce721f103586a48f74aa5c12504e8
[ "MIT" ]
null
null
null
flare_skia/src/skr_actor_star.cpp
taehyub/flare_cpp
7731bc0bcf2ce721f103586a48f74aa5c12504e8
[ "MIT" ]
6
2019-04-29T15:17:25.000Z
2021-11-16T03:20:59.000Z
#include "flare_skia/skr_actor_star.hpp" using namespace flare; SkrActorStar::SkrActorStar() : SkrActorBasePath(this) {} void SkrActorStar::invalidateDrawable() { m_IsPathValid = false; }
27.142857
66
0.784211
taehyub
2b4df60058134010d44cb4d759db34fe24b65a3b
7,330
cpp
C++
src/gameworld/gameworld/other/fb/rolestoryfb.cpp
mage-game/metagame-xm-server
193b67389262803fe0eae742800b1e878b5b3087
[ "MIT" ]
3
2021-12-16T13:57:28.000Z
2022-03-26T07:50:08.000Z
src/gameworld/gameworld/other/fb/rolestoryfb.cpp
mage-game/metagame-xm-server
193b67389262803fe0eae742800b1e878b5b3087
[ "MIT" ]
null
null
null
src/gameworld/gameworld/other/fb/rolestoryfb.cpp
mage-game/metagame-xm-server
193b67389262803fe0eae742800b1e878b5b3087
[ "MIT" ]
1
2022-03-26T07:50:11.000Z
2022-03-26T07:50:11.000Z
#include "rolestoryfb.hpp" #include "obj/character/role.h" #include "config/logicconfigmanager.hpp" #include "other/vip/vipconfig.hpp" #include "other/fb/storyfbconfig.hpp" #include "servercommon/errornum.h" #include "protocal/msgfb.h" #include "other/event/eventhandler.hpp" #include "monster/monsterpool.h" #include "gameworld/world.h" #include "servercommon/string/gameworldstr.h" #include "scene/scene.h" #include "item/itempool.h" #include "item/knapsack.h" #include "other/route/mailroute.hpp" #include "global/worldstatus/worldstatus.hpp" #include "global/usercache/usercache.hpp" #include "other/vip/vip.hpp" #include "other/daycounter/daycounter.hpp" RoleStoryFB::RoleStoryFB() : m_role(NULL) { } RoleStoryFB::~RoleStoryFB() { } void RoleStoryFB::Init(Role *role, const StoryFBParam &param) { m_role = role; m_param = param; } void RoleStoryFB::GetInitParam(StoryFBParam *param) { *param = m_param; } void RoleStoryFB::OnDayChange(unsigned int old_dayid, unsigned int now_dayid) { for (int i = 0; i < FB_STORY_MAX_COUNT; i++) { m_param.fb_list[i].today_times = 0; } this->SendInfo(); } bool RoleStoryFB::CanEnter(int fb_index) { if (fb_index < 0 || fb_index >= FB_STORY_MAX_COUNT) { return false; } if (fb_index > 0 && !this->IsPassLevel(fb_index - 1) && 0 == m_param.fb_list[fb_index - 1].today_times) { m_role->NoticeNum(errornum::EN_PRVE_FB_NOT_COMPLETED); return false; } const StoryFBLevelCfg::ConfigItem *level_cfg = LOGIC_CONFIG->GetStoryFBConfig().GetLevelCfg(fb_index); if (NULL == level_cfg) { return false; } if (m_role->GetLevel() < level_cfg->role_level) { m_role->NoticeNum(errornum::EN_STORY_FB_FUN_OPEN_LEVEL_LIMIT); return false; } if (m_param.fb_list[fb_index].today_times >= level_cfg->free_times) { m_role->NoticeNum(errornum::EN_STORY_FB_TIMES_LIMIT); return false; } return true; } void RoleStoryFB::OnEnterFB(int fb_index) { if (fb_index < 0 || fb_index >= FB_STORY_MAX_COUNT) { return; } m_param.curr_fb_index = fb_index; m_param.fb_list[fb_index].today_times++; m_role->GetDayCounter()->DayCountSet(DayCounter::DAYCOUNT_ID_FB_STORY, 1); this->SendInfo(); } void RoleStoryFB::AutoFBReqOne(int fb_index) { Scene *scene = m_role->GetScene(); if (NULL == scene) { return; } if (Scene::SCENE_TYPE_STORY_FB == scene->GetSceneType()) { m_role->NoticeNum(errornum::EN_FB_OPERATE_LIMIT); return; } if (fb_index < 0 || fb_index >= FB_STORY_MAX_COUNT) { return; } const StoryFBLevelCfg::ConfigItem *level_cfg = LOGIC_CONFIG->GetStoryFBConfig().GetLevelCfg(fb_index); if (NULL == level_cfg) { return; } if (0 == m_param.fb_list[fb_index].is_pass) { m_role->NoticeNum(errornum::EN_STORY_FB_NO_PASS); return; } if (m_param.fb_list[fb_index].today_times >= level_cfg->free_times) { const int vip_buy_times = LOGIC_CONFIG->GetVipConfig().GetAuthParam(m_role->GetVip()->GetVipLevel(), VAT_FB_STROY_COUNT); if (m_param.fb_list[fb_index].today_times >= level_cfg->free_times + vip_buy_times) { m_role->NoticeNum(errornum::EN_BUY_STROY_FB_TIME_LIMIT); return; } if (level_cfg->reset_gold > 0 && !m_role->GetKnapsack()->GetMoney()->AllGoldMoreThan(level_cfg->reset_gold)) { m_role->NoticeNum(errornum::EN_GOLD_NOT_ENOUGH); return; } } ItemConfigData reward_item_list[MonsterInitParam::MAX_DROP_ITEM_COUNT]; int index_count = MonsterInitParam::MAX_DROP_ITEM_COUNT; long long reward_exp = 0; for(int i = 0; i < level_cfg->monster_count && i < StoryFBLevelCfg::MONSTER_COUNT_MAX; i++) { if (0 != level_cfg->monster_id_list[i]) { MONSTERPOOL->GetMonsterDrop(level_cfg->monster_id_list[i], reward_item_list, &index_count, &reward_exp, NULL, NULL); } } short item_count = 0; for (int j = 0; j < index_count && j < MonsterInitParam::MAX_DROP_ITEM_COUNT; j++) { if (0 == reward_item_list[j].item_id) { break; } item_count++; } if (m_param.fb_list[fb_index].today_times >= level_cfg->free_times && !m_role->GetKnapsack()->GetMoney()->UseAllGold(level_cfg->reset_gold, "StoryFBAuto")) { m_role->NoticeNum(errornum::EN_GOLD_NOT_ENOUGH); return; } m_param.fb_list[fb_index].today_times++; EventHandler::Instance().OnAutoFbStory(m_role); m_role->AddExp(reward_exp, "StoryFBAuto", Role::EXP_ADD_REASON_DEFAULT); if (item_count > 0) { m_role->GetKnapsack()->PutList(item_count, reward_item_list, PUT_REASON_STORY_FB); } this->SendInfo(); } void RoleStoryFB::AutoFBReqAll() { Scene *scene = m_role->GetScene(); if (NULL == scene) { return; } if (Scene::SCENE_TYPE_STORY_FB == scene->GetSceneType()) { m_role->NoticeNum(errornum::EN_FB_OPERATE_LIMIT); return; } bool is_auto_succ = false; for(int i = 0; i < FB_STORY_MAX_COUNT; i ++) { const StoryFBLevelCfg::ConfigItem *level_cfg = LOGIC_CONFIG->GetStoryFBConfig().GetLevelCfg(i); if (NULL == level_cfg) { break; } if (0 == m_param.fb_list[i].is_pass) { continue; } if (m_param.fb_list[i].today_times >= level_cfg->free_times) { continue; } ItemConfigData reward_item_list[MonsterInitParam::MAX_DROP_ITEM_COUNT]; int index_count = MonsterInitParam::MAX_DROP_ITEM_COUNT; long long reward_exp = 0; for(int j = 0; j < level_cfg->monster_count && j < StoryFBLevelCfg::MONSTER_COUNT_MAX; j++) { if (0 != level_cfg->monster_id_list[j]) { MONSTERPOOL->GetMonsterDrop(level_cfg->monster_id_list[j], reward_item_list, &index_count, &reward_exp, NULL, NULL); } } short item_count = 0; for(int k = 0; k < index_count && k < MonsterInitParam::MAX_DROP_ITEM_COUNT; k++) { if (0 == reward_item_list[i].item_id) { break; } item_count++; } is_auto_succ = true; m_param.fb_list[i].today_times++; m_role->AddExp(reward_exp, "StoryFBAuto", Role::EXP_ADD_REASON_DEFAULT); if (index_count > 0) { m_role->GetKnapsack()->PutList(item_count, reward_item_list , PUT_REASON_STORY_FB); } EventHandler::Instance().OnAutoFbStory(m_role); } if (is_auto_succ) { m_role->GetDayCounter()->DayCountSet(DayCounter::DAYCOUNT_ID_FB_STORY, 1); this->SendInfo(); } else { m_role->NoticeNum(errornum::EN_STORY_FB_NOT_LEVEL); } } void RoleStoryFB::SendInfo() { static Protocol::SCStoryFBInfo cmd; for (int i = 0; i < FB_STORY_MAX_COUNT; i++) { cmd.info_list[i].is_pass = m_param.fb_list[i].is_pass; cmd.info_list[i].today_times = m_param.fb_list[i].today_times; } EngineAdapter::Instance().NetSend(m_role->GetNetId(), (const char*)&cmd, sizeof(cmd)); } void RoleStoryFB::OnPassLevel(int fb_index) { if (fb_index < 0 || fb_index >= FB_STORY_MAX_COUNT) { return; } const StoryFBLevelCfg::ConfigItem *level_cfg = LOGIC_CONFIG->GetStoryFBConfig().GetLevelCfg(fb_index); if (NULL == level_cfg) { return; } if (0 == m_param.fb_list[fb_index].is_pass) { m_param.fb_list[fb_index].is_pass = 1; m_role->GetKnapsack()->PutListOrMail(level_cfg->first_reward_list, PUT_REASON_STORY_FB); } else { m_role->GetKnapsack()->PutListOrMail(level_cfg->normal_reward_list, PUT_REASON_STORY_FB); } m_role->AddExp(level_cfg->reward_exp, "StoryFBPass", Role::EXP_ADD_REASON_DEFAULT); this->SendInfo(); } bool RoleStoryFB::IsPassLevel(int fb_index) { if (fb_index < 0 || fb_index >= FB_STORY_MAX_COUNT) { return false; } return 0 != m_param.fb_list[fb_index].is_pass; }
22.978056
156
0.715825
mage-game
2b531c733edd0986429110aec5a426add9e73335
354
hpp
C++
ntd/vector.hpp
aconstlink/natus
d2123c6e1798bd0771b8a1a05721c68392afc92f
[ "MIT" ]
null
null
null
ntd/vector.hpp
aconstlink/natus
d2123c6e1798bd0771b8a1a05721c68392afc92f
[ "MIT" ]
292
2020-03-19T22:38:52.000Z
2022-03-05T22:49:34.000Z
ntd/vector.hpp
aconstlink/natus
d2123c6e1798bd0771b8a1a05721c68392afc92f
[ "MIT" ]
null
null
null
#pragma once #include <natus/memory/allocator.hpp> #include <vector> namespace natus { namespace ntd { //template< typename T > //using vector = ::std::vector< T, natus::memory::allocator<T> > ; // for now, we use the default allocator template< typename T > using vector = ::std::vector< T > ; } }
19.666667
74
0.581921
aconstlink
2b5c0973d77dc6cbcd0829a6c30084dc53a6eb39
112
cc
C++
src/messages/reply.cc
zzunny97/Graduate-Velox
d820e7c8cee52f22d7cd9027623bd82ca59733ca
[ "Apache-2.0" ]
17
2016-11-27T13:13:40.000Z
2021-09-07T06:42:25.000Z
src/messages/reply.cc
zzunny97/Graduate-Velox
d820e7c8cee52f22d7cd9027623bd82ca59733ca
[ "Apache-2.0" ]
22
2017-01-18T06:10:18.000Z
2019-05-15T03:49:19.000Z
src/messages/reply.cc
zzunny97/Graduate-Velox
d820e7c8cee52f22d7cd9027623bd82ca59733ca
[ "Apache-2.0" ]
5
2017-07-24T15:19:32.000Z
2022-02-19T09:11:01.000Z
#include "reply.hh" using namespace eclipse::messages; std::string Reply::get_type() const { return "Reply"; }
22.4
55
0.723214
zzunny97
2b605c0a5c1cfdd09444dd5187f3d3a7193f9301
1,994
hpp
C++
include/Zelta/Core/RenderLayer.hpp
RafaelGC/ese
95868d2f7221334271d4a74ef38b2ed3478a8b91
[ "MIT" ]
1
2018-01-28T21:35:14.000Z
2018-01-28T21:35:14.000Z
include/Zelta/Core/RenderLayer.hpp
RafaelGC/ese
95868d2f7221334271d4a74ef38b2ed3478a8b91
[ "MIT" ]
1
2018-01-23T02:03:45.000Z
2018-01-23T02:03:45.000Z
include/Zelta/Core/RenderLayer.hpp
rafaelgc/ESE
95868d2f7221334271d4a74ef38b2ed3478a8b91
[ "MIT" ]
null
null
null
#ifndef ZELTALIB_LAYER_HPP #define ZELTALIB_LAYER_HPP #include <vector> #include <SFML/Graphics/Drawable.hpp> // Base class: sf::Drawable #include <SFML/Graphics/RenderTarget.hpp> namespace zt { /** * @brief Container for drawable objects. * This class allows you to group sf::Drawable elements such as sf::Sprite. * The container keeps pointers to the objects, so your drawable objects * should be kept alive while using the render layer. * */ class RenderLayer : public sf::Drawable { protected: /** * @brief If it's false the contained objects won't be drawn. * */ bool visible; /** * @brief Vector que contiene un puntero a los dibujables de esta capa. * */ std::vector<sf::Drawable*>drawableItems; public: /** * @brief Constructs an empty layer. * */ RenderLayer(bool visible = true); virtual ~RenderLayer(); /** * @brief Draws all contained objects if the layer is visible. * */ virtual void draw(sf::RenderTarget& target, sf::RenderStates states) const; /** * @brief Adds a drawable. * */ void addDrawable(sf::Drawable &item); /** * @brief Removes a drawable if it exists. * @param item Drawable you cant to remove. * @return True if it was removed. */ bool removeDrawable(sf::Drawable & item); /** * @brief Sets the visibility. * */ void setVisible(bool visible); bool isVisible() const; int getZ() const; void setZ(int z); unsigned int count() const; bool isEmpty() const; /** * Compares the depth of the layer. * @param other * @return */ bool operator<(zt::RenderLayer & other) const; }; } #endif // LAYER_HPP
26.236842
83
0.549147
RafaelGC
2b6a60525f50008936b2c335749c76337bbd685d
935
cpp
C++
test/example/executor/strand.cpp
YACLib/YACLib
fa5e13cdcc1f719e6b6363ba25a4791315e66916
[ "MIT" ]
106
2021-07-04T01:10:18.000Z
2022-03-21T00:58:27.000Z
test/example/executor/strand.cpp
YACLib/YACLib
fa5e13cdcc1f719e6b6363ba25a4791315e66916
[ "MIT" ]
119
2021-07-10T14:26:24.000Z
2022-03-22T22:48:18.000Z
test/example/executor/strand.cpp
YACLib/YACLib
fa5e13cdcc1f719e6b6363ba25a4791315e66916
[ "MIT" ]
7
2021-07-23T11:23:04.000Z
2021-11-13T20:22:56.000Z
/** * \example strand.cpp * Simple \ref Strand examples */ #include <yaclib/executor/strand.hpp> #include <yaclib/executor/thread_pool.hpp> #include <iostream> #include <gtest/gtest.h> using namespace yaclib; TEST(Example, Strand) { std::cout << "Strand" << std::endl; auto tp = MakeThreadPool(4); auto strand = MakeStrand(tp); size_t counter = 0; static constexpr size_t kThreads = 5; static constexpr size_t kIncrementsPerThread = 12345; std::vector<std::thread> threads; for (size_t i = 0; i < kThreads; ++i) { threads.emplace_back([&]() { for (size_t j = 0; j < kIncrementsPerThread; ++j) { strand->Execute([&] { ++counter; }); } }); } for (auto& t : threads) { t.join(); } tp->Stop(); tp->Wait(); std::cout << "Counter value = " << counter << ", expected " << kThreads * kIncrementsPerThread << std::endl; std::cout << std::endl; }
18.7
110
0.59893
YACLib
2b6d76ef984531a8a4aa2be05d6e7ede8a9f96a9
12,142
cpp
C++
src/c++/lib/model/IntervalGenerator.cpp
sequencing/EAGLE
6da0438c1f7620ea74dec1f34baf20bb0b14b110
[ "BSD-3-Clause" ]
28
2015-05-22T16:03:29.000Z
2022-01-15T12:12:46.000Z
src/c++/lib/model/IntervalGenerator.cpp
sequencing/EAGLE
6da0438c1f7620ea74dec1f34baf20bb0b14b110
[ "BSD-3-Clause" ]
15
2015-10-21T11:19:09.000Z
2020-07-15T05:01:12.000Z
src/c++/lib/model/IntervalGenerator.cpp
sequencing/EAGLE
6da0438c1f7620ea74dec1f34baf20bb0b14b110
[ "BSD-3-Clause" ]
8
2017-01-21T00:31:17.000Z
2018-08-12T13:28:57.000Z
/** ** Copyright (c) 2014 Illumina, Inc. ** ** This file is part of Illumina's Enhanced Artificial Genome Engine (EAGLE), ** covered by the "BSD 2-Clause License" (see accompanying LICENSE file) ** ** \description Generation of random/uniform intervals with precise boundaries ** Based on: ** [1] Jon Louis Bentley and James B. Saxe. 1980. Generating Sorted Lists of Random Numbers. ** ACM Trans. Math. Softw. 6, 3 (September 1980), 359-364. ** DOI=10.1145/355900.355907 http://doi.acm.org/10.1145/355900.355907 ** ** \author Lilian Janin **/ #include <numeric> #include <boost/foreach.hpp> #include <boost/format.hpp> #include "common/Exceptions.hh" #include "model/IntervalGenerator.hh" using namespace std; namespace eagle { namespace model { // Class RandomSequenceGenerator unsigned long RandomSequenceGenerator::getNext() { return static_cast<unsigned long>( floor(getNextAsDouble()) ); } bool RandomSequenceGenerator::hasFinished() { return (remainingSampleCount_ <= 0); } double RandomSequenceGenerator::getNextAsDouble() { if (remainingSampleCount_ <= 0) { BOOST_THROW_EXCEPTION( eagle::common::EagleException( 0, "RandomSequenceGenerator: all samples have already been generated") ); } double rand0to1 = (1.0+rand())/(1.0+RAND_MAX); curMax_ *= exp(log(rand0to1)/remainingSampleCount_); remainingSampleCount_--; return (1-curMax_)*intervalSize_; } // Class RandomIntervalGenerator pair< unsigned long, unsigned int > RandomIntervalGenerator::getNext( const signed long testValue ) { unsigned long intervalNum = (testValue<0)?randomSeq_.getNext():testValue; // Convert intervalNum to interval while ( intervalNum > currentContigIntervalInfo_->lastInterval || currentContigIntervalInfo_->lastInterval == 0xFFFFFFFFFFFFFFFF ) { ++currentContigIntervalInfo_; if (verbose_) { clog << "Generating fragments for chromosome starting at global pos " << currentContigIntervalInfo_->firstIntervalGlobalPos << endl; } } assert( intervalNum >= currentContigIntervalInfo_->firstInterval ); pair< unsigned long, unsigned int > p; if ( intervalNum < currentContigIntervalInfo_->firstSmallerInterval ) { unsigned long localIntervalNum = intervalNum - currentContigIntervalInfo_->firstInterval; p.first = currentContigIntervalInfo_->firstIntervalGlobalPos + localIntervalNum / intervalsPerNormalPosition_; p.second = minFragmentLength_ + localIntervalNum % intervalsPerNormalPosition_; } else { // static unsigned long lastSmallerIntervalNum = -1; // if ( currentContigIntervalInfo_->firstSmallerInterval != lastSmallerIntervalNum ) { unsigned long localIntervalNum = intervalNum - currentContigIntervalInfo_->firstSmallerInterval; unsigned int intervalCountForThisPos = maxFragmentLength_ - minFragmentLength_; unsigned long currentPos = currentContigIntervalInfo_->firstSmallerIntervalGlobalPos; while (intervalCountForThisPos > 0) { if ( localIntervalNum < intervalCountForThisPos ) { p.first = currentPos; p.second = localIntervalNum + minFragmentLength_; break; } localIntervalNum -= intervalCountForThisPos; --intervalCountForThisPos; ++currentPos; } assert( intervalCountForThisPos>0 && "should never happen" ); } } return p; } unsigned long RandomIntervalGenerator::getIntervalCount() { unsigned long intervalCount = 0; unsigned long globalPos = 0; BOOST_FOREACH( const unsigned long l, contigLengths_ ) { struct ContigIntervalInfo intervalInfo; intervalInfo.firstInterval = intervalCount; intervalInfo.firstIntervalGlobalPos = globalPos; if ( l+1 >= maxFragmentLength_ ) { unsigned long normalPositionCount = l - maxFragmentLength_ + 1; intervalCount += intervalsPerNormalPosition_ * normalPositionCount; intervalInfo.firstSmallerInterval = intervalCount; intervalCount += intervalsPerNormalPosition_ * (intervalsPerNormalPosition_-1) / 2; intervalInfo.firstSmallerIntervalGlobalPos = globalPos + normalPositionCount; } else { intervalInfo.firstSmallerIntervalGlobalPos = 0; EAGLE_WARNING( "Chromosome shorter than insert length" ); } intervalInfo.lastInterval = intervalCount - 1; if (verbose_) { clog << "Chromosome at global pos " << globalPos << " has " << (intervalInfo.lastInterval-intervalInfo.firstInterval+1) << " intervals" << endl; } globalPos += l; contigIntervalInfo_.push_back( intervalInfo ); } return intervalCount; } // Class RandomIntervalGeneratorUsingIntervalLengthDistribution pair< unsigned long, unsigned int > RandomIntervalGeneratorUsingIntervalLengthDistribution::getNext( const signed long testValue ) { assert( testValue < 0 ); // positive test case not implemented if (randomSeq_.hasFinished()) { return make_pair(0,0); } double randomPos = randomSeq_.getNextAsDouble(); // randomPos => currentPos double probaOfCurrentPos = getIntervalsProbaAtPos( currentPos_ ); while (randomPos >= accumulatedProbasUntilCurrentPos_ + probaOfCurrentPos) { accumulatedProbasUntilCurrentPos_ += probaOfCurrentPos; ++currentPos_; probaOfCurrentPos = getIntervalsProbaAtPos( currentPos_ ); } // randomPos(-currentPos) => fragmentLength unsigned int fragmentLength = fragmentLengthDist_.min(); double probaDiff = randomPos - accumulatedProbasUntilCurrentPos_; while (probaDiff > fragmentLengthDist_[fragmentLength]) { probaDiff -= fragmentLengthDist_[fragmentLength++]; } return make_pair( currentPos_, fragmentLength ); } double RandomIntervalGeneratorUsingIntervalLengthDistribution::getIntervalsProbaAtPos( unsigned long globalPos ) { assert( contigLengths_.size() == 1 ); // We restrict the current implementation to one contig at a time const unsigned long contigLength = contigLengths_[0]; if (globalPos + fragmentLengthDist_.max() < contigLength) { return 1.0; } else { unsigned int distanceToContigEnd = contigLength - globalPos; unsigned int index = fragmentLengthDist_.max() - distanceToContigEnd; if (index >= probas_.size()) { // We expect to build the index 1 entry at a time( index == probas_.size() most of the time), but we need to skip some initial entries for chromosomes smaller than the max template length if (index > probas_.size()) { probas_.resize( index, 0 ); } double p = 0; for (unsigned int i=fragmentLengthDist_.min(); i<=distanceToContigEnd; ++i) { p += fragmentLengthDist_[i]; } probas_.push_back( p ); // clog << (boost::format("Adding proba %f at index %d (for globalPos %d)") % p % index % globalPos).str() << endl; } return probas_[index]; } } double RandomIntervalGeneratorUsingIntervalLengthDistribution::getTotalIntervalsProba() { assert( contigLengths_.size() == 1 ); // We restrict the current implementation to one contig at a time const unsigned long contigLength = contigLengths_[0]; double intervalCount = 0; for (unsigned long globalPos=0; globalPos<contigLength; ++globalPos) { intervalCount += getIntervalsProbaAtPos( globalPos ); } if (verbose_) { EAGLE_DEBUG( 0, "Contig's total intervals probability: " << intervalCount ); } return intervalCount; } // Class UniformIntervalGenerator UniformIntervalGenerator::UniformIntervalGenerator( const vector<unsigned long>& contigLengths, const unsigned int medianFragmentLength, const double step, unsigned long& readCount, bool verbose) : IntervalGenerator( contigLengths, readCount, medianFragmentLength, medianFragmentLength, medianFragmentLength, verbose) , step_( step ) { unsigned long intervalCount = 0; unsigned long globalPos = 0; BOOST_FOREACH( const unsigned long l, contigLengths_ ) { struct ContigIntervalInfo intervalInfo; intervalInfo.firstGlobalPos = globalPos; unsigned long contigValidPosCount = l - medianFragmentLength + 1; intervalCount += contigValidPosCount; intervalInfo.lastGlobalPos = globalPos + contigValidPosCount - 1; globalPos += l; contigIntervalInfo_.push_back( intervalInfo ); } currentContigIntervalInfo_ = contigIntervalInfo_.begin(); currentGlobalPos_ = 0 - step_; unsigned long newReadCount = static_cast<unsigned long>( (double)intervalCount / step_ ); if (verbose_) { clog << (boost::format("Uniform coverage attempts to achieve the specified coverage depth for all the chromosome positions, which is impossible to achieve at the chromosome extremities => the average coverage depth will be lower than specified. Changing read count from %d to %d, for a step of %d") % readCount % newReadCount % step_).str() << endl; } readCount = newReadCount; } pair< unsigned long, unsigned int > UniformIntervalGenerator::getNext( const signed long testValue ) { currentGlobalPos_ += step_; // Convert intervalNum to interval while ( floor(currentGlobalPos_) > currentContigIntervalInfo_->lastGlobalPos ) { if ( currentContigIntervalInfo_+1 != contigIntervalInfo_.end() ) { ++currentContigIntervalInfo_; currentGlobalPos_ = currentContigIntervalInfo_->firstGlobalPos; if (verbose_) { clog << "Generating fragments for chromosome starting at global pos " << currentContigIntervalInfo_->firstGlobalPos << endl; } } else { return make_pair( 0, 0 ); //EAGLE_WARNING( "Too many reads generated at the end!" ); } } assert( floor(currentGlobalPos_) >= currentContigIntervalInfo_->firstGlobalPos ); return std::make_pair( (unsigned long)floor(currentGlobalPos_), medianFragmentLength_ ); } pair< unsigned long, unsigned int > RandomIntervalGeneratorFromProbabilityMatrix::getNext( const signed long testValue ) { if (remainingSampleCount_ > 0) { double rand0to1 = (1.0+rand())/(1.0+RAND_MAX); curMax_ *= exp(log(rand0to1)/remainingSampleCount_); remainingSampleCount_--; double choice = (1-curMax_) * intervalSize_; lastChoiceRemainder += choice - lastChoice; while (lastChoiceRemainder >= fragmentLengthProbabilityMatrix_.getProbabilities()[ lastChoiceIndex ]) { lastChoiceRemainder -= fragmentLengthProbabilityMatrix_.getProbabilities()[ lastChoiceIndex ]; if (lastChoiceIndex < fragmentLengthProbabilityMatrix_.getProbabilities().size()) { ++lastChoiceIndex; } else { // Avoid going past the end of the array because of rounding errors break; } } lastChoice = choice; unsigned long pickedGlobalPos = lastChoiceIndex / fragmentLengthDist_size; unsigned long pickedFragmentLength = lastChoiceIndex % fragmentLengthDist_size + fragmentLengthDist_min; cout << (boost::format("remainingSampleCount_=%d, choice=%f, choiceIndex=%d, pickedGlobalPos=%d, pickedFragmentLength=%d") % remainingSampleCount_ % choice % lastChoiceIndex % pickedGlobalPos % pickedFragmentLength).str() << endl; return make_pair( pickedGlobalPos, pickedFragmentLength ); } else { EAGLE_WARNING( "Too many reads generated at the end!" ); return make_pair( 0, 0 ); } } } // namespace model } // namespace eagle
37.36
357
0.674848
sequencing
2b6edefa630bd18dcd564cccb200219b6dcbb4d4
4,791
cpp
C++
src/web/downloadthread.cpp
quizzmaster/chemkit
803e4688b514008c605cb5c7790f7b36e67b68fc
[ "BSD-3-Clause" ]
34
2015-01-24T23:59:41.000Z
2020-11-12T13:48:01.000Z
src/web/downloadthread.cpp
soplwang/chemkit
d62b7912f2d724a05fa8be757f383776fdd5bbcb
[ "BSD-3-Clause" ]
4
2015-12-28T20:29:16.000Z
2016-01-26T06:48:19.000Z
src/web/downloadthread.cpp
soplwang/chemkit
d62b7912f2d724a05fa8be757f383776fdd5bbcb
[ "BSD-3-Clause" ]
17
2015-01-23T14:50:24.000Z
2021-06-10T15:43:50.000Z
/****************************************************************************** ** ** Copyright (C) 2009-2011 Kyle Lutz <[email protected]> ** All rights reserved. ** ** This file is a part of the chemkit project. For more information ** see <http://www.chemkit.org>. ** ** 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 chemkit project 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 "downloadthread.h" namespace chemkit { // === DownloadThread ====================================================== // /// \class DownloadThread downloadthread.h /// \ingroup chemkit-web /// \internal /// \brief The DownloadThread class provides an interface for /// downloading data from the web. // --- Construction and Destruction ---------------------------------------- // /// Creates a new download thread object. DownloadThread::DownloadThread(const QUrl &url) : QThread(), m_url(url) { m_manager = 0; m_ftp = 0; m_reply = 0; } /// Destroys the download thread object. DownloadThread::~DownloadThread() { delete m_ftp; delete m_manager; } // --- Properties ---------------------------------------------------------- // /// Returns the downloaded data. QByteArray DownloadThread::data() const { return m_data; } // --- Thread -------------------------------------------------------------- // /// Starts the download. /// /// This method should not be called directly. Use QThread::start(). void DownloadThread::run() { if(m_url.scheme() == "ftp"){ m_dataBuffer.open(QBuffer::ReadWrite); m_ftp = new QFtp; connect(m_ftp, SIGNAL(done(bool)), SLOT(ftpDone(bool)), Qt::DirectConnection); m_ftp->connectToHost(m_url.host()); m_ftp->login("anonymous", "chemkit"); QFileInfo fileInfo(m_url.path()); m_ftp->cd(fileInfo.path() + "/"); m_ftp->get(fileInfo.fileName(), &m_dataBuffer); m_ftp->close(); } else{ m_manager = new QNetworkAccessManager; connect(m_manager, SIGNAL(finished(QNetworkReply*)), SLOT(replyFinished(QNetworkReply*)), Qt::DirectConnection); m_reply = m_manager->get(QNetworkRequest(m_url)); connect(m_reply, SIGNAL(error(QNetworkReply::NetworkError)), SLOT(replyError(QNetworkReply::NetworkError)), Qt::DirectConnection); } exec(); } // --- Static Methods ------------------------------------------------------ // /// Downloads and returns the data from \p url. QByteArray DownloadThread::download(const QUrl &url) { DownloadThread thread(url); thread.start(); thread.wait(); return thread.data(); } // --- Slots --------------------------------------------------------------- // void DownloadThread::replyFinished(QNetworkReply *reply) { m_data = reply->readAll(); reply->deleteLater(); m_manager->deleteLater(); exit(0); } void DownloadThread::replyError(QNetworkReply::NetworkError error) { Q_UNUSED(error); qDebug() << "chemkit-web: DownloadThread Error: " << m_reply->errorString(); } void DownloadThread::ftpDone(bool error) { if(error){ qDebug() << "chemkit-web: DownloadThread Ftp Error:" << m_ftp->errorString(); exit(-1); } m_data = m_dataBuffer.data(); exit(0); } } // end chemkit namespace
33.041379
86
0.615947
quizzmaster
2b6feb5740721ab22d1b8a61391e5f5f9cb7af52
60
cpp
C++
common/UIOverlay.cpp
daozhangXDZ/OpenGLES_Examples
9266842fbd0ae899446b6ccda9cd63eeeaf1451f
[ "MIT" ]
248
2019-06-04T16:46:24.000Z
2022-02-13T11:21:14.000Z
common/UIOverlay.cpp
YKHahahaha/OpenGLES_Examples
b3451184bb5fffd2d6e8390ece93ca6cfcf80bfc
[ "MIT" ]
null
null
null
common/UIOverlay.cpp
YKHahahaha/OpenGLES_Examples
b3451184bb5fffd2d6e8390ece93ca6cfcf80bfc
[ "MIT" ]
40
2019-07-18T09:59:22.000Z
2021-09-17T13:00:05.000Z
// Implementation of Common library #include "UIOverlay.h"
20
36
0.766667
daozhangXDZ
2b763a401e508f70e6f79004fda13fa62b744358
10,614
cpp
C++
mpegts/mpegts/mpegts_muxer.cpp
Unit-X/srt_tango_2
9443457f807ad151c9b543f892c969404e74e3a7
[ "MIT" ]
1
2020-06-16T11:45:26.000Z
2020-06-16T11:45:26.000Z
mpegts/mpegts/mpegts_muxer.cpp
Unit-X/srt_tango_2
9443457f807ad151c9b543f892c969404e74e3a7
[ "MIT" ]
null
null
null
mpegts/mpegts/mpegts_muxer.cpp
Unit-X/srt_tango_2
9443457f807ad151c9b543f892c969404e74e3a7
[ "MIT" ]
null
null
null
#include "mpegts_muxer.h" #include "simple_buffer.h" #include "ts_packet.h" #include "crc.h" #include <string.h> #include "common.h" static const uint16_t MPEGTS_NULL_PACKET_PID = 0x1FFF; static const uint16_t MPEGTS_PAT_PID = 0x00; static const uint16_t MPEGTS_PMT_PID = 0x100; static const uint16_t MPEGTS_PCR_PID = 0x110; class MpegTsAdaptationFieldType { public: // Reserved for future use by ISO/IEC static const uint8_t mReserved = 0x00; // No adaptation_field, payload only static const uint8_t mPayloadOnly = 0x01; // Adaptation_field only, no payload static const uint8_t mAdaptionOnly = 0x02; // Adaptation_field followed by payload static const uint8_t mPayloadAdaptionBoth = 0x03; }; MpegTsMuxer::MpegTsMuxer() { } MpegTsMuxer::~MpegTsMuxer() { } void MpegTsMuxer::createPat(SimpleBuffer *pSb, uint16_t lPmtPid, uint8_t lCc) { int lPos = pSb->pos(); TsHeader lTsHeader; lTsHeader.mSyncByte = 0x47; lTsHeader.mTransportErrorIndicator = 0; lTsHeader.mPayloadUnitStartIndicator = 1; lTsHeader.mTransportPriority = 0; lTsHeader.mPid = MPEGTS_PAT_PID; lTsHeader.mTransportScramblingControl = 0; lTsHeader.mAdaptationFieldControl = MpegTsAdaptationFieldType::mPayloadOnly; lTsHeader.mContinuityCounter = lCc; AdaptationFieldHeader lAdaptField; PATHeader lPatHeader; lPatHeader.mTableId = 0x00; lPatHeader.mSectionSyntaxIndicator = 1; lPatHeader.mB0 = 0; lPatHeader.mReserved0 = 0x3; lPatHeader.mTransportStreamId = 0; lPatHeader.mReserved1 = 0x3; lPatHeader.mVersionNumber = 0; lPatHeader.mCurrentNextIndicator = 1; lPatHeader.mSectionNumber = 0x0; lPatHeader.mLastSectionNumber = 0x0; //program_number uint16_t lProgramNumber = 0x0001; //program_map_PID uint16_t lProgramMapPid = 0xe000 | (lPmtPid & 0x1fff); unsigned int lSectionLength = 4 + 4 + 5; lPatHeader.mSectionLength = lSectionLength & 0x3ff; lTsHeader.encode(pSb); lAdaptField.encode(pSb); lPatHeader.encode(pSb); pSb->write_2bytes(lProgramNumber); pSb->write_2bytes(lProgramMapPid); // crc32 uint32_t lCrc32 = crc32((uint8_t *) pSb->data() + 5, pSb->pos() - 5); pSb->write_4bytes(lCrc32); std::string lStuff(188 - (pSb->pos() - lPos), 0xff); pSb->write_string(lStuff); } void MpegTsMuxer::createPmt(SimpleBuffer *pSb, std::map<uint8_t, int> lStreamPidMap, uint16_t lPmtPid, uint8_t lCc) { int lPos = pSb->pos(); TsHeader lTsHeader; lTsHeader.mSyncByte = 0x47; lTsHeader.mTransportErrorIndicator = 0; lTsHeader.mPayloadUnitStartIndicator = 1; lTsHeader.mTransportPriority = 0; lTsHeader.mPid = lPmtPid; lTsHeader.mTransportScramblingControl = 0; lTsHeader.mAdaptationFieldControl = MpegTsAdaptationFieldType::mPayloadOnly; lTsHeader.mContinuityCounter = lCc; AdaptationFieldHeader lAdaptField; PMTHeader lPmtHeader; lPmtHeader.mTableId = 0x02; lPmtHeader.mSectionSyntaxIndicator = 1; lPmtHeader.mB0 = 0; lPmtHeader.mReserved0 = 0x3; lPmtHeader.mSectionLength = 0; lPmtHeader.mProgramNumber = 0x0001; lPmtHeader.mReserved1 = 0x3; lPmtHeader.mVersionNumber = 0; lPmtHeader.mCurrentNextIndicator = 1; lPmtHeader.mSectionNumber = 0x00; lPmtHeader.mLastSectionNumber = 0x00; lPmtHeader.mReserved2 = 0x7; lPmtHeader.mReserved3 = 0xf; lPmtHeader.mProgramInfoLength = 0; for (auto lIt = lStreamPidMap.begin(); lIt != lStreamPidMap.end(); lIt++) { lPmtHeader.mInfos.push_back(std::shared_ptr<PMTElementInfo>(new PMTElementInfo(lIt->first, lIt->second))); if (lIt->first == MpegTsStream::AVC) { lPmtHeader.mPcrPid = lIt->second; } } uint16_t lSectionLength = lPmtHeader.size() - 3 + 4; lPmtHeader.mSectionLength = lSectionLength & 0x3ff; lTsHeader.encode(pSb); lAdaptField.encode(pSb); lPmtHeader.encode(pSb); // crc32 uint32_t lCrc32 = crc32((uint8_t *) pSb->data() + lPos + 5, pSb->pos() - lPos - 5); pSb->write_4bytes(lCrc32); std::string lStuff(188 - (pSb->pos() - lPos), 0xff); pSb->write_string(lStuff); } void MpegTsMuxer::createPes(TsFrame *pFrame, SimpleBuffer *pSb) { bool lFirst = true; while (!pFrame->mData->empty()) { SimpleBuffer lPacket(188); TsHeader lTsHeader; lTsHeader.mPid = pFrame->mPid; lTsHeader.mAdaptationFieldControl = MpegTsAdaptationFieldType::mPayloadOnly; lTsHeader.mContinuityCounter = getCc(pFrame->mStreamType); if (lFirst) { lTsHeader.mPayloadUnitStartIndicator = 0x01; if (pFrame->mStreamType == MpegTsStream::AVC) { lTsHeader.mAdaptationFieldControl |= 0x02; AdaptationFieldHeader adapt_field_header; adapt_field_header.mAdaptationFieldLength = 0x07; adapt_field_header.mRandomAccessIndicator = 0x01; adapt_field_header.mPcrFlag = 0x01; lTsHeader.encode(&lPacket); adapt_field_header.encode(&lPacket); writePcr(&lPacket, pFrame->mDts); } else { lTsHeader.encode(&lPacket); } PESHeader lPesHeader; lPesHeader.mPacketStartCode = 0x000001; lPesHeader.mStreamId = pFrame->mStreamId; lPesHeader.mMarkerBits = 0x02; lPesHeader.mOriginalOrCopy = 0x01; if (pFrame->mPts != pFrame->mDts) { lPesHeader.mPtsDtsFlags = 0x03; lPesHeader.mHeaderDataLength = 0x0A; } else { lPesHeader.mPtsDtsFlags = 0x2; lPesHeader.mHeaderDataLength = 0x05; } uint32_t lPesSize = (lPesHeader.mHeaderDataLength + pFrame->mData->size() + 3); lPesHeader.mPesPacketLength = lPesSize > 0xffff ? 0 : lPesSize; lPesHeader.encode(&lPacket); if (lPesHeader.mPtsDtsFlags == 0x03) { writePts(&lPacket, 3, pFrame->mPts); writePts(&lPacket, 1, pFrame->mDts); } else { writePts(&lPacket, 2, pFrame->mPts); } lFirst = false; } else { lTsHeader.encode(&lPacket); } uint32_t lBodySize = lPacket.size() - lPacket.pos(); uint32_t lInSize = pFrame->mData->size() - pFrame->mData->pos(); if (lBodySize <= lInSize) { // MpegTsAdaptationFieldType::payload_only or MpegTsAdaptationFieldType::payload_adaption_both for AVC lPacket.write_string(pFrame->mData->read_string(lBodySize)); } else { uint16_t lStuffSize = lBodySize - lInSize; if (lTsHeader.mAdaptationFieldControl == MpegTsAdaptationFieldType::mAdaptionOnly || lTsHeader.mAdaptationFieldControl == MpegTsAdaptationFieldType::mPayloadAdaptionBoth) { char *lpBase = lPacket.data() + 5 + lPacket.data()[4]; lPacket.setData(lpBase - lPacket.data() + lStuffSize, lpBase, lPacket.data() + lPacket.pos() - lpBase); memset(lpBase, 0xff, lStuffSize); lPacket.skip(lStuffSize); lPacket.data()[4] += lStuffSize; } else { // adaptationFieldControl |= 0x20 == MpegTsAdaptationFieldType::payload_adaption_both lPacket.data()[3] |= 0x20; lPacket.setData(188 - 4 - lStuffSize, lPacket.data() + 4, lPacket.pos() - 4); lPacket.skip(lStuffSize); lPacket.data()[4] = lStuffSize - 1; if (lStuffSize >= 2) { lPacket.data()[5] = 0; memset(&(lPacket.data()[6]), 0xff, lStuffSize - 2); } } lPacket.write_string(pFrame->mData->read_string(lInSize)); } pSb->append(lPacket.data(), lPacket.size()); } } void MpegTsMuxer::createPcr(SimpleBuffer *pSb) { uint64_t lPcr = 0; TsHeader lTsHeader; lTsHeader.mSyncByte = 0x47; lTsHeader.mTransportErrorIndicator = 0; lTsHeader.mPayloadUnitStartIndicator = 0; lTsHeader.mTransportPriority = 0; lTsHeader.mPid = MPEGTS_PCR_PID; lTsHeader.mTransportScramblingControl = 0; lTsHeader.mAdaptationFieldControl = MpegTsAdaptationFieldType::mAdaptionOnly; lTsHeader.mContinuityCounter = 0; AdaptationFieldHeader lAdaptField; lAdaptField.mAdaptationFieldLength = 188 - 4 - 1; lAdaptField.mSiscontinuityIndicator = 0; lAdaptField.mRandomAccessIndicator = 0; lAdaptField.mElementaryStreamPriorityIndicator = 0; lAdaptField.mPcrFlag = 1; lAdaptField.mOpcrFlag = 0; lAdaptField.mSplicingPointFlag = 0; lAdaptField.mTransportPrivateDataFlag = 0; lAdaptField.mAdaptationFieldExtensionFlag = 0; char *p = pSb->data(); lTsHeader.encode(pSb); lAdaptField.encode(pSb); writePcr(pSb, lPcr); } void MpegTsMuxer::createNull(SimpleBuffer *pSb) { TsHeader lTsHeader; lTsHeader.mSyncByte = 0x47; lTsHeader.mTransportErrorIndicator = 0; lTsHeader.mPayloadUnitStartIndicator = 0; lTsHeader.mTransportPriority = 0; lTsHeader.mPid = MPEGTS_NULL_PACKET_PID; lTsHeader.mTransportScramblingControl = 0; lTsHeader.mAdaptationFieldControl = MpegTsAdaptationFieldType::mPayloadOnly; lTsHeader.mContinuityCounter = 0; lTsHeader.encode(pSb); } void MpegTsMuxer::encode(TsFrame *pFrame, std::map<uint8_t, int> lStreamPidMap, uint16_t lPmtPid, SimpleBuffer *pSb) { if (shouldCreatePat()) { uint8_t lPatPmtCc = getCc(0); createPat(pSb, lPmtPid, lPatPmtCc); createPmt(pSb, lStreamPidMap, lPmtPid, lPatPmtCc); } createPes(pFrame, pSb); } uint8_t MpegTsMuxer::getCc(uint32_t lWithPid) { if (mPidCcMap.find(lWithPid) != mPidCcMap.end()) { mPidCcMap[lWithPid] = (mPidCcMap[lWithPid] + 1) & 0x0F; return mPidCcMap[lWithPid]; } mPidCcMap[lWithPid] = 0; return 0; } bool MpegTsMuxer::shouldCreatePat() { bool lRet = false; static const int lPatInterval = 20; static int lCurrentIndex = 0; if (lCurrentIndex % lPatInterval == 0) { if (lCurrentIndex > 0) { lCurrentIndex = 0; } lRet = true; } lCurrentIndex++; return lRet; }
36.102041
129
0.63746
Unit-X
2b795362dfcbc6fe454f61ae890685908c7f1d6f
694
cpp
C++
flex-engine/src/flex-engine/Log.cpp
flexed-team/flex-engine
481f40a431a33a9f1a4cc0de95edb7dc81aba34e
[ "Apache-2.0" ]
null
null
null
flex-engine/src/flex-engine/Log.cpp
flexed-team/flex-engine
481f40a431a33a9f1a4cc0de95edb7dc81aba34e
[ "Apache-2.0" ]
null
null
null
flex-engine/src/flex-engine/Log.cpp
flexed-team/flex-engine
481f40a431a33a9f1a4cc0de95edb7dc81aba34e
[ "Apache-2.0" ]
null
null
null
#include "log.hpp" namespace FE { std::shared_ptr<spdlog::logger> Log::s_core_logger; std::shared_ptr<spdlog::logger> Log::s_client_logger; void Log::init() { // See spdlog [wiki](https://github.com/gabime/spdlog/wiki) for more pattern settings // ^ - start color range // T - ISO 8601 time format // n - logger's name // v - actual text to log // $ - end color range spdlog::set_pattern("%^[%T] %n: %v%$"); // Create color multi threaded logger s_core_logger = spdlog::stdout_color_mt("FE"); s_core_logger->set_level(spdlog::level::trace); s_client_logger = spdlog::stdout_color_mt("APP"); s_client_logger->set_level(spdlog::level::trace); } } // namespace FE
26.692308
87
0.680115
flexed-team
2b8b20fd3f2f2b67388e511070ed3135875ff451
1,362
cpp
C++
aws-cpp-sdk-cloudtrail/source/model/ListEventDataStoresResult.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-02-12T08:09:30.000Z
2022-02-12T08:09:30.000Z
aws-cpp-sdk-cloudtrail/source/model/ListEventDataStoresResult.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2021-10-14T16:57:00.000Z
2021-10-18T10:47:24.000Z
aws-cpp-sdk-cloudtrail/source/model/ListEventDataStoresResult.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2021-11-09T11:58:03.000Z
2021-11-09T11:58:03.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/cloudtrail/model/ListEventDataStoresResult.h> #include <aws/core/utils/json/JsonSerializer.h> #include <aws/core/AmazonWebServiceResult.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/UnreferencedParam.h> #include <utility> using namespace Aws::CloudTrail::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; using namespace Aws; ListEventDataStoresResult::ListEventDataStoresResult() { } ListEventDataStoresResult::ListEventDataStoresResult(const Aws::AmazonWebServiceResult<JsonValue>& result) { *this = result; } ListEventDataStoresResult& ListEventDataStoresResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result) { JsonView jsonValue = result.GetPayload().View(); if(jsonValue.ValueExists("EventDataStores")) { Array<JsonView> eventDataStoresJsonList = jsonValue.GetArray("EventDataStores"); for(unsigned eventDataStoresIndex = 0; eventDataStoresIndex < eventDataStoresJsonList.GetLength(); ++eventDataStoresIndex) { m_eventDataStores.push_back(eventDataStoresJsonList[eventDataStoresIndex].AsObject()); } } if(jsonValue.ValueExists("NextToken")) { m_nextToken = jsonValue.GetString("NextToken"); } return *this; }
27.24
126
0.768722
perfectrecall
2b957045c492074cd0090fa7e5a5a8b75985c999
2,954
cpp
C++
source/RegistCallback.cpp
xzrunner/nserializer
44c252703a53c5970b8d9f2b608d56830601055e
[ "MIT" ]
null
null
null
source/RegistCallback.cpp
xzrunner/nserializer
44c252703a53c5970b8d9f2b608d56830601055e
[ "MIT" ]
null
null
null
source/RegistCallback.cpp
xzrunner/nserializer
44c252703a53c5970b8d9f2b608d56830601055e
[ "MIT" ]
null
null
null
#include "ns/RegistCallback.h" #include "ns/CompSerializer.h" #include "ns/CompNoSerialize.h" #include "ns/N0CompComplex.h" #include <node0/CompComplex.h> #include "ns/N2CompAnim.h" #include <node2/CompAnim.h> #include "ns/N2CompColorCommon.h" #include <node2/CompColorCommon.h> #include "ns/N2CompColorMap.h" #include <node2/CompColorMap.h> #include "ns/N2CompTransform.h" #include <node2/CompTransform.h> #include <node2/CompBoundingBox.h> #include "ns/N2CompUniquePatch.h" #include <node2/CompUniquePatch.h> #include "ns/N2CompSharedPatch.h" #include <node2/CompSharedPatch.h> #include "ns/N2CompScissor.h" #include <node2/CompScissor.h> #include "ns/N2CompScript.h" #include <node2/CompScript.h> #include "ns/N2CompScript.h" // todo #include <node2/EditOp.h> #include "ns/N0CompIdentity.h" #include <node0/CompIdentity.h> #include "ns/N0CompComplex.h" #include <node0/CompComplex.h> #include "ns/N2CompImage.h" #include <node2/CompImage.h> #include "ns/N2CompMask.h" #include <node2/CompMask.h> #include "ns/N2CompText.h" #include <node2/CompText.h> #include "ns/N2CompScale9.h" #include <node2/CompScale9.h> #include "ns/N2CompShape.h" #include <node2/CompShape.h> #include "ns/N3CompAABB.h" #include <node3/CompAABB.h> #include "ns/N3CompTransform.h" #include <node3/CompTransform.h> #include "ns/N3CompModel.h" #include <node3/CompModel.h> #include "ns/N3CompModelInst.h" #include <node3/CompModelInst.h> #include "ns/N3CompShape.h" #include <node3/CompShape.h> #include "ns/N0CompFlags.h" #include <node0/CompFlags.h> #include <node0/SceneNode.h> #include <memmgr/LinearAllocator.h> #include <anim/Layer.h> #include <anim/KeyFrame.h> namespace ns { void RegistCallback::Init() { AddUniqueCB<n0::CompIdentity, N0CompIdentity>(); AddUniqueCB<n2::CompColorCommon, N2CompColorCommon>(); AddUniqueCB<n2::CompColorMap, N2CompColorMap>(); AddUniqueCB<n2::CompTransform, N2CompTransform>(); AddUniqueNullCB<n2::CompBoundingBox, CompNoSerialize>(); AddUniqueCB<n2::CompUniquePatch, N2CompUniquePatch>(); AddUniqueCB<n2::CompSharedPatch, N2CompSharedPatch>(); AddUniqueCB<n2::CompScissor, N2CompScissor>(); AddUniqueCB<n2::CompScript, N2CompScript>(); AddSharedCB<n0::CompComplex, N0CompComplex>(); AddSharedCB<n2::CompAnim, N2CompAnim>(); AddSharedCB<n2::CompImage, N2CompImage>(); AddSharedCB<n2::CompMask, N2CompMask>(); AddSharedCB<n2::CompText, N2CompText>(); AddSharedCB<n2::CompScale9, N2CompScale9>(); //AddSharedCB<n2::CompShape, N2CompShape>(); AddUniqueCB<n3::CompAABB, N3CompAABB>(); AddUniqueCB<n3::CompTransform, N3CompTransform>(); AddSharedCB<n3::CompModel, N3CompModel>(); AddUniqueCB<n3::CompModelInst, N3CompModelInst>(); AddUniqueCB<n3::CompShape, N3CompShape>(); AddUniqueCB<n0::CompFlags, N0CompFlags>(); AddAssetCB<n0::CompComplex>(); AddAssetCB<n2::CompAnim>(); AddAssetCB<n2::CompImage>(); AddAssetCB<n2::CompMask>(); AddAssetCB<n2::CompText>(); AddAssetCB<n2::CompScale9>(); } }
27.607477
57
0.756601
xzrunner
2b9629798298c6704a0c43083e35af2d7e4529af
145
inl
C++
Projects/CygnusAuxBoardMonitor/Resources/ConfigurationXML_info.inl
hightower70/CygnusGroundStationDev
9fd709f28a67adb293a99c5c251b4ed89e755db3
[ "BSD-2-Clause" ]
1
2019-04-23T05:24:16.000Z
2019-04-23T05:24:16.000Z
Projects/CygnusAuxBoardMonitor/Resources/ConfigurationXML_info.inl
hightower70/CygnusGroundStationDev
9fd709f28a67adb293a99c5c251b4ed89e755db3
[ "BSD-2-Clause" ]
1
2016-08-16T13:05:39.000Z
2016-08-16T13:05:39.000Z
Projects/CygnusAuxBoardMonitor/Resources/ConfigurationXML_info.inl
hightower70/CygnusGroundStationDev
9fd709f28a67adb293a99c5c251b4ed89e755db3
[ "BSD-2-Clause" ]
1
2018-06-24T14:51:20.000Z
2018-06-24T14:51:20.000Z
0x00, 0x00, 0x01, 0x01, 0x01, 0x00, 0x02, 0x0A, 0x03, 0x00, 0x02, 0x0A, 0x05, 0x00, 0x02, 0x03, 0x07, 0x00, 0x02, 0x0A, 0x09, 0x00, 0x02, 0x03
48.333333
96
0.662069
hightower70
2b9e3b7072aa6eac36c65a288f0b47b2c92fdab0
2,406
cpp
C++
Examples/Chess/src/chess-application.cpp
JoachimHerber/Bembel-Game-Engine
5c4e46c5a15356af6e997038a8d76065b0691b50
[ "MIT" ]
2
2018-01-02T14:07:54.000Z
2021-07-05T08:05:21.000Z
Examples/Chess/src/chess-application.cpp
JoachimHerber/Bembel-Game-Engine
5c4e46c5a15356af6e997038a8d76065b0691b50
[ "MIT" ]
null
null
null
Examples/Chess/src/chess-application.cpp
JoachimHerber/Bembel-Game-Engine
5c4e46c5a15356af6e997038a8d76065b0691b50
[ "MIT" ]
null
null
null
#include "chess-application.h" #include <GLFW/glfw3.h> #include <chrono> #include <iostream> #include <random> #include "selection-rendering-stage.h" using namespace bembel; ChessApplication::ChessApplication() : kernel::Application() { this->graphic_system = this->kernel->addSystem<graphics::GraphicSystem>(); this->graphic_system->getRendertingStageFactory() .registerDefaultObjectGenerator<SelectionRenderingStage>("SelectionRenderingStage"); auto& event_mgr = this->kernel->getEventManager(); event_mgr.addHandler<kernel::WindowShouldCloseEvent>(this); event_mgr.addHandler<kernel::FrameBufferResizeEvent>(this); } ChessApplication::~ChessApplication() { } bool ChessApplication::init() { BEMBEL_LOG_INFO() << "Loading Application Settings"; if(!this->kernel->loadSetting("chess/config.xml")) return false; auto pipline = this->graphic_system->getRenderingPipelines()[0].get(); this->camera = std::make_shared<CameraControle>(this->kernel->getEventManager(), pipline->getCamera()); BEMBEL_LOG_INFO() << "Initalizing Game"; this->chess_game = std::make_unique<ChessGame>( this->kernel->getAssetManager(), this->kernel->getEventManager(), *(this->graphic_system)); this->chess_game->resetChessBoard(); this->chess_game->resetChessBoard(); BEMBEL_LOG_INFO() << "Initalizing Camera"; pipline->setScene(this->chess_game->getScene()); this->camera->setCameraOffset(glm::vec3(8, 0.5f, 8)); this->camera->enableManualControle(true); BEMBEL_LOG_INFO() << "Initalizing Systems"; this->kernel->initSystems(); return true; } void ChessApplication::cleanup() { this->chess_game.reset(); this->kernel->shutdownSystems(); this->kernel->getAssetManager().deleteUnusedAssets(); this->kernel->getDisplayManager().closeOpenWindows(); } void ChessApplication::update(double time) { this->camera->update(time); this->chess_game->update(time); } void ChessApplication::handleEvent(const kernel::WindowShouldCloseEvent& event) { this->quit(); } void ChessApplication::handleEvent(const kernel::FrameBufferResizeEvent& event) { auto pipline = this->graphic_system->getRenderingPipelines()[0].get(); pipline->setResulution(event.size); pipline->getCamera()->setUpProjection( 60.0f * 3.14159265359f / 180.0f, event.size.x / event.size.y, 0.1f, 1000.0f); }
32.08
99
0.715711
JoachimHerber
2ba7bcde3e5dfc15bf94af1a4d55546f3cfbba51
14,693
cpp
C++
macros/phi_correlation_he6_carbon_compare.cpp
serjinio/thesis_ana
633a61dee56cf2cf4dcb67997ac87338537fb578
[ "MIT" ]
null
null
null
macros/phi_correlation_he6_carbon_compare.cpp
serjinio/thesis_ana
633a61dee56cf2cf4dcb67997ac87338537fb578
[ "MIT" ]
null
null
null
macros/phi_correlation_he6_carbon_compare.cpp
serjinio/thesis_ana
633a61dee56cf2cf4dcb67997ac87338537fb578
[ "MIT" ]
null
null
null
#include <iostream> #include "init_6he_ds.hpp" #include "TChain.h" void hdraw(TTree& tree, TString name, TString draw_cmd, TString binning, TCut cuts = "", TString title = "", TString xaxis_title = "", TString yaxis_title = "", TString draw_opts = "colz") { TString hstr = TString::Format("%s >>%s%s", draw_cmd.Data(), name.Data(), binning.Data()); tree.Draw(hstr, cuts, draw_opts); TH1 *hist = static_cast<TH1*>(gPad->GetPrimitive(name)); if (yaxis_title != "") { hist->GetYaxis()->SetTitle(yaxis_title); } if (xaxis_title != "") { hist->GetXaxis()->SetTitle(xaxis_title); } if (title != "") { hist->SetTitle(title); } } void phi_correlation_he6_carbon_compare() { init_dataset(); init_carbon_dataset(); std::cout << "Total number of events for he6: " << g_chain_total.GetEntries() << std::endl; std::cout << "Total number of events for carbon: " << g_c_chain.GetEntries() << std::endl; TCut p_angle_sn_cut = "p_theta*57.3>65 && p_theta*57.3<68"; TCut p_angle_acceptance_cut = "p_theta*57.3>55 && p_theta*57.3<70"; TCut phi_corr_cut_1d = "abs(abs(p_phi*57.3-s1dc_phi*57.3) - 180) < 8"; TCut target_cut{"tgt_up_xpos*tgt_up_xpos + tgt_up_ypos*tgt_up_ypos < 81"}; TCut vertex_zpos_cut{"es_vertex_zpos > -30 && es_vertex_zpos < 30"}; // distribution on HODF plastics // pla IDs [7,9]: beam / beam stopper // pla ID [0,4]: left scattering 6He // pla ID [11,14]: right scattering 6He // pla ID [17,23]: 4He (from inelastic shannel) std::string hodf_cut_str = ""; for (int i = 0; i < 5; i++) { hodf_cut_str += TString::Format("(hodf_q[%i]>14 && hodf_q[%i]<17) ", i, i); if (i != 4) hodf_cut_str += "|| "; } hodf_cut_str += "|| "; for (int i = 11; i < 15; i++) { hodf_cut_str += TString::Format("(hodf_q[%i]>14 && hodf_q[%i]<17) ", i, i); if (i != 14) hodf_cut_str += "|| "; } cout << "HODF cut:\n" << hodf_cut_str << std::endl; TCut hodf_cut{hodf_cut_str.c_str()}; TFile hist_out("out/phi_correlation_he6_carbon_compare.root", "RECREATE"); TCanvas c1("c1"); gStyle->SetOptStat(1111111); // // proton phi // c1.Clear(); // c1.Divide(2); // c1.cd(1); // hdraw(g_chain_total, "esl_p_phi", "esl_p_phi*57.3", "(360,-180,180)", // "triggers[5]==1" && target_cut && hodf_cut, // "ESPRI left, proton phi angle", // "Proton #phi angle [lab. deg.]", "Counts"); // //gPad->SetLogy(); // c1.cd(2); // hdraw(g_chain_total, "esr_p_phi", "esr_p_phi*57.3", "(360,-180,180)", // "triggers[5]==1" && target_cut && hodf_cut, // "ESPRI right, proton phi angle", // "Proton #phi angle [lab. deg.]", "Counts"); // //gPad->SetLogy(); // c1.Print("out/phi_correlation_he6_carbon_compare.pdf(", "pdf"); // // He phi // c1.Clear(); // c1.Divide(1); // c1.cd(1); // hdraw(g_chain_total, "fragment_phi_s1dc", "s1dc_phi*57.3", "(360,-180,180)", // "triggers[5]==1" && target_cut && hodf_cut, // "Fragment azimuthal angle", // "Fragment #phi angle [lab. deg.]", "Counts"); // //gPad->SetLogy(); // c1.Print("out/phi_correlation_he6_carbon_compare.pdf", "pdf"); // // phi 2d corr ESPRI L&R // c1.Clear(); // c1.Divide(2); // c1.cd(1); // hdraw(g_chain_total, "esl_phi_corr", "esl_p_phi*57.3:s1dc_phi*57.3", // "(100,60,120,100,-120,-60)", // "triggers[5]==1" && target_cut && hodf_cut, // "ESPRI left, phi correlation", // "Fragment #phi angle [lab. deg.]", // "Proton #phi angle [lab. deg.]"); // c1.cd(2); // hdraw(g_chain_total, "esr_phi_corr", "esr_p_phi*57.3:s1dc_phi*57.3", // "(100,-120,-60,100,60,120)", // "triggers[5]==1" && target_cut && hodf_cut, // "ESPRI right, phi correlation", // "Fragment #phi angle [lab. deg.]", // "Proton #phi angle [lab. deg.]"); // c1.Print("out/phi_correlation_he6_carbon_compare.pdf", "pdf"); // ESPRI L&R phi corr 1d // c1.Clear(); // c1.Divide(1,2); // c1.cd(1); // hdraw(g_chain_total, "esl_phi_corr_1d", "esl_p_phi*57.3-s1dc_phi*57.3", // "(300,-350,-10)", // "triggers[5]==1" && target_cut && hodf_cut, // "ESPRI left: P_{#phi} - He_{#phi}", // "P_{#phi} - He_{#phi} [deg]", // "Counts"); // //gPad->SetLogy(); // c1.cd(2); // hdraw(g_chain_total, "esr_phi_corr_1d", "esr_p_phi*57.3-s1dc_phi*57.3", // "(300,10,350)", // "triggers[5]==1" && target_cut && hodf_cut, // "ESPRI right: P_{#phi} - He_{#phi}", // "P_{#phi} - He_{#phi} [deg]", // "Counts"); // //gPad->SetLogy(); // c1.Print("out/phi_correlation_he6_carbon_compare.pdf", "pdf"); // // ESPRI total - phi, hodf cuts // c1.Clear(); // c1.Divide(1,2); // c1.cd(1); // hdraw(g_chain_total, "tot_phi_corr_1d", "abs(p_phi*57.3-s1dc_phi*57.3)", // "(300,10,350)", // "triggers[5]==1" && target_cut && hodf_cut, // "ESPRI left & right: P_{#phi} - He_{#phi} (no #phi cut)", // "P_{#phi} - He_{#phi} [deg.]", // "Counts"); // //gPad->SetLogy(); // c1.cd(2); // hdraw(g_chain_total, "tot_phi_corr_1d_cut", "abs(p_phi*57.3-s1dc_phi*57.3)", // "(300,10,350)", // "triggers[5]==1" && target_cut && hodf_cut && // phi_corr_cut_1d, // "ESPRI left & right: P_{#phi} - He_{#phi} (#phi cut)", // "P_{#phi} - He_{#phi} [deg.]", // "Counts"); // //gPad->SetLogy(); // c1.Print("out/phi_correlation_he6_carbon_compare.pdf", "pdf"); // polar corr with diff. cuts // // HODF cut - He6 vs. carbon // c1.Clear(); // c1.Divide(2,1); // c1.cd(1); // hdraw(g_chain_total, "polar_phi_hodf", "p_theta*57.3:s1dc_theta*57.3", // "(200,0.1,10,200,50,75)", // "triggers[5]==1" && target_cut && hodf_cut, // "#theta angle correlation for 6he-p (tgt, hodf cuts)", // "Fragment #theta angle [lab. deg.]", // "Proton #theta angle [lab. deg.]", "colz"); // c1.cd(2); // hdraw(g_c_chain, "polar_phi_hodf2", "p_theta*57.3:s1dc_theta*57.3", // "(200,0.1,10,200,50,75)", // "triggers[5]==1" && target_cut && hodf_cut, // "#theta angle correlation for 6he-C (tgt, hodf cuts)", // "Fragment #theta angle [lab. deg.]", // "Proton #theta angle [lab. deg.]", "colz"); // c1.Print("out/phi_correlation_he6_carbon_compare.pdf(", "pdf"); // // tgt,phi,hodf cut - He6 vs. carbon // c1.Clear(); // c1.Divide(2,1); // c1.cd(1); // hdraw(g_chain_total, "polar_tgt_phi1d_hodf", "p_theta*57.3:s1dc_theta*57.3", // "(200,0.1,10,200,50,75)", // "triggers[5]==1" && target_cut && // phi_corr_cut_1d && hodf_cut, // "#theta angle corr.: 6he-p (tgt, hodf, phi cuts)", // "Fragment #theta angle [lab. deg.]", // "Proton #theta angle [lab. deg.]", "colz"); // c1.cd(2); // hdraw(g_c_chain, "polar_tgt_phi1d_hodf2", "p_theta*57.3:s1dc_theta*57.3", // "(200,0.1,10,200,50,75)", // "triggers[5]==1" && target_cut && // phi_corr_cut_1d && hodf_cut, // "#theta angle corr.: 6he-C (tgt, hodf, phi cuts)", // "Fragment #theta angle [lab. deg.]", // "Proton #theta angle [lab. deg.]", "colz"); // c1.Print("out/phi_correlation_he6_carbon_compare.pdf", "pdf"); // // 1d hist theta corr S/N // c1.Clear(); // c1.Divide(2,1); // c1.cd(1); // hdraw(g_chain_total, "polar_tgt_phi1d_hodf_1d", "s1dc_theta*57.3", // "(200,0,10)", // "triggers[5]==1" && target_cut && // hodf_cut && phi_corr_cut_1d && p_angle_sn_cut, // "#theta angle corr.: 6he-p (tgt, hodf, phi cuts)", // "Fragment #theta angle [lab. deg.]", // "Counts", "colz"); // c1.cd(2); // hdraw(g_c_chain, "polar_tgt_phi1d_hodf_1d2", "s1dc_theta*57.3", // "(200,0,10)", // "triggers[5]==1" && target_cut && // hodf_cut && phi_corr_cut_1d && p_angle_sn_cut, // "#theta angle corr.: 6he-C (tgt, hodf, phi cuts)", // "Fragment #theta angle [lab. deg.]", // "Counts", "colz"); // c1.Print("out/phi_correlation_he6_carbon_compare.pdf", "pdf"); // // theta exp - theta_theor 2d corr c1.Clear(); c1.Divide(2,1); c1.cd(1); hdraw(g_chain_total, "polar_t_tgt_hodf_phi", "p_theta*57.3:s1dc_theta*57.3 - he_theta_theor*57.3", "(200,-8,8,200,50,75)", "triggers[5]==1" && target_cut && hodf_cut && phi_corr_cut_1d, "#theta angle corr.: #theta_{exp}-#theta_{theor} for 6he-p (tgt, hodf cuts)", "Fragment: #theta_{exp} - #theta_{theor} [lab. deg.]", "Proton #theta angle [lab. deg.]", "colz"); c1.cd(2); hdraw(g_c_chain, "polar_t_tgt_hodf_phi2", "p_theta*57.3:s1dc_theta*57.3 - he_theta_theor*57.3", "(200,-8,8,200,50,75)", "triggers[5]==1" && target_cut && hodf_cut && phi_corr_cut_1d, "#theta angle corr.: #theta_{exp}-#theta_{theor} for 6he-C (tgt, hodf cuts)", "Fragment: #theta_{exp} - #theta_{theor} [lab. deg.]", "Proton #theta angle [lab. deg.]", "colz"); c1.Print("out/phi_correlation_he6_carbon_compare.pdf(", "pdf"); // // theta exp - theta_theor 1d corr // c1.Clear(); // c1.Divide(2,1); // c1.cd(1); // hdraw(g_chain_total, "polar_t_1d", // "s1dc_theta*57.3 - he_theta_theor*57.3", // "(200,-8,8)", // "triggers[5]==1" && target_cut && // hodf_cut && p_angle_acceptance_cut, // "#theta angle corr.: #theta_{exp}-#theta_{theor} for 6he-p (tgt, hodf cuts)", // "Fragment: #theta_{exp} - #theta_{theor} [lab. deg.]", // "Counts", "colz"); // gPad->SetLogy(); // c1.cd(2); // hdraw(g_c_chain, "polar_t_1d2", // "s1dc_theta*57.3 - he_theta_theor*57.3", // "(200,-8,8)", // "triggers[5]==1" && target_cut && // hodf_cut && p_angle_acceptance_cut, // "#theta angle corr.: #theta_{exp}-#theta_{theor} for 6he-C (tgt, hodf cuts)", // "Fragment: #theta_{exp} - #theta_{theor} [lab. deg.]", // "Counts", "colz"); // gPad->SetLogy(); // c1.Print("out/phi_correlation_he6_carbon_compare.pdf", "pdf"); // // theta exp - theta_theor 1d corr + carbon BG // c1.Clear(); // c1.Divide(1); // c1.cd(1); // g_chain_total.SetLineColor(kBlue); // hdraw(g_chain_total, "polar_t_1d_hc1", // "s1dc_theta*57.3 - he_theta_theor*57.3", // "(200,-8,8)", // "triggers[5]==1" && target_cut && // hodf_cut && p_angle_acceptance_cut, // "#theta angle corr.: #theta_{exp}-#theta_{theor} for 6he-p and 6he-C (tgt, hodf cuts)", // "Fragment: #theta_{exp} - #theta_{theor} [lab. deg.]", // "Counts"); // g_c_chain.SetLineColor(kRed); // hdraw(g_c_chain, "polar_t_1d_hc2", // "s1dc_theta*57.3 - he_theta_theor*57.3", // "(200,-8,8)", // "triggers[5]==1" && target_cut && // hodf_cut && p_angle_acceptance_cut, // "#theta angle corr.: #theta_{exp}-#theta_{theor} for 6he-p and 6he-C (tgt, hodf cuts)", // "Fragment: #theta_{exp} - #theta_{theor} [lab. deg.]", // "Counts", "SAME"); // gPad->SetLogy(); // c1.Print("out/phi_correlation_he6_carbon_compare.pdf", "pdf"); // theta exp - theta_theor 1d corr + phi cut c1.Clear(); c1.Divide(2,1); c1.cd(1); hdraw(g_chain_total, "polar_t_1d_phi", "s1dc_theta*57.3 - he_theta_theor*57.3", "(200,-8,8)", "triggers[5]==1" && target_cut && hodf_cut && phi_corr_cut_1d && p_angle_acceptance_cut, "#theta angle corr.: #theta_{exp}-#theta_{theor} for 6he-p (tgt, hodf, phi cuts)", "Fragment: #theta_{exp} - #theta_{theor} [lab. deg.]", "Counts", "colz"); gPad->SetLogy(); c1.cd(2); g_c_chain.SetLineColor(kBlue); hdraw(g_c_chain, "polar_t_1d2_phi", "s1dc_theta*57.3 - he_theta_theor*57.3", "(200,-8,8)", "triggers[5]==1" && target_cut && hodf_cut && phi_corr_cut_1d && p_angle_acceptance_cut, "#theta angle corr.: #theta_{exp}-#theta_{theor} for 6he-C (tgt, hodf, phi cuts)", "Fragment: #theta_{exp} - #theta_{theor} [lab. deg.]", "Counts", "colz"); gPad->SetLogy(); c1.Print("out/phi_correlation_he6_carbon_compare.pdf", "pdf"); // theta exp - theta_theor 1d corr + phi cut + carbon BG c1.Clear(); c1.Divide(1); c1.cd(1); g_chain_total.SetLineColor(kBlue); hdraw(g_chain_total, "polar_t_1d_hc1_phi", "s1dc_theta*57.3 - he_theta_theor*57.3", "(200,-8,8)", "triggers[5]==1" && target_cut && hodf_cut && phi_corr_cut_1d && p_angle_acceptance_cut, "#theta angle corr.: #theta_{exp}-#theta_{theor} for 6he-p and 6he-C (tgt, hodf, phi cuts)", "Fragment: #theta_{exp} - #theta_{theor} [lab. deg.]", "Counts"); g_c_chain.SetLineColor(kRed); hdraw(g_c_chain, "polar_t_1d_hc2_phi", "s1dc_theta*57.3 - he_theta_theor*57.3", "(200,-8,8)", "triggers[5]==1" && target_cut && hodf_cut && phi_corr_cut_1d && p_angle_acceptance_cut, "#theta angle corr.: #theta_{exp}-#theta_{theor} for 6he-p and 6he-C (tgt, hodf, phi cuts)", "Fragment: #theta_{exp} - #theta_{theor} [lab. deg.]", "Counts", "SAME"); TH1* he6_polar = static_cast<TH1*>(gPad->GetPrimitive("polar_t_1d_hc1_phi")); TH1* carbon_polar = static_cast<TH1*>(gPad->GetPrimitive("polar_t_1d_hc2_phi")); carbon_polar->Scale(3); he6_polar->Draw(); carbon_polar->SetLineColor(kRed); carbon_polar->Draw("SAME"); gPad->SetLogy(); c1.Print("out/phi_correlation_he6_carbon_compare.pdf", "pdf"); // theta exp - theta_theor 1d corr - carbon BG c1.Clear(); c1.Divide(1); c1.cd(1); g_chain_total.SetLineColor(kBlue); g_c_chain.SetLineColor(kBlue); TH1* he6_polar_min_bg = (TH1*)he6_polar->Clone(); he6_polar_min_bg->Add(carbon_polar, -1); he6_polar_min_bg->SetTitle("#theta angle corr.: #theta_{exp}-#theta_{theor} for " "6he-p - 6he-C (tgt, hodf, phi cuts)"); he6_polar_min_bg->Draw(); gPad->SetLogy(); c1.Print("out/phi_correlation_he6_carbon_compare.pdf", "pdf"); c1.Clear(); c1.Divide(1); c1.cd(1); he6_polar->Draw(); carbon_polar->SetLineColor(kRed); carbon_polar->Draw("SAME"); //gPad->SetLogy(); c1.Print("out/phi_correlation_he6_carbon_compare.pdf", "pdf"); c1.Clear(); c1.Divide(1); c1.cd(1); g_chain_total.SetLineColor(kBlue); g_c_chain.SetLineColor(kBlue); he6_polar_min_bg->Draw(); //gPad->SetLogy(); c1.Print("out/phi_correlation_he6_carbon_compare.pdf)", "pdf"); hist_out.Write(); hist_out.Close(); }
38.064767
100
0.574355
serjinio
2ba8b7704ef008a72827b0bfff98fe3808468963
10,557
cpp
C++
src/drivers/milliped.cpp
pierrelouys/PSP-MAME4ALL
54374b0579b7e2377f015ac155d8f519addfaa1a
[ "Unlicense" ]
1
2021-01-25T20:16:33.000Z
2021-01-25T20:16:33.000Z
src/drivers/milliped.cpp
pierrelouys/PSP-MAME4ALL
54374b0579b7e2377f015ac155d8f519addfaa1a
[ "Unlicense" ]
1
2021-05-24T20:28:35.000Z
2021-05-25T14:44:54.000Z
src/drivers/milliped.cpp
PSP-Archive/PSP-MAME4ALL
54374b0579b7e2377f015ac155d8f519addfaa1a
[ "Unlicense" ]
null
null
null
/*************************************************************************** Millipede memory map (preliminary) 0400-040F POKEY 1 0800-080F POKEY 2 1000-13BF SCREEN RAM (8x8 TILES, 32x30 SCREEN) 13C0-13CF SPRITE IMAGE OFFSETS 13D0-13DF SPRITE HORIZONTAL OFFSETS 13E0-13EF SPRITE VERTICAL OFFSETS 13F0-13FF SPRITE COLOR OFFSETS 2000 BIT 1-4 trackball BIT 5 IS P1 FIRE BIT 6 IS P1 START BIT 7 IS VBLANK 2001 BIT 1-4 trackball BIT 5 IS P2 FIRE BIT 6 IS P2 START BIT 7,8 (?) 2010 BIT 1 IS P1 RIGHT BIT 2 IS P1 LEFT BIT 3 IS P1 DOWN BIT 4 IS P1 UP BIT 5 IS SLAM, LEFT COIN, AND UTIL COIN BIT 6,7 (?) BIT 8 IS RIGHT COIN 2030 earom read 2480-249F COLOR RAM 2500-2502 Coin counters 2503-2504 LEDs 2505-2507 Coin door lights ?? 2600 INTERRUPT ACKNOWLEDGE 2680 CLEAR WATCHDOG 2700 earom control 2780 earom write 4000-7FFF GAME CODE Known issues: * The dipswitches under $2000 aren't fully emulated. There must be some sort of trick to reading them properly. *************************************************************************/ #include "driver.h" #include "vidhrdw/generic.h" #include "machine/atari_vg.h" void milliped_paletteram_w(int offset,int data); void milliped_vh_screenrefresh(struct osd_bitmap *bitmap,int full_refresh); int milliped_IN0_r(int offset); /* JB 971220 */ int milliped_IN1_r(int offset); /* JB 971220 */ void milliped_input_select_w(int offset, int data); void milliped_led_w (int offset, int data) { osd_led_w (offset, ~(data >> 7)); } static struct MemoryReadAddress readmem[] = { { 0x0000, 0x03ff, MRA_RAM }, { 0x0400, 0x040f, pokey1_r }, { 0x0800, 0x080f, pokey2_r }, { 0x1000, 0x13ff, MRA_RAM }, { 0x2000, 0x2000, milliped_IN0_r }, /* JB 971220 */ { 0x2001, 0x2001, milliped_IN1_r }, /* JB 971220 */ { 0x2010, 0x2010, input_port_2_r }, { 0x2011, 0x2011, input_port_3_r }, { 0x2030, 0x2030, atari_vg_earom_r }, { 0x4000, 0x7fff, MRA_ROM }, { 0xf000, 0xffff, MRA_ROM }, /* for the reset / interrupt vectors */ { -1 } /* end of table */ }; static struct MemoryWriteAddress writemem[] = { { 0x0000, 0x03ff, MWA_RAM }, { 0x0400, 0x040f, pokey1_w }, { 0x0800, 0x080f, pokey2_w }, { 0x1000, 0x13ff, videoram_w, &videoram, &videoram_size }, { 0x13c0, 0x13ff, MWA_RAM, &spriteram }, { 0x2480, 0x249f, milliped_paletteram_w, &paletteram }, { 0x2680, 0x2680, watchdog_reset_w }, { 0x2600, 0x2600, MWA_NOP }, /* IRQ ack */ { 0x2500, 0x2502, coin_counter_w }, { 0x2503, 0x2504, milliped_led_w }, { 0x2505, 0x2505, milliped_input_select_w }, { 0x2780, 0x27bf, atari_vg_earom_w }, { 0x2700, 0x2700, atari_vg_earom_ctrl }, { 0x2505, 0x2507, MWA_NOP }, /* coin door lights? */ { 0x4000, 0x73ff, MWA_ROM }, { -1 } /* end of table */ }; INPUT_PORTS_START( input_ports ) PORT_START /* IN0 $2000 */ /* see port 6 for x trackball */ PORT_DIPNAME (0x03, 0x00, "Language", IP_KEY_NONE ) PORT_DIPSETTING ( 0x00, "English" ) PORT_DIPSETTING ( 0x01, "German" ) PORT_DIPSETTING ( 0x02, "French" ) PORT_DIPSETTING ( 0x03, "Spanish" ) PORT_DIPNAME (0x0c, 0x04, "Bonus", IP_KEY_NONE ) PORT_DIPSETTING ( 0x00, "0" ) PORT_DIPSETTING ( 0x04, "0 1x" ) PORT_DIPSETTING ( 0x08, "0 1x 2x" ) PORT_DIPSETTING ( 0x0c, "0 1x 2x 3x" ) PORT_BIT ( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_BIT ( 0x20, IP_ACTIVE_LOW, IPT_START1 ) PORT_BIT ( 0x40, IP_ACTIVE_HIGH, IPT_VBLANK ) PORT_BIT ( 0x80, IP_ACTIVE_HIGH, IPT_UNKNOWN ) PORT_START /* IN1 $2001 */ /* see port 7 for y trackball */ PORT_BIT ( 0x03, IP_ACTIVE_HIGH, IPT_UNKNOWN ) /* JB 971220 */ PORT_DIPNAME (0x04, 0x00, "Credit Minimum", IP_KEY_NONE ) /* JB 971220 */ PORT_DIPSETTING ( 0x00, "1" ) PORT_DIPSETTING ( 0x04, "2" ) PORT_DIPNAME (0x08, 0x00, "Coin Counters", IP_KEY_NONE ) /* JB 971220 */ PORT_DIPSETTING ( 0x00, "1" ) PORT_DIPSETTING ( 0x08, "2" ) PORT_BIT ( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 | IPF_COCKTAIL ) PORT_BIT ( 0x20, IP_ACTIVE_LOW, IPT_START2 ) PORT_BIT ( 0x40, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT ( 0x80, IP_ACTIVE_HIGH, IPT_UNKNOWN ) PORT_START /* IN2 $2010 */ PORT_BIT ( 0x01, IP_ACTIVE_LOW, IP_KEY_NONE ) PORT_BIT ( 0x02, IP_ACTIVE_LOW, IP_KEY_NONE ) PORT_BIT ( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN | IPF_8WAY ) PORT_BIT ( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_UP | IPF_8WAY ) PORT_BIT ( 0x10, IP_ACTIVE_LOW, IPT_TILT ) PORT_BIT ( 0x20, IP_ACTIVE_LOW, IPT_COIN1 ) PORT_BIT ( 0x40, IP_ACTIVE_LOW, IPT_COIN2 ) PORT_BIT ( 0x80, IP_ACTIVE_LOW, IPT_COIN3 ) PORT_START /* IN3 $2011 */ PORT_BIT ( 0x01, IP_ACTIVE_LOW, IP_KEY_NONE ) PORT_BIT ( 0x02, IP_ACTIVE_LOW, IP_KEY_NONE ) PORT_BIT ( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN | IPF_8WAY | IPF_COCKTAIL ) PORT_BIT ( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_UP | IPF_8WAY | IPF_COCKTAIL ) PORT_BIT ( 0x10, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT ( 0x20, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT ( 0x40, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BITX( 0x80, 0x80, IPT_DIPSWITCH_NAME | IPF_TOGGLE, "Service Mode", OSD_KEY_F2, IP_JOY_NONE, 0 ) PORT_DIPSETTING( 0x80, "Off" ) PORT_DIPSETTING( 0x00, "On" ) PORT_START /* 4 */ /* DSW1 $0408 */ PORT_DIPNAME (0x01, 0x00, "Millipede Head", IP_KEY_NONE ) PORT_DIPSETTING ( 0x00, "Easy" ) PORT_DIPSETTING ( 0x01, "Hard" ) PORT_DIPNAME (0x02, 0x00, "Beetle", IP_KEY_NONE ) PORT_DIPSETTING ( 0x00, "Easy" ) PORT_DIPSETTING ( 0x02, "Hard" ) PORT_DIPNAME (0x0c, 0x04, "Lives", IP_KEY_NONE ) PORT_DIPSETTING ( 0x00, "2" ) PORT_DIPSETTING ( 0x04, "3" ) PORT_DIPSETTING ( 0x08, "4" ) PORT_DIPSETTING ( 0x0c, "5" ) PORT_DIPNAME (0x30, 0x10, "Bonus Life", IP_KEY_NONE ) PORT_DIPSETTING ( 0x00, "12000" ) PORT_DIPSETTING ( 0x10, "15000" ) PORT_DIPSETTING ( 0x20, "20000" ) PORT_DIPSETTING ( 0x30, "None" ) PORT_DIPNAME (0x40, 0x00, "Spider", IP_KEY_NONE ) PORT_DIPSETTING ( 0x00, "Easy" ) PORT_DIPSETTING ( 0x40, "Hard" ) PORT_DIPNAME (0x80, 0x00, "Starting Score Select", IP_KEY_NONE ) PORT_DIPSETTING ( 0x00, "On" ) PORT_DIPSETTING ( 0x80, "Off" ) PORT_START /* 5 */ /* DSW2 $0808 */ PORT_DIPNAME (0x03, 0x02, "Coinage", IP_KEY_NONE ) PORT_DIPSETTING ( 0x00, "Free Play" ) PORT_DIPSETTING ( 0x01, "1 Coin/2 Credits" ) PORT_DIPSETTING ( 0x02, "1 Coin/1 Credit" ) PORT_DIPSETTING ( 0x03, "2 Coins/1 Credit" ) PORT_DIPNAME (0x0c, 0x00, "Right Coin", IP_KEY_NONE ) PORT_DIPSETTING ( 0x00, "*1" ) PORT_DIPSETTING ( 0x04, "*4" ) PORT_DIPSETTING ( 0x08, "*5" ) PORT_DIPSETTING ( 0x0c, "*6" ) PORT_DIPNAME (0x10, 0x00, "Left Coin", IP_KEY_NONE ) PORT_DIPSETTING ( 0x00, "*1" ) PORT_DIPSETTING ( 0x10, "*2" ) PORT_DIPNAME (0xe0, 0x00, "Bonus Coins", IP_KEY_NONE ) PORT_DIPSETTING ( 0x00, "None" ) PORT_DIPSETTING ( 0x20, "3 credits/2 coins" ) PORT_DIPSETTING ( 0x40, "5 credits/4 coins" ) PORT_DIPSETTING ( 0x60, "6 credits/4 coins" ) PORT_DIPSETTING ( 0x80, "6 credits/5 coins" ) PORT_DIPSETTING ( 0xa0, "4 credits/3 coins" ) PORT_DIPSETTING ( 0xc0, "Demo mode" ) PORT_START /* IN6: FAKE - used for trackball-x at $2000 */ PORT_ANALOGX( 0xff, 0x00, IPT_TRACKBALL_X | IPF_REVERSE, 50, 10, 0, 0, IP_KEY_NONE, IP_KEY_NONE, IP_JOY_NONE, IP_JOY_NONE, 4 ) PORT_START /* IN7: FAKE - used for trackball-y at $2001 */ PORT_ANALOGX( 0xff, 0x00, IPT_TRACKBALL_Y | IPF_REVERSE, 50, 10, 0, 0, IP_KEY_NONE, IP_KEY_NONE, IP_JOY_NONE, IP_JOY_NONE, 4 ) INPUT_PORTS_END static struct GfxLayout charlayout = { 8,8, /* 8*8 characters */ 256, /* 256 characters */ 2, /* 2 bits per pixel */ { 0, 256*8*8 }, /* the two bitplanes are separated */ { 0, 1, 2, 3, 4, 5, 6, 7 }, { 0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8 }, 8*8 /* every char takes 8 consecutive bytes */ }; static struct GfxLayout spritelayout = { 8,16, /* 16*8 sprites */ 128, /* 64 sprites */ 2, /* 2 bits per pixel */ { 0, 128*16*8 }, /* the two bitplanes are separated */ { 0, 1, 2, 3, 4, 5, 6, 7 }, { 0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8, 8*8, 9*8, 10*8, 11*8, 12*8, 13*8, 14*8, 15*8 }, 16*8 /* every sprite takes 16 consecutive bytes */ }; static struct GfxDecodeInfo gfxdecodeinfo[] = { { 1, 0x0000, &charlayout, 0, 4 }, /* use colors 0-15 */ { 1, 0x0000, &spritelayout, 16, 1 }, /* use colors 16-19 */ { -1 } /* end of array */ }; static struct POKEYinterface pokey_interface = { 2, /* 2 chips */ 1500000, /* 1.5 MHz??? */ 50, POKEY_DEFAULT_GAIN, NO_CLIP, /* The 8 pot handlers */ { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, /* The allpot handler */ { input_port_4_r, input_port_5_r }, }; static struct MachineDriver machine_driver = { /* basic machine hardware */ { { CPU_M6502, 1500000, /* 1.5 Mhz ???? */ 0, readmem,writemem,0,0, interrupt,4 } }, 60, DEFAULT_REAL_60HZ_VBLANK_DURATION, /* frames per second, vblank duration */ 10, 0, /* video hardware */ 32*8, 32*8, { 0*8, 32*8-1, 0*8, 30*8-1 }, gfxdecodeinfo, 32, 32, 0, VIDEO_TYPE_RASTER|VIDEO_SUPPORTS_DIRTY|VIDEO_MODIFIES_PALETTE, 0, generic_vh_start, generic_vh_stop, milliped_vh_screenrefresh, /* sound hardware */ 0,0,0,0, { { SOUND_POKEY, &pokey_interface } } }; /*************************************************************************** Game driver(s) ***************************************************************************/ ROM_START( milliped_rom ) ROM_REGION(0x10000) /* 64k for code */ ROM_LOAD( "milliped.104", 0x4000, 0x1000, 0x40711675 ) ROM_LOAD( "milliped.103", 0x5000, 0x1000, 0xfb01baf2 ) ROM_LOAD( "milliped.102", 0x6000, 0x1000, 0x62e137e0 ) ROM_LOAD( "milliped.101", 0x7000, 0x1000, 0x46752c7d ) ROM_RELOAD( 0xf000, 0x1000 ) /* for the reset and interrupt vectors */ ROM_REGION_DISPOSE(0x1000) /* temporary space for graphics (disposed after conversion) */ ROM_LOAD( "milliped.106", 0x0000, 0x0800, 0xf4468045 ) ROM_LOAD( "milliped.107", 0x0800, 0x0800, 0x68c3437a ) ROM_END struct GameDriver milliped_driver = { __FILE__, 0, "milliped", "Millipede", "1982", "Atari", "Ivan Mackintosh\nNicola Salmoria\nJohn Butler\nAaron Giles\nBernd Wiebelt\nBrad Oliver", 0, &machine_driver, 0, milliped_rom, 0, 0, 0, 0, /* sound_prom */ input_ports, 0, 0, 0, ORIENTATION_ROTATE_270, atari_vg_earom_load, atari_vg_earom_save };
29.822034
134
0.637586
pierrelouys
ad9601f7ae49dc17671c16c6096ce479c6bbd639
9,600
cpp
C++
quake_framebuffer/quake_framebuffer/sv_move.cpp
WarlockD/quake-stm32
8414f407f6fc529bf9d5a371ed91c1ee1194679b
[ "BSD-2-Clause" ]
4
2018-07-03T14:21:39.000Z
2021-06-01T06:12:14.000Z
quake_framebuffer/quake_framebuffer/sv_move.cpp
WarlockD/quake-stm32
8414f407f6fc529bf9d5a371ed91c1ee1194679b
[ "BSD-2-Clause" ]
null
null
null
quake_framebuffer/quake_framebuffer/sv_move.cpp
WarlockD/quake-stm32
8414f407f6fc529bf9d5a371ed91c1ee1194679b
[ "BSD-2-Clause" ]
null
null
null
/* Copyright (C) 1996-1997 Id Software, 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. */ // sv_move.c -- monster movement #include "icommon.h" #define STEPSIZE 18 /* ============= SV_CheckBottom Returns false if any part of the bottom of the entity is off an edge that is not a staircase. ============= */ int c_yes, c_no; qboolean SV_CheckBottom (edict_t *ent) { vec3_t mins, maxs, start, stop; trace_t trace; int x, y; float mid, bottom; VectorAdd (ent->v.origin, ent->v.mins, mins); VectorAdd (ent->v.origin, ent->v.maxs, maxs); // if all of the points under the corners are solid world, don't bother // with the tougher checks // the corners must be within 16 of the midpoint start[2] = mins[2] - 1; for (x=0 ; x<=1 ; x++) for (y=0 ; y<=1 ; y++) { start[0] = x ? maxs[0] : mins[0]; start[1] = y ? maxs[1] : mins[1]; if (SV_PointContents (start) != CONTENTS_SOLID) goto realcheck; } c_yes++; return true; // we got out easy realcheck: c_no++; // // check it for real... // start[2] = mins[2]; // the midpoint must be within 16 of the bottom start[0] = stop[0] = (mins[0] + maxs[0])*0.5f; start[1] = stop[1] = (mins[1] + maxs[1])*0.5f; stop[2] = start[2] - 2*STEPSIZE; trace = SV_Move (start, vec3_origin, vec3_origin, stop, true, ent); if (trace.fraction == 1.0) return false; mid = bottom = trace.endpos[2]; // the corners must be within 16 of the midpoint for (x=0 ; x<=1 ; x++) for (y=0 ; y<=1 ; y++) { start[0] = stop[0] = x ? maxs[0] : mins[0]; start[1] = stop[1] = y ? maxs[1] : mins[1]; trace = SV_Move (start, vec3_origin, vec3_origin, stop, true, ent); if (trace.fraction != 1.0 && trace.endpos[2] > bottom) bottom = trace.endpos[2]; if (trace.fraction == 1.0 || mid - trace.endpos[2] > STEPSIZE) return false; } c_yes++; return true; } /* ============= SV_movestep Called by monster program code. The move will be adjusted for slopes and stairs, but if the move isn't possible, no move is done, false is returned, and vm.pr_global_struct->trace_normal is set to the normal of the blocking wall ============= */ qboolean SV_movestep (edict_t *ent, vec3_t move, qboolean relink) { float dz; vec3_t oldorg, neworg, end; trace_t trace; int i; edict_t *enemy; // try the move VectorCopy (ent->v.origin, oldorg); VectorAdd (ent->v.origin, move, neworg); // flying monsters don't step up if ( (int)ent->v.flags & (FL_SWIM | FL_FLY) ) { // try one move with vertical motion, then one without for (i=0 ; i<2 ; i++) { VectorAdd (ent->v.origin, move, neworg); enemy = ent->v.enemy; if (i == 0 && enemy != sv.worldedict) { dz = ent->v.origin[2] - ent->v.enemy->v.origin[2]; if (dz > 40) neworg[2] -= 8; if (dz < 30) neworg[2] += 8; } trace = SV_Move (ent->v.origin, ent->v.mins, ent->v.maxs, neworg, false, ent); if (trace.fraction == 1) { if ( ((int)ent->v.flags & FL_SWIM) && SV_PointContents(trace.endpos) == CONTENTS_EMPTY ) return false; // swim monster left water VectorCopy (trace.endpos, ent->v.origin); if (relink) SV_LinkEdict (ent, true); return true; } if (enemy == nullptr) break; } return false; } // push down from a step height above the wished position neworg[2] += STEPSIZE; VectorCopy (neworg, end); end[2] -= STEPSIZE*2; trace = SV_Move (neworg, ent->v.mins, ent->v.maxs, end, false, ent); if (trace.allsolid) return false; if (trace.startsolid) { neworg[2] -= STEPSIZE; trace = SV_Move (neworg, ent->v.mins, ent->v.maxs, end, false, ent); if (trace.allsolid || trace.startsolid) return false; } if (trace.fraction == 1) { // if monster had the ground pulled out, go ahead and fall if ( (int)ent->v.flags & FL_PARTIALGROUND ) { VectorAdd (ent->v.origin, move, ent->v.origin); if (relink) SV_LinkEdict (ent, true); ent->v.flags = static_cast<float>((int)ent->v.flags & ~FL_ONGROUND); // Con_Printf ("fall down\n"); return true; } return false; // walked off an edge } // check point traces down for dangling corners VectorCopy (trace.endpos, ent->v.origin); if (!SV_CheckBottom (ent)) { if ( (int)ent->v.flags & FL_PARTIALGROUND ) { // entity had floor mostly pulled out from underneath it // and is trying to correct if (relink) SV_LinkEdict (ent, true); return true; } VectorCopy (oldorg, ent->v.origin); return false; } if ( (int)ent->v.flags & FL_PARTIALGROUND ) { // Con_Printf ("back on ground\n"); ent->v.flags = static_cast<float>(static_cast<int>(ent->v.flags) & ~FL_PARTIALGROUND); } ent->v.groundentity = vm.EDICT_TO_PROG(trace.ent); // the move is ok if (relink) SV_LinkEdict (ent, true); return true; } //============================================================================ /* ====================== SV_StepDirection Turns to the movement direction, and walks the current distance if facing it. ====================== */ void PF_changeyaw (void); qboolean SV_StepDirection (edict_t *ent, float yaw, float dist) { vec3_t move, oldorigin; float delta; ent->v.ideal_yaw = yaw; PF_changeyaw(); static constexpr float yaw_constant= static_cast<float>(M_PI*2.0 / 360.0); yaw = yaw* yaw_constant; move[0] = cos(yaw)*dist; move[1] = sin(yaw)*dist; move[2] = 0; VectorCopy (ent->v.origin, oldorigin); if (SV_movestep (ent, move, false)) { delta = ent->v.angles[YAW] - ent->v.ideal_yaw; if (delta > 45.0f && delta < 315.0f) { // not turned far enough, so don't take the step VectorCopy (oldorigin, ent->v.origin); } SV_LinkEdict (ent, true); return true; } SV_LinkEdict (ent, true); return false; } /* ====================== SV_FixCheckBottom ====================== */ void SV_FixCheckBottom (edict_t *ent) { // Con_Printf ("SV_FixCheckBottom\n"); ent->v.flags = static_cast<float>(static_cast<int>(ent->v.flags) | FL_PARTIALGROUND); } /* ================ SV_NewChaseDir ================ */ #define DI_NODIR -1 void SV_NewChaseDir (edict_t *actor, edict_t *enemy, float dist) { float deltax,deltay; float d[3]; float tdir, olddir, turnaround; olddir = anglemod( (int)(actor->v.ideal_yaw/45.0f)*45.0f ); turnaround = anglemod(olddir - 180); deltax = enemy->v.origin[0] - actor->v.origin[0]; deltay = enemy->v.origin[1] - actor->v.origin[1]; if (deltax>10) d[1]= 0; else if (deltax<-10) d[1]= 180; else d[1]= DI_NODIR; if (deltay<-10) d[2]= 270; else if (deltay>10) d[2]= 90; else d[2]= DI_NODIR; // try direct route if (d[1] != DI_NODIR && d[2] != DI_NODIR) { if (d[1] == 0) tdir = d[2] == 90.0f ? 45.0f : 315.0f; else tdir = d[2] == 90.0f ? 135.0f : 215.0f; if (tdir != turnaround && SV_StepDirection(actor, tdir, dist)) return; } // try other directions if ( ((rand()&3) & 1) || std::abs(deltay)>abs(deltax)) { tdir=d[1]; d[1]=d[2]; d[2]=tdir; } if (d[1]!=DI_NODIR && d[1]!=turnaround && SV_StepDirection(actor, d[1], dist)) return; if (d[2]!=DI_NODIR && d[2]!=turnaround && SV_StepDirection(actor, d[2], dist)) return; /* there is no direct path to the player, so pick another direction */ if (olddir!=DI_NODIR && SV_StepDirection(actor, olddir, dist)) return; if (rand()&1) /*randomly determine direction of search*/ { for (tdir=0 ; tdir<=315 ; tdir += 45) if (tdir!=turnaround && SV_StepDirection(actor, tdir, dist) ) return; } else { for (tdir=315 ; tdir >=0 ; tdir -= 45) if (tdir!=turnaround && SV_StepDirection(actor, tdir, dist) ) return; } if (turnaround != DI_NODIR && SV_StepDirection(actor, turnaround, dist) ) return; actor->v.ideal_yaw = olddir; // can't move // if a bridge was pulled out from underneath a monster, it may not have // a valid standing position at all if (!SV_CheckBottom (actor)) SV_FixCheckBottom (actor); } /* ====================== SV_CloseEnough ====================== */ qboolean SV_CloseEnough (edict_t *ent, edict_t *goal, float dist) { int i; for (i=0 ; i<3 ; i++) { if (goal->v.absmin[i] > ent->v.absmax[i] + dist) return false; if (goal->v.absmax[i] < ent->v.absmin[i] - dist) return false; } return true; } /* ====================== SV_MoveToGoal ====================== */ void SV_MoveToGoal (void) { #ifdef QUAKE2 edict_t *enemy; #endif auto ent = vm.pr_global_struct->self; auto goal = ent->v.goalentity; float dist = vm.G_FLOAT(OFS_PARM0); if ( !( (int)ent->v.flags & (FL_ONGROUND|FL_FLY|FL_SWIM) ) ) { vm.G_FLOAT(OFS_RETURN) = 0; return; } // if the next step hits the enemy, return immediately #ifdef QUAKE2 enemy = vm.PROG_TO_EDICT(ent->v.enemy); if (enemy != sv.edicts && SV_CloseEnough (ent, enemy, dist) ) #else if (ent->v.enemy != nullptr && SV_CloseEnough (ent, goal, dist) ) #endif return; // bump around... if ( (rand()&3)==1 || !SV_StepDirection (ent, ent->v.ideal_yaw, dist)) { SV_NewChaseDir (ent, goal, dist); } }
22.535211
92
0.621354
WarlockD
ad9db69271a9151979b183ac511aa504315c42c6
1,106
cpp
C++
c++/dp/MiniSqaureCut.cpp
Nk095291/pepcoding
fb57f8fa58c155d38bdbc47824f547e24c0804b6
[ "MIT" ]
1
2020-04-24T05:45:44.000Z
2020-04-24T05:45:44.000Z
c++/dp/MiniSqaureCut.cpp
Nk095291/pepcoding
fb57f8fa58c155d38bdbc47824f547e24c0804b6
[ "MIT" ]
null
null
null
c++/dp/MiniSqaureCut.cpp
Nk095291/pepcoding
fb57f8fa58c155d38bdbc47824f547e24c0804b6
[ "MIT" ]
null
null
null
#include<iostream> #include<vector> #include<climits> using namespace std; int solve(vector<vector<int>>&res, int b,int l){ if(l<=0||b<=0) return 0; if(l==b) return 0; if(res[b][l]!=INT_MAX) return res[b][l]; for(int i =1;i<=min(b,l);i++){ int p1v=solve(res,b-i,i); int p2v=solve(res,b,l-i); int p1h=solve(res,i,l-i); int p2h=solve(res,b-i,l); res[b][l]=min((p1h+p2h+1),(p1v+p2v+1)); } return res[b][l]; } int solve2(vector<vector<int>>&res, int b,int l){ if(l==0||b==0) return 0; if(l==b) return 1; if(res[b][l]!=0) return res[b][l]; int mymin=INT_MAX; for(int i =1;i<=min(b,l);i++){ int p1v=solve(res,b-i,i); int p2v=solve(res,b,l-i); int c1=p1v+p2v+1; int p1h=solve(res,i,l-i); int p2h=solve(res,b-i,l); int c2 =p1h+p2h+1; mymin=min(mymin,min(c1,c2)); } res[b][l]=mymin; return mymin; } int main(){ vector<vector<int>>res(31,vector<int>(36+1,INT_MAX)); cout<<solve(res,30,36); }
21.269231
57
0.507233
Nk095291
ada146d03ec82a7927462795c75ab534000fad54
451
cpp
C++
Arrays - Reverse array/Arrays - Reverse array/Source.cpp
CHList/CS-305
731a192fb8ef38bde2e845733d43fd63e4129695
[ "MIT" ]
null
null
null
Arrays - Reverse array/Arrays - Reverse array/Source.cpp
CHList/CS-305
731a192fb8ef38bde2e845733d43fd63e4129695
[ "MIT" ]
null
null
null
Arrays - Reverse array/Arrays - Reverse array/Source.cpp
CHList/CS-305
731a192fb8ef38bde2e845733d43fd63e4129695
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; void reverseArray(int [], int); int main() { const int size = 6; int list[size] = { 1,6,7,9,2,5 }; reverseArray(list, size); cout << list[0]; for (int i = 1; i < size; i++) { cout << "," << list[i]; } cout << endl; return 0; } void reverseArray(int list[], int size) { int temp = 0; for (int i = 1; i <= size/2; i++) { temp = list[size-i]; list[size - i] = list[i-1]; list[i-1] = temp; } }
18.791667
41
0.552106
CHList
ada2e2c33c4a1f6ea0a55e19426f4182afc20be6
1,115
cpp
C++
03-composition-references/1-reference/assign_a_reference.cpp
nofar88/cpp-5782
473c68627fc0908fdef8956caf1e1d2267c9417b
[ "MIT" ]
14
2021-01-30T16:36:18.000Z
2022-03-30T17:24:44.000Z
03-composition-references/1-reference/assign_a_reference.cpp
dimastar2310/cpp-5781
615ba07e0841522df74384f380172557f5e305a7
[ "MIT" ]
1
2022-03-02T20:55:14.000Z
2022-03-02T20:55:14.000Z
03-composition-references/1-reference/assign_a_reference.cpp
dimastar2310/cpp-5781
615ba07e0841522df74384f380172557f5e305a7
[ "MIT" ]
16
2021-03-02T11:13:41.000Z
2021-07-09T14:18:15.000Z
/** * Demonstrates assigning values to references in C++. * * @author Erel Segal-Halevi * @since 2018-02 */ #include <iostream> using namespace std; int main() { int* p1; //int& r1; // compile error int num = 1, num2 = 999; cout << "Pointer:" << endl; int* pnum = &num; cout << "pnum = " << pnum << " " << *pnum << " " << num << endl; (*pnum) = 2; cout << "pnum = " << pnum << " " << *pnum << " " << num << endl; pnum = &num2; cout << "pnum = " << pnum << " " << *pnum << " " << num << endl; pnum += 4; // unsafe cout << "pnum = " << pnum << " " << *pnum << " " << num << endl << endl; cout << "Reference:" << endl; int& rnum = num; cout << "rnum = " << &rnum << " " << rnum << " " << num << endl; rnum = 3; // Here a reference is like a pointer cout << "rnum = " << &rnum << " " << rnum << " " << num << endl; rnum = num2; // Here a reference is unlike a pointer cout << "rnum = " << &rnum << " " << rnum << " " << num << endl; rnum += 4; cout << "rnum = " << &rnum << " " << rnum << " " << num << endl << endl; }
30.135135
76
0.442152
nofar88
ada5da0873736248a9ef99e8067522d738188fd2
838
cpp
C++
UbiGame_Blank/Source/Game/Util/WallManager.cpp
AdrienPringle/HTN-team-brain-damage
f234bd1e46bd83f5c2a8af5535d3e795e0b8d985
[ "MIT" ]
null
null
null
UbiGame_Blank/Source/Game/Util/WallManager.cpp
AdrienPringle/HTN-team-brain-damage
f234bd1e46bd83f5c2a8af5535d3e795e0b8d985
[ "MIT" ]
null
null
null
UbiGame_Blank/Source/Game/Util/WallManager.cpp
AdrienPringle/HTN-team-brain-damage
f234bd1e46bd83f5c2a8af5535d3e795e0b8d985
[ "MIT" ]
null
null
null
#include "WallManager.h" #include "GameEngine/GameEngineMain.h" #include "Game/GameEntities/WallEntity.h" using namespace Game; WallManager* WallManager::sm_instance = nullptr; WallManager::WallManager(){ wasMouseDown = true; } WallManager::~WallManager(){ } void WallManager::Update(){ //spawn wall on mouse down if(!sf::Mouse::isButtonPressed(sf::Mouse::Left)){ wasMouseDown = false; } else if (!wasMouseDown) { wasMouseDown = true; SpawnWall(); } } void WallManager::SpawnWall(){ sf::RenderWindow *window = GameEngine::GameEngineMain::GetInstance()->GetRenderWindow(); sf::Vector2f mousePos = sf::Vector2f(sf::Mouse::getPosition(*window)); WallEntity* wall = new WallEntity(); wall->SetPos(mousePos); GameEngine::GameEngineMain::GetInstance()->AddEntity(wall); }
23.942857
92
0.689737
AdrienPringle
adad1ee2fe75ed250ac64d745fa10f209da9c2a0
735
cpp
C++
ESOData/Filesystem/DataFileHeader.cpp
FloorBelow/ESOData
eb35a95ec64d56c5842c4df85bc844e06fc72582
[ "MIT" ]
1
2021-12-20T02:46:34.000Z
2021-12-20T02:46:34.000Z
ESOData/Filesystem/DataFileHeader.cpp
rekiofoldhome/ESOData
3c176110e7fa37fcff0b74b0bf0649f7251e59ed
[ "MIT" ]
null
null
null
ESOData/Filesystem/DataFileHeader.cpp
rekiofoldhome/ESOData
3c176110e7fa37fcff0b74b0bf0649f7251e59ed
[ "MIT" ]
1
2021-06-10T03:00:46.000Z
2021-06-10T03:00:46.000Z
#include <ESOData/Filesystem/DataFileHeader.h> #include <ESOData/Serialization/SerializationStream.h> #include <stdexcept> namespace esodata { SerializationStream &operator <<(SerializationStream &stream, const DataFileHeader &header) { stream << DataFileHeader::Signature; stream << header.version; stream << header.unknown; stream << header.headerSize; return stream; } SerializationStream &operator >>(SerializationStream &stream, DataFileHeader &header) { uint32_t signature; stream >> signature; if (signature != DataFileHeader::Signature) throw std::runtime_error("Bad DAT file signature"); stream >> header.version; stream >> header.unknown; stream >> header.headerSize; return stream; } }
24.5
94
0.742857
FloorBelow
adb86ae40f02307ae6ef47ba88df07ccb71ad290
3,225
hpp
C++
src/xml/Xml.hpp
Yousazoe/Solar
349c75f7a61b1727aa0c6d581cf75124b2502a57
[ "Apache-2.0" ]
1
2021-08-07T13:02:01.000Z
2021-08-07T13:02:01.000Z
src/xml/Xml.hpp
Yousazoe/Solar
349c75f7a61b1727aa0c6d581cf75124b2502a57
[ "Apache-2.0" ]
null
null
null
src/xml/Xml.hpp
Yousazoe/Solar
349c75f7a61b1727aa0c6d581cf75124b2502a57
[ "Apache-2.0" ]
null
null
null
#pragma once #include<../thirdparty/tinyxml/tinyxml.h> #include<memory> #include<fstream> namespace tutorial { class XMLAttribute { public: XMLAttribute() : _attrib(nullptr) {} XMLAttribute(TiXmlAttribute *attrib) : _attrib(attrib) {} bool is_empty() const { return _attrib == nullptr; } const char* name() const { return _attrib->Name(); } const char* value() const { return _attrib->Value(); } XMLAttribute next_attrib() { return XMLAttribute(_attrib->Next()); } protected: TiXmlAttribute* _attrib; }; class XMLNode { public: XMLNode() = default; XMLNode(TiXmlElement* node) : _node(node) {} public: TiXmlElement* get_xml_node() { return _node; } bool is_empty() const { return _node == nullptr; } const char* name() const { return _node->Value(); } XMLNode first_child() const { return XMLNode(_node->FirstChildElement()); } XMLNode next_sibling() const { return XMLNode(_node->NextSiblingElement()); } XMLNode first_child(const char* name) const { return XMLNode(_node->FirstChildElement(name)); } XMLNode next_sibling(const char* name) const { return XMLNode(_node->NextSiblingElement(name)); } XMLAttribute first_attrib() { return XMLAttribute(_node->FirstAttribute()); } const char* attribute(const char* name, const char* defValue = "") const { const char *attrib = _node->Attribute(name); return attrib != nullptr ? attrib : defValue; } void attribute(const char* name, float* value, const float& default) const { double v = default; _node->Attribute(name, &v); *value = (float)v; } void attribute(const char* name, int* value, const int& default) const { _node->Attribute(name, value); } size_t child_node_count(const char *name = nullptr) const { size_t numNodes = 0u; TiXmlElement *node1 = _node->FirstChildElement(name); while (node1) { ++numNodes; node1 = node1->NextSiblingElement(name); } return numNodes; } operator bool() const { return !is_empty(); } protected: TiXmlElement* _node = nullptr; }; class XMLDoc { public: XMLDoc() { } ~XMLDoc() { _doc.Clear(); } public: bool has_error() const; XMLNode get_root_node(); void parse_string(const char* text); void parse_buffer(const char* charbuf, size_t size); bool parse_file(const char* file_name); private: TiXmlDocument _doc; std::unique_ptr<char[]> buf; }; inline bool XMLDoc::has_error() const { return _doc.RootElement() == nullptr; } inline XMLNode XMLDoc::get_root_node() { return XMLNode(_doc.RootElement()); } inline void XMLDoc::parse_string(const char* text) { _doc.Parse(text); } inline void XMLDoc::parse_buffer(const char* charbuf, size_t size) { buf.reset(new char[size + 1]); memcpy(buf.get(), charbuf, size); buf[size] = '\0'; parse_string(buf.get()); } inline bool XMLDoc::parse_file(const char* file_name) { std::fstream f(file_name, std::ios::in | std::ios::binary); if (!f.is_open()) return false; f.seekg(0, std::ios::end); auto size = (size_t)f.tellg(); f.seekg(0, std::ios::beg); buf.reset(new char[size + 1]); f.read(buf.get(), size); buf[size] = '\0'; f.close(); parse_string(buf.get()); return true; } }
23.201439
99
0.671628
Yousazoe
adbc18e69243df5c6ea4b52bfeae1e38d8b83f58
6,237
cpp
C++
levelManager.cpp
LEpigeon888/IndevBuggedGame
c99f9bc64d3b52fca830be4a79fb81dbdb8f97d7
[ "Zlib" ]
null
null
null
levelManager.cpp
LEpigeon888/IndevBuggedGame
c99f9bc64d3b52fca830be4a79fb81dbdb8f97d7
[ "Zlib" ]
null
null
null
levelManager.cpp
LEpigeon888/IndevBuggedGame
c99f9bc64d3b52fca830be4a79fb81dbdb8f97d7
[ "Zlib" ]
null
null
null
#include <fstream> #include <utility> #include "blockManager.hpp" #include "eventManager.hpp" #include "global.hpp" #include "levelManager.hpp" #include "utilities.hpp" void LevelManager::setBlockHere(std::map<Point, std::unique_ptr<Block>>& currentMap, BlockId idOfBlock, int xBlock, int yBlock) { auto block = BlockManager::createBlock(idOfBlock); block->setPosition({xBlock * SIZE_BLOCK, yBlock * SIZE_BLOCK}); currentMap[Point(xBlock, yBlock)] = std::move(block); } void LevelManager::loadLevelFromFile(LevelInfo& currentLevel, std::string filePath) { size_t spacePos; std::string currentLine; std::string currentType; std::string firstWordOfLine; std::ifstream file; file.open("resources/" + filePath); while (std::getline(file, currentLine)) { spacePos = currentLine.find(' '); firstWordOfLine = currentLine.substr(0, spacePos); if (spacePos == std::string::npos) { currentLine.clear(); } else { currentLine.erase(0, spacePos + 1); } if (firstWordOfLine == "GAME_VERSION") { currentLevel.initialGameVersion = VersionNumber(currentLine); } else if (firstWordOfLine == "NEXT_LEVEL") { currentLevel.nextLevelName = currentLine; } else if (firstWordOfLine == "SIZE_OF_LEVEL") { currentLevel.limitOfGame.top = 0; currentLevel.limitOfGame.left = 0; currentLevel.limitOfGame.width = Utilities::stringToInt(Utilities::readFirstString(currentLine)); currentLevel.limitOfGame.height = Utilities::stringToInt(Utilities::readFirstString(currentLine)); } else if (firstWordOfLine == "PLAYER_POSITION") { currentLevel.playerStartPosition.x = Utilities::stringToInt(Utilities::readFirstString(currentLine)); currentLevel.playerStartPosition.y = Utilities::stringToInt(Utilities::readFirstString(currentLine)); } else if (firstWordOfLine == "NEW_BLOCK") { BlockId idOfBlock = BlockManager::stringBlockId(Utilities::readFirstString(currentLine)); int posX = Utilities::stringToInt(Utilities::readFirstString(currentLine)); int posY = Utilities::stringToInt(Utilities::readFirstString(currentLine)); setBlockHere(currentLevel.mapOfGame, idOfBlock, posX, posY); } else if (firstWordOfLine == "NEW_EVENT") { std::string nameOfEvent = Utilities::readFirstString(currentLine); int posX = Utilities::stringToInt(Utilities::readFirstString(currentLine)); int posY = Utilities::stringToInt(Utilities::readFirstString(currentLine)); int sizeX = Utilities::stringToInt(Utilities::readFirstString(currentLine)); int sizeY = Utilities::stringToInt(Utilities::readFirstString(currentLine)); currentLevel.listOfEvent.emplace_back( EventManager::createEvent(nameOfEvent, sf::IntRect{posX, posY, sizeX, sizeY}, currentLine)); } } file.close(); } void LevelManager::loadBasicLevelFromFile(BasicLevelInfo& currentLevel, std::string filePath) { size_t spacePos; std::string currentLine; std::string currentType; std::string firstWordOfLine; std::ifstream file; file.open("resources/" + filePath); while (std::getline(file, currentLine)) { spacePos = currentLine.find(' '); firstWordOfLine = currentLine.substr(0, spacePos); if (spacePos == std::string::npos) { currentLine.clear(); } else { currentLine.erase(0, spacePos + 1); } if (firstWordOfLine == "SIZE_OF_LEVEL") { currentLevel.limitOfGame.top = 0; currentLevel.limitOfGame.left = 0; currentLevel.limitOfGame.width = Utilities::stringToInt(Utilities::readFirstString(currentLine)); currentLevel.limitOfGame.height = Utilities::stringToInt(Utilities::readFirstString(currentLine)); } else if (firstWordOfLine == "PLAYER_POSITION") { currentLevel.playerStartPosition.x = Utilities::stringToInt(Utilities::readFirstString(currentLine)); currentLevel.playerStartPosition.y = Utilities::stringToInt(Utilities::readFirstString(currentLine)); } else if (firstWordOfLine == "NEW_BLOCK") { BasicBlock newBlock; newBlock.id = BlockManager::stringBlockId(Utilities::readFirstString(currentLine)); int posX = Utilities::stringToInt(Utilities::readFirstString(currentLine)); int posY = Utilities::stringToInt(Utilities::readFirstString(currentLine)); newBlock.sprite.setSize(sf::Vector2f(SIZE_BLOCK, SIZE_BLOCK)); newBlock.sprite.setPosition(SIZE_BLOCK * posX, SIZE_BLOCK * posY); newBlock.sprite.setFillColor(BlockManager::getColorOfBlock(newBlock.id)); currentLevel.mapOfGame[Point(posX, posY)] = std::move(newBlock); } else { std::string newLine = firstWordOfLine; if (!currentLine.empty()) { newLine += " " + currentLine; } currentLevel.otherLines.push_back(newLine); } } file.close(); } void LevelManager::saveBasicLevel(BasicLevelInfo& currentLevel, std::string levelName) { std::ofstream file; file.open("resources/" + levelName); file << "SIZE_OF_LEVEL " << currentLevel.limitOfGame.width << " " << currentLevel.limitOfGame.height << std::endl; file << "PLAYER_POSITION " << currentLevel.playerStartPosition.x << " " << currentLevel.playerStartPosition.y << std::endl; for (auto& currentLevelIte : currentLevel.mapOfGame) { file << "NEW_BLOCK " << BlockManager::blockIdToString(currentLevelIte.second.id) << " " << currentLevelIte.first.first << " " << currentLevelIte.first.second << std::endl; } for (std::string& line : currentLevel.otherLines) { file << line << std::endl; } file.close(); }
36.473684
118
0.636364
LEpigeon888
adbecc30a0fe5a2dbe4ac91abdf0b678606a2c3f
955
cpp
C++
src/mxml/parsing/MordentHandler.cpp
dkun7944/mxml
6450e7cab88eb6ee0ac469f437047072e1868ea4
[ "MIT" ]
18
2016-05-22T00:55:28.000Z
2021-03-29T08:44:23.000Z
src/mxml/parsing/MordentHandler.cpp
dkun7944/mxml
6450e7cab88eb6ee0ac469f437047072e1868ea4
[ "MIT" ]
6
2017-05-17T13:20:09.000Z
2018-10-22T20:00:57.000Z
src/mxml/parsing/MordentHandler.cpp
dkun7944/mxml
6450e7cab88eb6ee0ac469f437047072e1868ea4
[ "MIT" ]
14
2016-05-12T22:54:34.000Z
2021-10-19T12:43:16.000Z
// Copyright © 2016 Venture Media Labs. // // This file is part of mxml. The full mxml copyright notice, including // terms governing use, modification, and redistribution, is contained in the // file LICENSE at the root of the source code distribution tree. #include "MordentHandler.h" #include "EmptyPlacementHandler.h" namespace mxml { using dom::Mordent; static const char* kPlacementAttribute = "placement"; static const char* kLongAttribute = "long"; void MordentHandler::startElement(const lxml::QName& qname, const AttributeMap& attributes) { _result.reset(new Mordent()); auto placement = attributes.find(kPlacementAttribute); if (placement != attributes.end()) _result->setPlacement(presentOptional(EmptyPlacementHandler::placementFromString(placement->second))); auto longv = attributes.find(kLongAttribute); if (longv != attributes.end()) _result->setLong(longv->second == "yes"); } } // namespace
30.806452
110
0.736126
dkun7944
adccb5f1b156054bc25860aecc8c8c7d649bfd59
14,637
cpp
C++
Source/Client/IM-Client/IMClient/HttpDownloader.cpp
InstantBusinessNetwork/IBN
bbcf47de56bfc52049eeb2e46677642a28f38825
[ "MIT" ]
21
2015-07-22T15:22:41.000Z
2021-03-23T05:40:44.000Z
Source/Client/IM-Client/IMClient/HttpDownloader.cpp
InstantBusinessNetwork/IBN
bbcf47de56bfc52049eeb2e46677642a28f38825
[ "MIT" ]
11
2015-10-19T07:54:10.000Z
2021-09-01T08:47:56.000Z
Source/Client/IM-Client/IMClient/HttpDownloader.cpp
InstantBusinessNetwork/IBN
bbcf47de56bfc52049eeb2e46677642a28f38825
[ "MIT" ]
16
2015-07-22T15:23:09.000Z
2022-01-17T10:49:43.000Z
// HttpDownloader.cpp: implementation of the CHttpDownloader class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "HttpDownloader.h" #include "Resource.h" #include "GlobalFunction.h" #include "atlenc.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CHttpDownloader::CHttpDownloader() { m_hInternet = 0; m_hConnect = 0; m_hRequest = 0; m_longAbort = FALSE; m_pStream = NULL; m_hWnd = NULL; m_nMessage = 0; m_dwTotalSize = 0; m_dwDownloaded = 0; m_dwTimeout = 60000; m_dwConnectRetryCount = 3; m_ProxyType = GetOptionInt(IDS_NETOPTIONS, IDS_ACCESSTYPE, INTERNET_OPEN_TYPE_PRECONFIG); m_ProxyName.Format(_T("http=http://%s:%s"), GetOptionString(IDS_NETOPTIONS, IDS_PROXYNAME, _T("")), GetOptionString(IDS_NETOPTIONS, IDS_PROXYPORT, _T(""))); // m_UseFireWall = GetOptionInt(IDS_NETOPTIONS, IDS_USEFIREWALL, FALSE); // m_FireWallUser = GetOptionString(IDS_NETOPTIONS, IDS_FIREWALLUSER, ""); // m_FireWallPass = GetOptionString(IDS_NETOPTIONS, IDS_FIREWALLPASS, ""); m_hEvent = ::CreateEvent(NULL, TRUE, TRUE, NULL); } CHttpDownloader::~CHttpDownloader() { Clear(); if(m_pStream) { m_pStream->Release(); m_pStream = NULL; } CloseHandle(m_hEvent); } HRESULT CHttpDownloader::ConnectToServer(_bstr_t &strBuffer) { BOOL bResult; DWORD dwStatus; DWORD nTimeoutCounter; _bstr_t strMethod; _bstr_t strUrl = m_request.url; LPCTSTR szProxyName = NULL; if(m_ProxyType == INTERNET_OPEN_TYPE_PROXY) szProxyName = m_ProxyName; //// InternetOpen \\\\ if(!m_hInternet) m_hInternet = InternetOpen(_T("McHttpDownloader"), m_ProxyType, szProxyName, NULL, INTERNET_FLAG_ASYNC); if(!m_hInternet) { strBuffer = _T("InternetOpen failed"); return E_FAIL; } InternetSetStatusCallback(m_hInternet, (INTERNET_STATUS_CALLBACK)CallbackFunc); //// InternetOpen //// if(m_longAbort > 0) return E_ABORT; //// InternetConnect \\\\ if(!m_hConnect) { m_hConnect = InternetConnect(m_hInternet, m_request.server, (short)m_request.port, NULL, NULL, INTERNET_SERVICE_HTTP, NULL, (DWORD)&m_context); } if(m_hConnect == NULL) { strBuffer = _T("InternetConnect failed"); return INET_E_CANNOT_CONNECT; } //// InternetConnect //// nTimeoutCounter = 0; NewConnect: strMethod = _T("GET"); strBuffer = _T(""); //// OpenRequest \\\\ if(m_hRequest) { ::InternetCloseHandle(m_hRequest); m_hRequest = NULL; } if(m_longAbort > 0) return E_ABORT; DWORD dwFlags = INTERNET_FLAG_KEEP_CONNECTION | INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_RELOAD | INTERNET_FLAG_PRAGMA_NOCACHE | INTERNET_FLAG_NO_UI | INTERNET_FLAG_NO_COOKIES | INTERNET_FLAG_IGNORE_CERT_CN_INVALID | INTERNET_FLAG_NO_AUTO_REDIRECT | INTERNET_FLAG_HYPERLINK | (m_request.bUseSSL ? (INTERNET_FLAG_SECURE/*| INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTPS| INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTP*/) : 0); m_context.op = HTTP_DOWNLOADER_OP_OPEN_REQUEST; m_hRequest = HttpOpenRequest(m_hConnect, strMethod, strUrl, _T("HTTP/1.1"), NULL, NULL, dwFlags, (DWORD)&m_context); if(m_hRequest == NULL) { strBuffer = _T("HttpOpenRequest failed"); return E_FAIL; } if(m_ProxyType == INTERNET_OPEN_TYPE_PROXY) { if(GetOptionInt(IDS_NETOPTIONS,IDS_USEFIREWALL,0)) { CString fireWallUser = GetOptionString(IDS_NETOPTIONS, IDS_FIREWALLUSER, _T("")); CString fireWallPass = GetOptionString(IDS_NETOPTIONS, IDS_FIREWALLPASS, _T("")); ////////////////////////////////////////////////////////////////////////// int HeaderLen = ATL::ProxyAuthorizationStringGetRequiredLength(fireWallUser, fireWallPass); LPTSTR strHeader = new TCHAR[HeaderLen+1]; ZeroMemory(strHeader,HeaderLen+1); HRESULT hr = ATL::ProxyAuthorizationString(fireWallUser, fireWallPass, strHeader, &HeaderLen); ASSERT(hr==S_OK); HttpAddRequestHeaders(m_hRequest, strHeader, HeaderLen, HTTP_ADDREQ_FLAG_ADD ); delete []strHeader; ////////////////////////////////////////////////////////////////////////// } } //// OpenRequest //// NewRequest: if(m_longAbort > 0) return E_ABORT; m_context.op = HTTP_DOWNLOADER_OP_SEND_REQUEST; bResult = HttpSendRequest(m_hRequest, NULL , 0, (LPVOID)(BYTE*)(LPCTSTR)strBuffer, lstrlen(strBuffer)); if(!bResult && 997 == GetLastError()) // Overlapped I/O operation is in progress. bResult = WaitForComplete(m_dwTimeout); // Resolve host name, connect, send request, receive response. if(!bResult) { DWORD dwErrCode = GetLastError(); // ATLTRACE("Send Request error = %d \r\n",dwErrCode); if(dwErrCode == 6) // The handle is invalid. goto NewConnect; if(dwErrCode == ERROR_INTERNET_TIMEOUT) // timeout { if(++nTimeoutCounter < m_dwConnectRetryCount) goto NewConnect; else { strBuffer = _T("Timeout"); return E_FAIL;//INET_E_CONNECTION_TIMEOUT; } } strBuffer = _T("SendRequest failed"); return E_FAIL; } dwStatus = GetHttpStatus(); if(dwStatus == 401 || dwStatus == 407) // Denied or Proxy asks password { if(ERROR_INTERNET_FORCE_RETRY == InternetErrorDlg(GetDesktopWindow(), m_hRequest, ERROR_INTERNET_INCORRECT_PASSWORD, FLAGS_ERROR_UI_FILTER_FOR_ERRORS | FLAGS_ERROR_UI_FLAGS_CHANGE_OPTIONS | FLAGS_ERROR_UI_FLAGS_GENERATE_DATA, NULL)) { goto NewRequest; } } if(dwStatus != 200) // Not OK { strBuffer = _T("SendRequest returned with error"); return INET_E_CANNOT_CONNECT; } return S_OK; } DWORD CHttpDownloader::GetHttpStatus() { LPVOID lpOutBuffer = new char[4]; DWORD dwSize = 4; DWORD Status = 0; DWORD err = 0; BOOL bResult; ret: m_context.op = HTTP_DOWNLOADER_OP_GET_STATUS; bResult = HttpQueryInfo(m_hRequest, HTTP_QUERY_STATUS_CODE, (LPVOID)lpOutBuffer, &dwSize, NULL); if(!bResult&&997 == GetLastError()) WaitForComplete(m_dwTimeout); if(!bResult) { err = GetLastError(); if(err == ERROR_HTTP_HEADER_NOT_FOUND) { return false; //throw(); } else { if (err == ERROR_INSUFFICIENT_BUFFER) { if(lpOutBuffer!=NULL) delete[] lpOutBuffer; lpOutBuffer = new char[dwSize]; goto ret; } else { return Status; //throw(); } } } else { // ATLTRACE("HTTP STATUS - %s \r\n", lpOutBuffer); Status = atol((char*)lpOutBuffer); delete[] lpOutBuffer; lpOutBuffer = NULL; return Status; } } HRESULT CHttpDownloader::WorkFunction() { HRESULT hr; _bstr_t strBuffer; strBuffer = _T(""); if(m_longAbort > 0) { hr = E_ABORT; goto EndWorkFunc; } if(m_request.pCritSect) EnterCriticalSection(m_request.pCritSect); if(m_longAbort > 0) { hr = E_ABORT; goto EndWorkFunc; } hr = ConnectToServer(strBuffer); if(FAILED(hr)) goto EndWorkFunc; hr = ReadData(strBuffer); if(FAILED(hr) || m_dwDownloaded < m_dwTotalSize) { strBuffer = _T("Cannot read data"); goto EndWorkFunc; } EndWorkFunc: // TRACE(_T("HTTP OPERATION = %d\n"), m_context.op); Clear(); if(m_pStream) { LARGE_INTEGER li = {0, 0}; hr = m_pStream->Seek(li, STREAM_SEEK_SET, NULL); } if(m_request.pCritSect) { try { LeaveCriticalSection(m_request.pCritSect); } catch(...) { // MCTRACE(0, _T("LeaveCriticalSection(%08x)"), m_request.pCritSect); } } return hr; } HRESULT CHttpDownloader::ReadData(_bstr_t &strBuffer) { HRESULT hr = E_FAIL; IStream *pStream = NULL; INTERNET_BUFFERS ib ={0}; ULONG ulWritten; BOOL bResult; DWORD dwErr; TCHAR buf[32]; DWORD dwBufferLength; TCHAR *szNULL = _T("\x0"); // Get file size dwBufferLength = 32*sizeof(TCHAR); if(::HttpQueryInfo(m_hRequest, HTTP_QUERY_CONTENT_LENGTH, buf, &dwBufferLength, NULL)) { m_dwTotalSize = _tcstoul(buf, &szNULL, 10); if(m_hWnd != NULL && m_nMessage != 0) ::PostMessage(m_hWnd, m_nMessage, m_dwDownloaded, m_dwTotalSize); } //Check MD5 hash if(m_request.md5 != NULL && _tcslen(m_request.md5) >= 22) { dwBufferLength = 32*sizeof(TCHAR); if(::HttpQueryInfo(m_hRequest, HTTP_QUERY_CONTENT_MD5, buf, &dwBufferLength, NULL)) { if(0 == _tcsnicmp(m_request.md5, buf, 22)) { if(m_hWnd != NULL && m_nMessage != 0) ::PostMessage(m_hWnd, m_nMessage, m_dwTotalSize, m_dwTotalSize); } return S_OK; } } hr = CreateStreamOnHGlobal(NULL, TRUE, &pStream); if(FAILED(hr)) { return hr; } ib.lpcszHeader = NULL; ib.dwHeadersLength = NULL; ib.lpvBuffer = new TCHAR[COMMAND_BUFF_SIZE_PART]; ib.dwBufferLength = COMMAND_BUFF_SIZE_PART; ib.dwStructSize = sizeof(ib); do { ib.dwBufferLength = COMMAND_BUFF_SIZE_PART; if(m_longAbort > 0) { hr = E_ABORT; break; } m_context.op = HTTP_DOWNLOADER_OP_READ_DATA; bResult = InternetReadFileEx(m_hRequest, &ib, IRF_ASYNC | IRF_USE_CONTEXT, (DWORD)&m_context); dwErr = GetLastError(); if(!bResult && dwErr == 997) // Overlapped I/O operation is in progress. { bResult = WaitForComplete(m_dwTimeout); if(bResult) continue; } if(bResult) { if(ib.dwBufferLength) { hr = pStream->Write(ib.lpvBuffer, ib.dwBufferLength, &ulWritten); if(FAILED(hr)) { strBuffer = _T("Cannot write to stream"); break; } m_dwDownloaded += ib.dwBufferLength; if(m_hWnd != NULL && m_nMessage != 0) ::PostMessage(m_hWnd, m_nMessage, m_dwDownloaded, m_dwTotalSize); } } else { hr = E_FAIL; break; } // Sleep(1); } while(ib.dwBufferLength); if(ib.lpvBuffer) { delete[] ib.lpvBuffer; ib.lpvBuffer = NULL; } if(SUCCEEDED(hr) && pStream) { m_pStream = pStream; return hr; } else { if(pStream) pStream->Release(); pStream = NULL; } return hr; } HRESULT CHttpDownloader::Load(LPCTSTR szUrl, IStream **ppStream, LPCTSTR szMD5) { HRESULT hr = E_FAIL; m_longAbort = 0; Clear(); *ppStream = NULL; m_dwDownloaded = 0; m_dwTotalSize = 0; m_request.md5 = szMD5; hr = ParseUrl(szUrl); if(SUCCEEDED(hr)) { if(m_pStream) { m_pStream->Release(); m_pStream = NULL; } m_context.op = HTTP_DOWNLOADER_OP_IDLE; m_context.hEvent = m_hEvent; SetEvent(m_hEvent); hr = WorkFunction(); if(SUCCEEDED(hr)) { m_pStream->AddRef(); *ppStream = m_pStream; } } return hr; } HRESULT CHttpDownloader::ParseUrl(LPCTSTR szUrlIn) { if(!lstrlen(szUrlIn)) return INET_E_INVALID_URL; URL_COMPONENTS uc; memset(&uc, 0, sizeof(uc)); uc.dwStructSize = sizeof(uc); TCHAR szServer[1024]; TCHAR szUrl[1024]; // TCHAR szScheme[1024]; uc.lpszHostName = szServer; uc.dwHostNameLength = sizeof(szServer); uc.lpszUrlPath = szUrl; uc.dwUrlPathLength = sizeof(szUrl); // uc.lpszScheme =szScheme; // uc.dwSchemeLength = sizeof(szScheme); if(!InternetCrackUrl(szUrlIn, lstrlen(szUrlIn), 0, &uc)) return INET_E_INVALID_URL; if(uc.nScheme==INTERNET_SCHEME_HTTPS) m_request.bUseSSL = TRUE; if(lstrlen(szServer)) m_request.server = szServer; if(uc.nPort != 0) m_request.port = uc.nPort; if(lstrlen(szUrl)) m_request.url = szUrl; return S_OK; } void CHttpDownloader::EnableProgress(HWND hWnd, UINT nMessage) { m_hWnd = hWnd; m_nMessage = nMessage; } void CHttpDownloader::Abort() { InterlockedExchange(&m_longAbort, 1); Clear(); SetEvent(m_hEvent); } void CHttpDownloader::Clear() { if(m_hRequest) { InternetCloseHandle(m_hRequest); m_hRequest = NULL; } if(m_hConnect) { InternetCloseHandle(m_hConnect); m_hConnect = NULL; } if(m_hInternet) { InternetCloseHandle(m_hInternet); m_hInternet = NULL; } } void __stdcall CHttpDownloader::CallbackFunc(HINTERNET hInternet, DWORD dwContext, DWORD dwInternetStatus, LPVOID lpvStatusInformation, DWORD dwStatusInformationLength) { // TRACE(_T("INTERNET CALLBACK %08x %08x %d\n"), hInternet, dwContext, dwInternetStatus); if(IsBadWritePtr((LPVOID)dwContext,sizeof(CHttpDownloader :: HttpDownloaderContext))) return; CHttpDownloader::HttpDownloaderContext *pContext = (CHttpDownloader::HttpDownloaderContext*)dwContext; INTERNET_ASYNC_RESULT* pINTERNET_ASYNC_RESULT = NULL; BOOL bRetVal = FALSE; switch (dwInternetStatus) { case INTERNET_STATUS_REQUEST_COMPLETE: pINTERNET_ASYNC_RESULT = (INTERNET_ASYNC_RESULT*)lpvStatusInformation; if(pINTERNET_ASYNC_RESULT->dwError!=ERROR_INTERNET_OPERATION_CANCELLED) { pContext->dwError = pINTERNET_ASYNC_RESULT->dwError; bRetVal = SetEvent(pContext->hEvent); } break; /* case INTERNET_STATUS_RESPONSE_RECEIVED: if(pContext) { if(pContext->op == HTTP_DOWNLOADER_OP_READ_DATA) SetEvent(pContext->hEvent); } break;*/ case INTERNET_STATUS_RESOLVING_NAME: case INTERNET_STATUS_NAME_RESOLVED: case INTERNET_STATUS_CONNECTING_TO_SERVER: case INTERNET_STATUS_CONNECTED_TO_SERVER: case INTERNET_STATUS_SENDING_REQUEST: case INTERNET_STATUS_REQUEST_SENT: case INTERNET_STATUS_RECEIVING_RESPONSE: case INTERNET_STATUS_CTL_RESPONSE_RECEIVED: case INTERNET_STATUS_PREFETCH: case INTERNET_STATUS_CLOSING_CONNECTION: case INTERNET_STATUS_CONNECTION_CLOSED: case INTERNET_STATUS_HANDLE_CREATED: case INTERNET_STATUS_HANDLE_CLOSING: case INTERNET_STATUS_REDIRECT: case INTERNET_STATUS_INTERMEDIATE_RESPONSE: case INTERNET_STATUS_STATE_CHANGE: default: break; } } BOOL CHttpDownloader::WaitForComplete(DWORD dwMilliseconds) { ResetEvent(m_hEvent); DWORD dw = WaitForSingleObject(m_hEvent, dwMilliseconds); //TRACE("\r\n == after WaitForSingleObject == \r\n"); if(m_longAbort > 0) { // TRACE(_T("WaitForComplete: ABORTED, OP = %d\n"), m_context.op); SetLastError(ERROR_INTERNET_CONNECTION_ABORTED); return FALSE; } if(dw == WAIT_TIMEOUT) { // TRACE(_T("WaitForComplete: TIMEOUT, OP = %d\n"), m_context.op); SetLastError(ERROR_INTERNET_TIMEOUT); return FALSE; } if(m_context.dwError != ERROR_SUCCESS) return FALSE; return (dw == WAIT_OBJECT_0); }
23.27027
169
0.662909
InstantBusinessNetwork
add35b5bbe2b0962674ac0b421017a86f1f02314
8,813
cc
C++
common/cpp/src/google_smart_card_common/pp_var_utils/extraction.cc
swapnil119/chromeos_smart_card_connector
c01ec7e9aad61ede90f1eeaf8554540ede988d2d
[ "Apache-2.0" ]
1
2021-10-18T03:23:18.000Z
2021-10-18T03:23:18.000Z
common/cpp/src/google_smart_card_common/pp_var_utils/extraction.cc
AdrianaDJ/chromeos_smart_card_connector
63bcbc1ce293779efbe99a63edfbc824d96719fc
[ "Apache-2.0" ]
1
2021-02-23T22:37:22.000Z
2021-02-23T22:37:22.000Z
common/cpp/src/google_smart_card_common/pp_var_utils/extraction.cc
AdrianaDJ/chromeos_smart_card_connector
63bcbc1ce293779efbe99a63edfbc824d96719fc
[ "Apache-2.0" ]
1
2021-04-15T17:09:55.000Z
2021-04-15T17:09:55.000Z
// Copyright 2016 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <google_smart_card_common/pp_var_utils/extraction.h> #include <cstring> #include <google_smart_card_common/numeric_conversions.h> namespace google_smart_card { namespace { constexpr char kErrorWrongType[] = "Expected a value of type \"%s\", instead got: %s"; template <typename T> bool VarAsInteger(const pp::Var& var, const char* type_name, T* result, std::string* error_message) { int64_t integer; if (var.is_int()) { integer = var.AsInt(); } else if (var.is_double()) { if (!CastDoubleToInt64(var.AsDouble(), &integer, error_message)) return false; } else { *error_message = FormatPrintfTemplate(kErrorWrongType, kIntegerJsTypeTitle, DebugDumpVar(var).c_str()); return false; } return CastInteger(integer, type_name, result, error_message); } } // namespace bool VarAs(const pp::Var& var, int8_t* result, std::string* error_message) { return VarAsInteger(var, "int8_t", result, error_message); } bool VarAs(const pp::Var& var, uint8_t* result, std::string* error_message) { return VarAsInteger(var, "uint8_t", result, error_message); } bool VarAs(const pp::Var& var, int16_t* result, std::string* error_message) { return VarAsInteger(var, "int16_t", result, error_message); } bool VarAs(const pp::Var& var, uint16_t* result, std::string* error_message) { return VarAsInteger(var, "uint16_t", result, error_message); } bool VarAs(const pp::Var& var, int32_t* result, std::string* error_message) { return VarAsInteger(var, "int32_t", result, error_message); } bool VarAs(const pp::Var& var, uint32_t* result, std::string* error_message) { return VarAsInteger(var, "uint32_t", result, error_message); } bool VarAs(const pp::Var& var, int64_t* result, std::string* error_message) { return VarAsInteger(var, "int64_t", result, error_message); } bool VarAs(const pp::Var& var, uint64_t* result, std::string* error_message) { return VarAsInteger(var, "uint64_t", result, error_message); } bool VarAs(const pp::Var& var, long* result, std::string* error_message) { return VarAsInteger(var, "long", result, error_message); } bool VarAs(const pp::Var& var, unsigned long* result, std::string* error_message) { return VarAsInteger(var, "unsigned long", result, error_message); } bool VarAs(const pp::Var& var, float* result, std::string* error_message) { double double_value; if (!VarAs(var, &double_value, error_message)) return false; *result = static_cast<float>(double_value); return true; } bool VarAs(const pp::Var& var, double* result, std::string* error_message) { if (!var.is_number()) { *error_message = FormatPrintfTemplate(kErrorWrongType, kIntegerJsTypeTitle, DebugDumpVar(var).c_str()); return false; } *result = var.AsDouble(); return true; } bool VarAs(const pp::Var& var, bool* result, std::string* error_message) { if (!var.is_bool()) { *error_message = FormatPrintfTemplate(kErrorWrongType, kBooleanJsTypeTitle, DebugDumpVar(var).c_str()); return false; } *result = var.AsBool(); return true; } bool VarAs(const pp::Var& var, std::string* result, std::string* error_message) { if (!var.is_string()) { *error_message = FormatPrintfTemplate(kErrorWrongType, kStringJsTypeTitle, DebugDumpVar(var).c_str()); return false; } *result = var.AsString(); return true; } bool VarAs(const pp::Var& var, pp::Var* result, std::string* /*error_message*/) { *result = var; return true; } bool VarAs(const pp::Var& var, pp::VarArray* result, std::string* error_message) { if (!var.is_array()) { *error_message = FormatPrintfTemplate(kErrorWrongType, kArrayJsTypeTitle, DebugDumpVar(var).c_str()); return false; } *result = pp::VarArray(var); return true; } bool VarAs(const pp::Var& var, pp::VarArrayBuffer* result, std::string* error_message) { if (!var.is_array_buffer()) { *error_message = FormatPrintfTemplate( kErrorWrongType, kArrayBufferJsTypeTitle, DebugDumpVar(var).c_str()); return false; } *result = pp::VarArrayBuffer(var); return true; } bool VarAs(const pp::Var& var, pp::VarDictionary* result, std::string* error_message) { if (!var.is_dictionary()) { *error_message = FormatPrintfTemplate( kErrorWrongType, kDictionaryJsTypeTitle, DebugDumpVar(var).c_str()); return false; } *result = pp::VarDictionary(var); return true; } bool VarAs(const pp::Var& var, pp::Var::Null* /*result*/, std::string* error_message) { if (!var.is_null()) { *error_message = FormatPrintfTemplate(kErrorWrongType, kNullJsTypeTitle, DebugDumpVar(var).c_str()); return false; } return true; } namespace internal { std::vector<uint8_t> GetVarArrayBufferData(pp::VarArrayBuffer var) { std::vector<uint8_t> result(var.ByteLength()); if (!result.empty()) { std::memcpy(&result[0], var.Map(), result.size()); var.Unmap(); } return result; } } // namespace internal int GetVarDictSize(const pp::VarDictionary& var) { return GetVarArraySize(var.GetKeys()); } int GetVarArraySize(const pp::VarArray& var) { return static_cast<int>(var.GetLength()); } bool GetVarDictValue(const pp::VarDictionary& var, const std::string& key, pp::Var* result, std::string* error_message) { if (!var.HasKey(key)) { *error_message = FormatPrintfTemplate("The dictionary has no key \"%s\"", key.c_str()); return false; } *result = var.Get(key); return true; } pp::Var GetVarDictValue(const pp::VarDictionary& var, const std::string& key) { pp::Var result; std::string error_message; if (!GetVarDictValue(var, key, &result, &error_message)) GOOGLE_SMART_CARD_LOG_FATAL << error_message; return result; } VarDictValuesExtractor::VarDictValuesExtractor(const pp::VarDictionary& var) : var_(var) { const std::vector<std::string> keys = VarAs<std::vector<std::string>>(var_.GetKeys()); not_requested_keys_.insert(keys.begin(), keys.end()); } bool VarDictValuesExtractor::GetSuccess(std::string* error_message) const { if (failed_) { *error_message = error_message_; return false; } return true; } bool VarDictValuesExtractor::GetSuccessWithNoExtraKeysAllowed( std::string* error_message) const { if (!GetSuccess(error_message)) return false; if (!not_requested_keys_.empty()) { std::string unexpected_keys_dump; for (const std::string& key : not_requested_keys_) { if (!unexpected_keys_dump.empty()) unexpected_keys_dump += ", "; unexpected_keys_dump += '"' + key + '"'; } *error_message = FormatPrintfTemplate("The dictionary contains unexpected keys: %s", unexpected_keys_dump.c_str()); return false; } return true; } void VarDictValuesExtractor::CheckSuccess() const { std::string error_message; if (!GetSuccess(&error_message)) GOOGLE_SMART_CARD_LOG_FATAL << error_message; } void VarDictValuesExtractor::CheckSuccessWithNoExtraKeysAllowed() const { std::string error_message; if (!GetSuccessWithNoExtraKeysAllowed(&error_message)) GOOGLE_SMART_CARD_LOG_FATAL << error_message; } void VarDictValuesExtractor::AddRequestedKey(const std::string& key) { not_requested_keys_.erase(key); } void VarDictValuesExtractor::ProcessFailedExtraction( const std::string& key, const std::string& extraction_error_message) { if (failed_) { // We could concatenate all occurred errors, but storing of the first error // only should be enough. return; } error_message_ = FormatPrintfTemplate( "Failed to extract the dictionary value with key \"%s\": %s", key.c_str(), extraction_error_message.c_str()); failed_ = true; } } // namespace google_smart_card
30.181507
80
0.666969
swapnil119
add80978f49c3218f7ec8dd60422cf62bb0cd10f
51,310
cpp
C++
source/TrickHLA/Interaction.cpp
jiajlin/TrickHLA
ae704b97049579e997593ae6d8dd016010b8fa1e
[ "NASA-1.3" ]
null
null
null
source/TrickHLA/Interaction.cpp
jiajlin/TrickHLA
ae704b97049579e997593ae6d8dd016010b8fa1e
[ "NASA-1.3" ]
null
null
null
source/TrickHLA/Interaction.cpp
jiajlin/TrickHLA
ae704b97049579e997593ae6d8dd016010b8fa1e
[ "NASA-1.3" ]
null
null
null
/*! @file TrickHLA/Interaction.cpp @ingroup TrickHLA @brief This class represents an HLA Interaction that is managed by Trick. @copyright Copyright 2019 United States Government as represented by the Administrator of the National Aeronautics and Space Administration. No copyright is claimed in the United States under Title 17, U.S. Code. All Other Rights Reserved. \par<b>Responsible Organization</b> Simulation and Graphics Branch, Mail Code ER7\n Software, Robotics & Simulation Division\n NASA, Johnson Space Center\n 2101 NASA Parkway, Houston, TX 77058 @tldh @trick_link_dependency{DebugHandler.cpp} @trick_link_dependency{Federate.cpp} @trick_link_dependency{Int64Interval.cpp} @trick_link_dependency{Int64Time.cpp} @trick_link_dependency{Interaction.cpp} @trick_link_dependency{InteractionHandler.cpp} @trick_link_dependency{InteractionItem.cpp} @trick_link_dependency{Manager.cpp} @trick_link_dependency{MutexLock.cpp} @trick_link_dependency{MutexProtection.cpp} @trick_link_dependency{Parameter.cpp} @trick_link_dependency{ParameterItem.cpp} @trick_link_dependency{Types.cpp} @revs_title @revs_begin @rev_entry{Dan Dexter, L3 Titan Group, DSES, Aug 2006, --, Initial implementation.} @rev_entry{Dan Dexter, NASA ER7, TrickHLA, March 2019, --, Version 2 origin.} @rev_entry{Edwin Z. Crues, NASA ER7, TrickHLA, March 2019, --, Version 3 rewrite.} @revs_end */ // System include files. #include <cstdlib> #include <iostream> #include <sstream> // Trick include files. #include "trick/exec_proto.h" #include "trick/message_proto.h" // TrickHLA include files. #include "TrickHLA/Constants.hh" #include "TrickHLA/DebugHandler.hh" #include "TrickHLA/Federate.hh" #include "TrickHLA/Int64Interval.hh" #include "TrickHLA/Int64Time.hh" #include "TrickHLA/Interaction.hh" #include "TrickHLA/InteractionHandler.hh" #include "TrickHLA/InteractionItem.hh" #include "TrickHLA/Manager.hh" #include "TrickHLA/MutexLock.hh" #include "TrickHLA/MutexProtection.hh" #include "TrickHLA/Parameter.hh" #include "TrickHLA/ParameterItem.hh" #include "TrickHLA/StringUtilities.hh" #include "TrickHLA/Types.hh" // C++11 deprecated dynamic exception specifications for a function so we need // to silence the warnings coming from the IEEE 1516 declared functions. // This should work for both GCC and Clang. #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated" // HLA include files. #include RTI1516_HEADER #pragma GCC diagnostic pop using namespace std; using namespace RTI1516_NAMESPACE; using namespace TrickHLA; /*! * @job_class{initialization} */ Interaction::Interaction() : FOM_name( NULL ), publish( false ), subscribe( false ), preferred_order( TRANSPORT_SPECIFIED_IN_FOM ), param_count( 0 ), parameters( NULL ), handler( NULL ), mutex(), changed( false ), received_as_TSO( false ), time( 0.0 ), manager( NULL ), user_supplied_tag_size( 0 ), user_supplied_tag_capacity( 0 ), user_supplied_tag( NULL ) { return; } /*! * @job_class{shutdown} */ Interaction::~Interaction() { // Remove this interaction from the federation execution. remove(); if ( user_supplied_tag != NULL ) { if ( TMM_is_alloced( (char *)user_supplied_tag ) ) { TMM_delete_var_a( user_supplied_tag ); } user_supplied_tag = NULL; user_supplied_tag_size = 0; } // Make sure we destroy the mutex. (void)mutex.unlock(); } /*! * @job_class{initialization} */ void Interaction::initialize( Manager *trickhla_mgr ) { TRICKHLA_VALIDATE_FPU_CONTROL_WORD; if ( trickhla_mgr == NULL ) { send_hs( stderr, "Interaction::initialize():%d Unexpected NULL Trick-HLA-Manager!%c", __LINE__, THLA_NEWLINE ); exec_terminate( __FILE__, "Interaction::initialize() Unexpected NULL Trick-HLA-Manager!" ); return; } this->manager = trickhla_mgr; // Make sure we have a valid object FOM name. if ( ( FOM_name == NULL ) || ( *FOM_name == '\0' ) ) { ostringstream errmsg; errmsg << "Interaction::initialize():" << __LINE__ << " Missing Interaction FOM Name." << " Please check your input or modified-data files to make sure the" << " Interaction FOM name is correctly specified." << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); exec_terminate( __FILE__, (char *)errmsg.str().c_str() ); } // TODO: Get the preferred order by parsing the FOM. // // Do a quick bounds check on the 'preferred_order' value. if ( ( preferred_order < TRANSPORT_FIRST_VALUE ) || ( preferred_order > TRANSPORT_LAST_VALUE ) ) { ostringstream errmsg; errmsg << "Interaction::initialize():" << __LINE__ << " For Interaction '" << FOM_name << "', the 'preferred_order' is not valid and must be one" << " of TRANSPORT_SPECIFIED_IN_FOM, TRANSPORT_TIMESTAMP_ORDER or" << " TRANSPORT_RECEIVE_ORDER. Please check your input or modified-data" << " files to make sure the 'preferred_order' is correctly specified." << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); exec_terminate( __FILE__, (char *)errmsg.str().c_str() ); } // If we have an parameter count but no parameters then let the user know. if ( ( param_count > 0 ) && ( parameters == NULL ) ) { ostringstream errmsg; errmsg << "Interaction::initialize():" << __LINE__ << " For Interaction '" << FOM_name << "', the 'param_count' is " << param_count << " but no 'parameters' are specified. Please check your input or" << " modified-data files to make sure the Interaction Parameters are" << " correctly specified." << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); exec_terminate( __FILE__, (char *)errmsg.str().c_str() ); } // If we have parameters but the parameter-count is invalid then let // the user know. if ( ( param_count <= 0 ) && ( parameters != NULL ) ) { ostringstream errmsg; errmsg << "Interaction::initialize():" << __LINE__ << " For Interaction '" << FOM_name << "', the 'param_count' is " << param_count << " but 'parameters' have been specified. Please check your input" << " or modified-data files to make sure the Interaction Parameters" << " are correctly specified." << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); exec_terminate( __FILE__, (char *)errmsg.str().c_str() ); } // Reset the TrickHLA Parameters count if it is negative or if there // are no attributes. if ( ( param_count < 0 ) || ( parameters == NULL ) ) { param_count = 0; } // We must have an interaction handler specified, otherwise we can not // process the interaction. if ( handler == NULL ) { ostringstream errmsg; errmsg << "Interaction::initialize():" << __LINE__ << " An Interaction-Handler for" << " 'handler' was not specified for the '" << FOM_name << "'" << " interaction. Please check your input or modified-data files to" << " make sure an Interaction-Handler is correctly specified." << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); exec_terminate( __FILE__, (char *)errmsg.str().c_str() ); } // Initialize the Interaction-Handler. handler->initialize_callback( this ); TRICKHLA_VALIDATE_FPU_CONTROL_WORD; } void Interaction::set_user_supplied_tag( unsigned char *tag, size_t tag_size ) { if ( tag_size > user_supplied_tag_capacity ) { user_supplied_tag_capacity = tag_size; if ( user_supplied_tag == NULL ) { user_supplied_tag = (unsigned char *)TMM_declare_var_1d( "char", (int)user_supplied_tag_capacity ); } else { user_supplied_tag = (unsigned char *)TMM_resize_array_1d_a( user_supplied_tag, (int)user_supplied_tag_capacity ); } } user_supplied_tag_size = tag_size; if ( tag != NULL ) { memcpy( user_supplied_tag, tag, user_supplied_tag_size ); } else { memset( user_supplied_tag, 0, user_supplied_tag_size ); } } /*! * @details Called from the virtual destructor. * @job_class{shutdown} */ void Interaction::remove() // RETURN: -- None. { // Only remove the Interaction if the manager has not been shutdown. if ( is_shutdown_called() ) { // Get the RTI-Ambassador and check for NULL. RTIambassador *rti_amb = get_RTI_ambassador(); if ( rti_amb != NULL ) { if ( is_publish() ) { // Macro to save the FPU Control Word register value. TRICKHLA_SAVE_FPU_CONTROL_WORD; // Un-publish the Interaction. try { if ( DebugHandler::show( DEBUG_LEVEL_2_TRACE, DEBUG_SOURCE_INTERACTION ) ) { send_hs( stdout, "Interaction::remove():%d Unpublish Interaction '%s'.%c", __LINE__, get_FOM_name(), THLA_NEWLINE ); } rti_amb->unpublishInteractionClass( get_class_handle() ); } catch ( RTI1516_EXCEPTION &e ) { string rti_err_msg; StringUtilities::to_string( rti_err_msg, e.what() ); send_hs( stderr, "Interaction::remove():%d Unpublish Interaction '%s' exception '%s'%c", __LINE__, get_FOM_name(), rti_err_msg.c_str(), THLA_NEWLINE ); } // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; } // Un-subscribe from the Interaction unsubscribe_from_interaction(); } } } void Interaction::setup_preferred_order_with_RTI() { // Just return if the user wants to use the default preferred order // specified in the FOM. Return if the interaction is not published since // we can only change the preferred order for publish interactions. if ( ( preferred_order == TRANSPORT_SPECIFIED_IN_FOM ) || !is_publish() ) { return; } RTIambassador *rti_amb = get_RTI_ambassador(); if ( rti_amb == NULL ) { send_hs( stderr, "Interaction::setup_preferred_order_with_RTI():%d Unexpected NULL RTIambassador.%c", __LINE__, THLA_NEWLINE ); return; } if ( DebugHandler::show( DEBUG_LEVEL_2_TRACE, DEBUG_SOURCE_INTERACTION ) ) { send_hs( stdout, "Interaction::setup_preferred_order_with_RTI():%d \ Published Interaction '%s' Preferred-Order:%s%c", __LINE__, get_FOM_name(), ( preferred_order == TRANSPORT_TIMESTAMP_ORDER ? "TIMESTAMP" : "RECEIVE" ), THLA_NEWLINE ); } // Macro to save the FPU Control Word register value. TRICKHLA_SAVE_FPU_CONTROL_WORD; // Change the preferred order. try { switch ( preferred_order ) { case TRANSPORT_RECEIVE_ORDER: { rti_amb->changeInteractionOrderType( this->class_handle, RTI1516_NAMESPACE::RECEIVE ); break; } case TRANSPORT_TIMESTAMP_ORDER: default: { rti_amb->changeInteractionOrderType( this->class_handle, RTI1516_NAMESPACE::TIMESTAMP ); break; } } } catch ( RTI1516_NAMESPACE::InteractionClassNotPublished &e ) { // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; ostringstream errmsg; errmsg << "Interaction::setup_preferred_order_with_RTI():" << __LINE__ << " EXCEPTION: InteractionClassNotPublished for Interaction '" << get_FOM_name() << "'" << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); exec_terminate( __FILE__, (char *)errmsg.str().c_str() ); } catch ( RTI1516_NAMESPACE::FederateNotExecutionMember &e ) { // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; ostringstream errmsg; errmsg << "Interaction::setup_preferred_order_with_RTI():" << __LINE__ << " EXCEPTION: FederateNotExecutionMember for Interaction '" << get_FOM_name() << "'" << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); exec_terminate( __FILE__, (char *)errmsg.str().c_str() ); } catch ( RTI1516_NAMESPACE::InteractionClassNotDefined &e ) { // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; ostringstream errmsg; errmsg << "Interaction::setup_preferred_order_with_RTI():" << __LINE__ << " EXCEPTION: InteractionClassNotDefined for Interaction '" << get_FOM_name() << "'" << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); exec_terminate( __FILE__, (char *)errmsg.str().c_str() ); } catch ( RTI1516_NAMESPACE::RestoreInProgress &e ) { // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; ostringstream errmsg; errmsg << "Interaction::setup_preferred_order_with_RTI():" << __LINE__ << " EXCEPTION: RestoreInProgress for Interaction '" << get_FOM_name() << "'" << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); exec_terminate( __FILE__, (char *)errmsg.str().c_str() ); } catch ( RTI1516_NAMESPACE::RTIinternalError &e ) { // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; ostringstream errmsg; errmsg << "Interaction::setup_preferred_order_with_RTI():" << __LINE__ << " EXCEPTION: RTIinternalError for Interaction '" << get_FOM_name() << "'" << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); exec_terminate( __FILE__, (char *)errmsg.str().c_str() ); } catch ( RTI1516_NAMESPACE::SaveInProgress &e ) { // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; ostringstream errmsg; errmsg << "Interaction::setup_preferred_order_with_RTI():" << __LINE__ << " EXCEPTION: SaveInProgress for Interaction '" << get_FOM_name() << "'" << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); exec_terminate( __FILE__, (char *)errmsg.str().c_str() ); } catch ( RTI1516_NAMESPACE::NotConnected &e ) { // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; ostringstream errmsg; errmsg << "Interaction::setup_preferred_order_with_RTI():" << __LINE__ << " EXCEPTION: NotConnected for Interaction '" << get_FOM_name() << "'" << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); exec_terminate( __FILE__, (char *)errmsg.str().c_str() ); } catch ( RTI1516_EXCEPTION &e ) { // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; string rti_err_msg; StringUtilities::to_string( rti_err_msg, e.what() ); ostringstream errmsg; errmsg << "Interaction::setup_preferred_order_with_RTI():" << __LINE__ << " RTI1516_EXCEPTION for Interaction '" << get_FOM_name() << "' with error '" << rti_err_msg << "'" << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); exec_terminate( __FILE__, (char *)errmsg.str().c_str() ); } // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; } void Interaction::publish_interaction() { // The RTI must be ready and the flag must be set to publish. if ( !is_publish() ) { return; } RTIambassador *rti_amb = get_RTI_ambassador(); if ( rti_amb == NULL ) { send_hs( stderr, "Interaction::publish_interaction():%d Unexpected NULL RTIambassador.%c", __LINE__, THLA_NEWLINE ); return; } if ( DebugHandler::show( DEBUG_LEVEL_2_TRACE, DEBUG_SOURCE_INTERACTION ) ) { send_hs( stdout, "Interaction::publish_interaction():%d Interaction '%s'.%c", __LINE__, get_FOM_name(), THLA_NEWLINE ); } // Macro to save the FPU Control Word register value. TRICKHLA_SAVE_FPU_CONTROL_WORD; // Publish the Interaction try { rti_amb->publishInteractionClass( this->class_handle ); } catch ( RTI1516_NAMESPACE::FederateNotExecutionMember &e ) { // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; ostringstream errmsg; errmsg << "Interaction::publish_interaction():" << __LINE__ << " EXCEPTION: FederateNotExecutionMember for Interaction '" << get_FOM_name() << "'" << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); exec_terminate( __FILE__, (char *)errmsg.str().c_str() ); } catch ( RTI1516_NAMESPACE::InteractionClassNotDefined &e ) { // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; ostringstream errmsg; errmsg << "Interaction::publish_interaction():" << __LINE__ << " EXCEPTION: InteractionClassNotDefined for Interaction '" << get_FOM_name() << "'" << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); exec_terminate( __FILE__, (char *)errmsg.str().c_str() ); } catch ( RTI1516_NAMESPACE::RestoreInProgress &e ) { // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; ostringstream errmsg; errmsg << "Interaction::publish_interaction():" << __LINE__ << " EXCEPTION: RestoreInProgress for Interaction '" << get_FOM_name() << "'" << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); exec_terminate( __FILE__, (char *)errmsg.str().c_str() ); } catch ( RTI1516_NAMESPACE::RTIinternalError &e ) { // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; ostringstream errmsg; errmsg << "Interaction::publish_interaction():" << __LINE__ << " EXCEPTION: RTIinternalError for Interaction '" << get_FOM_name() << "'" << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); exec_terminate( __FILE__, (char *)errmsg.str().c_str() ); } catch ( RTI1516_NAMESPACE::SaveInProgress &e ) { // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; ostringstream errmsg; errmsg << "Interaction::publish_interaction():" << __LINE__ << " EXCEPTION: SaveInProgress for Interaction '" << get_FOM_name() << "'" << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); exec_terminate( __FILE__, (char *)errmsg.str().c_str() ); } catch ( RTI1516_NAMESPACE::NotConnected &e ) { // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; ostringstream errmsg; errmsg << "Interaction::publish_interaction():" << __LINE__ << " EXCEPTION: NotConnected for Interaction '" << get_FOM_name() << "'" << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); exec_terminate( __FILE__, (char *)errmsg.str().c_str() ); } catch ( RTI1516_EXCEPTION &e ) { // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; string rti_err_msg; StringUtilities::to_string( rti_err_msg, e.what() ); ostringstream errmsg; errmsg << "Interaction::publish_interaction():" << __LINE__ << " RTI1516_EXCEPTION for Interaction '" << get_FOM_name() << "' with error '" << rti_err_msg << "'" << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); exec_terminate( __FILE__, (char *)errmsg.str().c_str() ); } // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; } void Interaction::unpublish_interaction() { RTIambassador *rti_amb = get_RTI_ambassador(); if ( rti_amb == NULL ) { send_hs( stderr, "Interaction::unpublish_interaction():%d Unexpected NULL RTIambassador.%c", __LINE__, THLA_NEWLINE ); return; } // Subscribe to the interaction. if ( is_publish() ) { if ( DebugHandler::show( DEBUG_LEVEL_2_TRACE, DEBUG_SOURCE_INTERACTION ) ) { send_hs( stdout, "Interaction::unpublish_interaction():%d Interaction '%s'%c", __LINE__, get_FOM_name(), THLA_NEWLINE ); } // Macro to save the FPU Control Word register value. TRICKHLA_SAVE_FPU_CONTROL_WORD; try { rti_amb->unpublishInteractionClass( this->class_handle ); } catch ( RTI1516_NAMESPACE::InteractionClassNotDefined &e ) { // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; ostringstream errmsg; errmsg << "Interaction::unpublish_interaction():" << __LINE__ << " EXCEPTION: InteractionClassNotDefined for Interaction '" << get_FOM_name() << "'" << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); exec_terminate( __FILE__, (char *)errmsg.str().c_str() ); } catch ( RTI1516_NAMESPACE::FederateNotExecutionMember &e ) { // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; ostringstream errmsg; errmsg << "Interaction::unpublish_interaction():" << __LINE__ << " EXCEPTION: FederateNotExecutionMember for Interaction '" << get_FOM_name() << "'" << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); exec_terminate( __FILE__, (char *)errmsg.str().c_str() ); } catch ( RTI1516_NAMESPACE::SaveInProgress &e ) { // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; ostringstream errmsg; errmsg << "Interaction::unpublish_interaction():" << __LINE__ << " EXCEPTION: SaveInProgress for Interaction '" << get_FOM_name() << "'" << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); exec_terminate( __FILE__, (char *)errmsg.str().c_str() ); } catch ( RTI1516_NAMESPACE::RestoreInProgress &e ) { // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; ostringstream errmsg; errmsg << "Interaction::unpublish_interaction():" << __LINE__ << " EXCEPTION: RestoreInProgress for Interaction '" << get_FOM_name() << "'" << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); exec_terminate( __FILE__, (char *)errmsg.str().c_str() ); } catch ( RTI1516_NAMESPACE::NotConnected &e ) { // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; ostringstream errmsg; errmsg << "Interaction::unpublish_interaction():" << __LINE__ << " EXCEPTION: NotConnected for Interaction '" << get_FOM_name() << "'" << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); exec_terminate( __FILE__, (char *)errmsg.str().c_str() ); } catch ( RTI1516_NAMESPACE::RTIinternalError &e ) { // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; ostringstream errmsg; errmsg << "Interaction::unpublish_interaction():" << __LINE__ << " EXCEPTION: RTIinternalError for Interaction '" << get_FOM_name() << "'" << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); exec_terminate( __FILE__, (char *)errmsg.str().c_str() ); } catch ( RTI1516_EXCEPTION &e ) { // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; string rti_err_msg; StringUtilities::to_string( rti_err_msg, e.what() ); ostringstream errmsg; errmsg << "Interaction::unpublish_interaction():" << __LINE__ << " RTI1516_EXCEPTION for Interaction '" << get_FOM_name() << "' with error '" << rti_err_msg << "'" << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); exec_terminate( __FILE__, (char *)errmsg.str().c_str() ); } // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; } } void Interaction::subscribe_to_interaction() { // Get the RTI-Ambassador. RTIambassador *rti_amb = get_RTI_ambassador(); if ( rti_amb == NULL ) { send_hs( stderr, "Interaction::subscribe_to_interaction():%d Unexpected NULL RTIambassador.%c", __LINE__, THLA_NEWLINE ); return; } // Subscribe to the interaction. if ( is_subscribe() ) { if ( DebugHandler::show( DEBUG_LEVEL_2_TRACE, DEBUG_SOURCE_INTERACTION ) ) { send_hs( stdout, "Interaction::subscribe_to_interaction():%d Interaction '%s'%c", __LINE__, get_FOM_name(), THLA_NEWLINE ); } // Macro to save the FPU Control Word register value. TRICKHLA_SAVE_FPU_CONTROL_WORD; try { rti_amb->subscribeInteractionClass( this->class_handle, true ); } catch ( RTI1516_NAMESPACE::FederateNotExecutionMember &e ) { // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; ostringstream errmsg; errmsg << "Interaction::subscribe_to_interaction():" << __LINE__ << " EXCEPTION: FederateNotExecutionMember for Interaction '" << get_FOM_name() << "'" << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); exec_terminate( __FILE__, (char *)errmsg.str().c_str() ); } catch ( RTI1516_NAMESPACE::FederateServiceInvocationsAreBeingReportedViaMOM &e ) { // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; ostringstream errmsg; errmsg << "Interaction::subscribe_to_interaction():" << __LINE__ << " EXCEPTION: FederateServiceInvocationsAreBeingReportedViaMOM for Interaction '" << get_FOM_name() << "'" << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); exec_terminate( __FILE__, (char *)errmsg.str().c_str() ); } catch ( RTI1516_NAMESPACE::InteractionClassNotDefined &e ) { // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; ostringstream errmsg; errmsg << "Interaction::subscribe_to_interaction():" << __LINE__ << " EXCEPTION: InteractionClassNotDefined for Interaction '" << get_FOM_name() << "'" << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); exec_terminate( __FILE__, (char *)errmsg.str().c_str() ); } catch ( RTI1516_NAMESPACE::RestoreInProgress &e ) { // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; ostringstream errmsg; errmsg << "Interaction::subscribe_to_interaction():" << __LINE__ << " EXCEPTION: RestoreInProgress for Interaction '" << get_FOM_name() << "'" << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); exec_terminate( __FILE__, (char *)errmsg.str().c_str() ); } catch ( RTI1516_NAMESPACE::RTIinternalError &e ) { // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; ostringstream errmsg; errmsg << "Interaction::subscribe_to_interaction():" << __LINE__ << " EXCEPTION: RTIinternalError for Interaction '" << get_FOM_name() << "'" << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); exec_terminate( __FILE__, (char *)errmsg.str().c_str() ); } catch ( RTI1516_NAMESPACE::SaveInProgress &e ) { // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; ostringstream errmsg; errmsg << "Interaction::subscribe_to_interaction():" << __LINE__ << " EXCEPTION: SaveInProgress for Interaction '" << get_FOM_name() << "'" << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); exec_terminate( __FILE__, (char *)errmsg.str().c_str() ); } catch ( RTI1516_NAMESPACE::NotConnected &e ) { // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; ostringstream errmsg; errmsg << "Interaction::subscribe_to_interaction():" << __LINE__ << " EXCEPTION: NotConnected for Interaction '" << get_FOM_name() << "'" << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); exec_terminate( __FILE__, (char *)errmsg.str().c_str() ); } catch ( RTI1516_EXCEPTION &e ) { // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; string rti_err_msg; StringUtilities::to_string( rti_err_msg, e.what() ); ostringstream errmsg; errmsg << "Interaction::subscribe_to_interaction():" << __LINE__ << " RTI1516_EXCEPTION for Interaction '" << get_FOM_name() << "' with error '" << rti_err_msg << "'" << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); exec_terminate( __FILE__, (char *)errmsg.str().c_str() ); } // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; } } void Interaction::unsubscribe_from_interaction() { // Get the RTI-Ambassador. RTIambassador *rti_amb = get_RTI_ambassador(); if ( rti_amb == NULL ) { send_hs( stderr, "Interaction::unsubscribe_from_interaction():%d Unexpected NULL RTIambassador.%c", __LINE__, THLA_NEWLINE ); return; } // Make sure we only unsubscribe an interaction that was subscribed to. if ( is_subscribe() ) { if ( DebugHandler::show( DEBUG_LEVEL_2_TRACE, DEBUG_SOURCE_INTERACTION ) ) { send_hs( stdout, "Interaction::unsubscribe_from_interaction():%d Interaction '%s'%c", __LINE__, get_FOM_name(), THLA_NEWLINE ); } // Macro to save the FPU Control Word register value. TRICKHLA_SAVE_FPU_CONTROL_WORD; try { rti_amb->unsubscribeInteractionClass( this->class_handle ); } catch ( RTI1516_NAMESPACE::InteractionClassNotDefined &e ) { // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; ostringstream errmsg; errmsg << "Interaction::unsubscribe_from_interaction():" << __LINE__ << " EXCEPTION: InteractionClassNotDefined for Interaction '" << get_FOM_name() << "'" << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); exec_terminate( __FILE__, (char *)errmsg.str().c_str() ); } catch ( RTI1516_NAMESPACE::FederateNotExecutionMember &e ) { // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; ostringstream errmsg; errmsg << "Interaction::unsubscribe_from_interaction():" << __LINE__ << " EXCEPTION: FederateNotExecutionMember for Interaction '" << get_FOM_name() << "'" << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); exec_terminate( __FILE__, (char *)errmsg.str().c_str() ); } catch ( RTI1516_NAMESPACE::SaveInProgress &e ) { // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; ostringstream errmsg; errmsg << "Interaction::unsubscribe_from_interaction():" << __LINE__ << " EXCEPTION: SaveInProgress for Interaction '" << get_FOM_name() << "'" << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); exec_terminate( __FILE__, (char *)errmsg.str().c_str() ); } catch ( RTI1516_NAMESPACE::RestoreInProgress &e ) { // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; ostringstream errmsg; errmsg << "Interaction::unsubscribe_from_interaction():" << __LINE__ << " EXCEPTION: RestoreInProgress for Interaction '" << get_FOM_name() << "'" << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); exec_terminate( __FILE__, (char *)errmsg.str().c_str() ); } catch ( RTI1516_NAMESPACE::NotConnected &e ) { // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; ostringstream errmsg; errmsg << "Interaction::unsubscribe_from_interaction():" << __LINE__ << " EXCEPTION: NotConnected for Interaction '" << get_FOM_name() << "'" << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); exec_terminate( __FILE__, (char *)errmsg.str().c_str() ); } catch ( RTI1516_NAMESPACE::RTIinternalError &e ) { // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; ostringstream errmsg; errmsg << "Interaction::unsubscribe_from_interaction():" << __LINE__ << " EXCEPTION: RTIinternalError for Interaction '" << get_FOM_name() << "'" << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); exec_terminate( __FILE__, (char *)errmsg.str().c_str() ); } catch ( RTI1516_EXCEPTION &e ) { // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; string rti_err_msg; StringUtilities::to_string( rti_err_msg, e.what() ); ostringstream errmsg; errmsg << "Interaction::unsubscribe_from_interaction():" << __LINE__ << " RTI1516_EXCEPTION for Interaction '" << get_FOM_name() << "' with error '" << rti_err_msg << "'" << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); exec_terminate( __FILE__, (char *)errmsg.str().c_str() ); } // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; } } bool Interaction::send( RTI1516_USERDATA const &the_user_supplied_tag ) { // RTI must be ready and the flag must be set to publish. if ( !is_publish() ) { return ( false ); } // Macro to save the FPU Control Word register value. TRICKHLA_SAVE_FPU_CONTROL_WORD; // Get the Trick-Federate. Federate *trick_fed = get_federate(); // Get the RTI-Ambassador. RTIambassador *rti_amb = get_RTI_ambassador(); if ( rti_amb == NULL ) { send_hs( stderr, "Interaction::send():%d As Receive-Order: Unexpected NULL RTIambassador.%c", __LINE__, THLA_NEWLINE ); return ( false ); } ParameterHandleValueMap param_values_map; // For thread safety, lock here to avoid corrupting the parameters and use // braces to create scope for the mutex-protection to auto unlock the mutex. { // When auto_unlock_mutex goes out of scope it automatically unlocks the // mutex even if there is an exception. MutexProtection auto_unlock_mutex( &mutex ); // Add all the parameter values to the map. for ( int i = 0; i < param_count; i++ ) { param_values_map[parameters[i].get_parameter_handle()] = parameters[i].get_encoded_parameter_value(); } // Release mutex lock as auto_unlock_mutex goes out of scope } if ( DebugHandler::show( DEBUG_LEVEL_2_TRACE, DEBUG_SOURCE_INTERACTION ) ) { send_hs( stdout, "Interaction::send():%d As Receive-Order: Interaction '%s'%c", __LINE__, get_FOM_name(), THLA_NEWLINE ); } bool successfuly_sent = false; try { // RECEIVE_ORDER with no timestamp. // Do not send any interactions if federate save / restore has begun (see // IEEE-1516.1-2000 sections 4.12, 4.20) if ( trick_fed->should_publish_data() ) { // This call returns an event retraction handle but we // don't support event retraction so no need to store it. (void)rti_amb->sendInteraction( this->class_handle, param_values_map, the_user_supplied_tag ); successfuly_sent = true; } } catch ( RTI1516_EXCEPTION &e ) { string rti_err_msg; StringUtilities::to_string( rti_err_msg, e.what() ); send_hs( stderr, "Interaction::send():%d As Receive-Order: Interaction '%s' with exception '%s'%c", __LINE__, get_FOM_name(), rti_err_msg.c_str(), THLA_NEWLINE ); } // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; // Free the memory used in the parameter values map. param_values_map.clear(); return ( successfuly_sent ); } bool Interaction::send( double send_HLA_time, RTI1516_USERDATA const &the_user_supplied_tag ) { // RTI must be ready and the flag must be set to publish. if ( !is_publish() ) { return ( false ); } // Macro to save the FPU Control Word register value. TRICKHLA_SAVE_FPU_CONTROL_WORD; RTIambassador *rti_amb = get_RTI_ambassador(); if ( rti_amb == NULL ) { send_hs( stderr, "Interaction::send():%d Unexpected NULL RTIambassador.%c", __LINE__, THLA_NEWLINE ); return ( false ); } ParameterHandleValueMap param_values_map; // For thread safety, lock here to avoid corrupting the parameters and use // braces to create scope for the mutex-protection to auto unlock the mutex. { // When auto_unlock_mutex goes out of scope it automatically unlocks the // mutex even if there is an exception. MutexProtection auto_unlock_mutex( &mutex ); // Add all the parameter values to the map. for ( int i = 0; i < param_count; i++ ) { if ( DebugHandler::show( DEBUG_LEVEL_7_TRACE, DEBUG_SOURCE_INTERACTION ) ) { send_hs( stdout, "Interaction::send():%d Adding '%s' to parameter map.%c", __LINE__, parameters[i].get_FOM_name(), THLA_NEWLINE ); } param_values_map[parameters[i].get_parameter_handle()] = parameters[i].get_encoded_parameter_value(); } // auto_unlock_mutex unlocks the mutex here as it goes out of scope. } // Update the timestamp. time.set( send_HLA_time ); // Get the Trick-Federate. Federate *trick_fed = get_federate(); // Determine if the interaction should be sent with a timestamp. // See IEEE 1516.1-2010 Section 6.12. bool send_with_timestamp = trick_fed->in_time_regulating_state() && ( preferred_order != TRANSPORT_RECEIVE_ORDER ); bool successfuly_sent = false; try { // Do not send any interactions if federate save or restore has begun (see // IEEE-1516.1-2000 sections 4.12, 4.20) if ( trick_fed->should_publish_data() ) { // The message will only be sent as TSO if our Federate is in the HLA Time // Regulating state and the interaction prefers timestamp order. // See IEEE-1516.1-2000, Sections 6.6 and 8.1.1. if ( send_with_timestamp ) { if ( DebugHandler::show( DEBUG_LEVEL_2_TRACE, DEBUG_SOURCE_INTERACTION ) ) { send_hs( stdout, "Interaction::send():%d As Timestamp-Order: Interaction '%s' sent for time %lf seconds.%c", __LINE__, get_FOM_name(), time.get_time_in_seconds(), THLA_NEWLINE ); } // This call returns an event retraction handle but we // don't support event retraction so no need to store it. // Send in Timestamp Order. (void)rti_amb->sendInteraction( this->class_handle, param_values_map, the_user_supplied_tag, time.get() ); successfuly_sent = true; } else { if ( DebugHandler::show( DEBUG_LEVEL_2_TRACE, DEBUG_SOURCE_INTERACTION ) ) { send_hs( stdout, "Interaction::send():%d As Receive-Order: \ Interaction '%s' is time-regulating:%s, preferred-order:%s.%c", __LINE__, get_FOM_name(), ( trick_fed->in_time_regulating_state() ? "Yes" : "No" ), ( ( preferred_order == TRANSPORT_RECEIVE_ORDER ) ? "receive" : "timestamp" ), THLA_NEWLINE ); } // Send in Receive Order (i.e. with no timestamp). (void)rti_amb->sendInteraction( this->class_handle, param_values_map, the_user_supplied_tag ); successfuly_sent = true; } } } catch ( RTI1516_NAMESPACE::InvalidLogicalTime &e ) { // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; string rti_err_msg; StringUtilities::to_string( rti_err_msg, e.what() ); ostringstream errmsg; errmsg << "Interaction::send():" << __LINE__ << " As " << ( send_with_timestamp ? "Timestamp Order" : "Receive Order" ) << ", InvalidLogicalTime exception for " << get_FOM_name() << " time=" << time.get_time_in_seconds() << " (" << time.get_time_in_micros() << " microseconds)" << " error message:'" << rti_err_msg.c_str() << "'" << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); } catch ( RTI1516_EXCEPTION &e ) { string rti_err_msg; StringUtilities::to_string( rti_err_msg, e.what() ); ostringstream errmsg; errmsg << "Interaction::send():" << __LINE__ << " As " << ( send_with_timestamp ? "Timestamp Order" : "Receive Order" ) << ", Interaction '" << get_FOM_name() << "' with exception '" << rti_err_msg.c_str() << "'" << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); } // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; // Free the memory used in the parameter values map. param_values_map.clear(); return ( successfuly_sent ); } void Interaction::process_interaction() { // The Interaction data must have changed and the RTI must be ready. if ( !is_changed() ) { return; } // For thread safety, lock here to avoid corrupting the parameters and use // braces to create scope for the mutex-protection to auto unlock the mutex. { // When auto_unlock_mutex goes out of scope it automatically unlocks the // mutex even if there is an exception. MutexProtection auto_unlock_mutex( &mutex ); // Check the change flag again now that we have the lock on the mutex. if ( !is_changed() ) { // cppcheck-suppress [identicalConditionAfterEarlyExit] return; } if ( DebugHandler::show( DEBUG_LEVEL_5_TRACE, DEBUG_SOURCE_INTERACTION ) ) { string handle_str; StringUtilities::to_string( handle_str, class_handle ); if ( received_as_TSO ) { send_hs( stdout, "Interaction::process_interaction():%d ID:%s, FOM_name:'%s', HLA time:%G, Timestamp-Order%c", __LINE__, handle_str.c_str(), get_FOM_name(), time.get_time_in_seconds(), THLA_NEWLINE ); } else { send_hs( stdout, "Interaction::process_interaction():%d ID:%s, FOM_name:'%s', Receive-Order%c", __LINE__, handle_str.c_str(), get_FOM_name(), THLA_NEWLINE ); } } // Unpack all the parameter data. for ( int i = 0; i < param_count; i++ ) { parameters[i].unpack_parameter_buffer(); } mark_unchanged(); // Unlock the mutex as the auto_unlock_mutex goes out of scope. } // Call the users interaction handler (callback) so that they can // continue processing the interaction. if ( handler != NULL ) { if ( user_supplied_tag_size > 0 ) { handler->receive_interaction( RTI1516_USERDATA( user_supplied_tag, user_supplied_tag_size ) ); } else { handler->receive_interaction( RTI1516_USERDATA( 0, 0 ) ); } } } void Interaction::extract_data( InteractionItem *interaction_item ) { // Must be set to subscribe to the interaction and the interaction item // is not null, otherwise just return. if ( !is_subscribe() || ( interaction_item == NULL ) ) { return; } if ( DebugHandler::show( DEBUG_LEVEL_7_TRACE, DEBUG_SOURCE_INTERACTION ) ) { string handle_str; StringUtilities::to_string( handle_str, class_handle ); send_hs( stdout, "Interaction::extract_data():%d ID:%s, FOM_name:'%s'%c", __LINE__, handle_str.c_str(), get_FOM_name(), THLA_NEWLINE ); } if ( interaction_item->is_timestamp_order() ) { // Update the timestamp. time.set( interaction_item->time ); // Received in Timestamp Order (TSO). received_as_TSO = true; } else { // Receive Order (RO), not Timestamp Order (TSO). received_as_TSO = false; } // For thread safety, lock here to avoid corrupting the parameters. // When auto_unlock_mutex goes out of scope it automatically unlocks the // mutex even if there is an exception. MutexProtection auto_unlock_mutex( &mutex ); // Extract the user supplied tag. if ( interaction_item->user_supplied_tag_size > 0 ) { set_user_supplied_tag( interaction_item->user_supplied_tag, interaction_item->user_supplied_tag_size ); mark_changed(); } else { set_user_supplied_tag( (unsigned char *)NULL, 0 ); } // Process all the parameter-items in the queue. while ( !interaction_item->parameter_queue.empty() ) { ParameterItem *param_item = static_cast< ParameterItem * >( interaction_item->parameter_queue.front() ); // Determine if we have a valid parameter-item. if ( ( param_item != NULL ) && ( param_item->index >= 0 ) && ( param_item->index < param_count ) ) { if ( DebugHandler::show( DEBUG_LEVEL_7_TRACE, DEBUG_SOURCE_INTERACTION ) ) { send_hs( stdout, "Interaction::extract_data():%d Decoding '%s' from parameter map.%c", __LINE__, parameters[param_item->index].get_FOM_name(), THLA_NEWLINE ); } // Extract the parameter data for the given parameter-item. parameters[param_item->index].extract_data( param_item->size, param_item->data ); // Mark the interaction as changed. mark_changed(); } // Now that we extracted the data from the parameter-item remove it // from the queue. interaction_item->parameter_queue.pop(); } // Unlock the mutex as auto_unlock_mutex goes out of scope. } void Interaction::mark_unchanged() { this->changed = false; // Clear the change flag for each of the attributes as well. for ( int i = 0; i < param_count; i++ ) { parameters[i].mark_unchanged(); } } /*! * @details If the manager does not exist, -1.0 seconds is assigned to the returned object. */ Int64Interval Interaction::get_fed_lookahead() const { Int64Interval i; if ( manager != NULL ) { i = manager->get_fed_lookahead(); } else { i = Int64Interval( -1.0 ); } return i; } /*! * @details If the manager does not exist, MAX_LOGICAL_TIME_SECONDS is assigned * to the returned object. */ Int64Time Interaction::get_granted_fed_time() const { Int64Time t; if ( manager != NULL ) { t = manager->get_granted_fed_time(); } else { t = Int64Time( MAX_LOGICAL_TIME_SECONDS ); } return t; } Federate *Interaction::get_federate() { return ( ( this->manager != NULL ) ? this->manager->get_federate() : NULL ); } RTIambassador *Interaction::get_RTI_ambassador() { return ( ( this->manager != NULL ) ? this->manager->get_RTI_ambassador() : static_cast< RTI1516_NAMESPACE::RTIambassador * >( NULL ) ); } bool Interaction::is_shutdown_called() const { return ( ( this->manager != NULL ) ? this->manager->is_shutdown_called() : false ); }
40.982428
123
0.638823
jiajlin
addc2b8b55dc4dcf0b78935062600f696c73c88e
10,750
cpp
C++
Src/GUI/FrTabControl.cpp
VladGordienko28/FluorineEngine-I
31114c41884d41ec60d04dba7965bc83be47d229
[ "MIT" ]
null
null
null
Src/GUI/FrTabControl.cpp
VladGordienko28/FluorineEngine-I
31114c41884d41ec60d04dba7965bc83be47d229
[ "MIT" ]
null
null
null
Src/GUI/FrTabControl.cpp
VladGordienko28/FluorineEngine-I
31114c41884d41ec60d04dba7965bc83be47d229
[ "MIT" ]
null
null
null
/*============================================================================= FrTabControl.cpp: Tab control widget. Copyright Jul.2016 Vlad Gordienko. =============================================================================*/ #include "GUI.h" /*----------------------------------------------------------------------------- WTabPage implementation. -----------------------------------------------------------------------------*/ // Whether fade tab, if it not in focus. #define FADE_TAB 0 // // Tab page constructor. // WTabPage::WTabPage( WContainer* InOwner, WWindow* InRoot ) : WContainer( InOwner, InRoot ), Color( COLOR_SteelBlue ), TabWidth( 70 ), TabControl( nullptr ) { Align = AL_Client; Padding = TArea( 0, 0, 0, 0 ); } // // Tab page repaint. // void WTabPage::OnPaint( CGUIRenderBase* Render ) { WContainer::OnPaint( Render ); #if 0 // Debug draw. Render->DrawRegion ( ClientToWindow( TPoint( 0, 0 ) ), Size, Color * COLOR_CornflowerBlue, Color * COLOR_CornflowerBlue, BPAT_Diagonal ); #endif } // // Close the tab page. // void WTabPage::Close( Bool bForce ) { assert(TabControl != nullptr); TabControl->CloseTabPage( TabControl->Pages.FindItem(this), bForce ); } /*----------------------------------------------------------------------------- WTabControl implementation. -----------------------------------------------------------------------------*/ // // Tabs control constructor. // WTabControl::WTabControl( WContainer* InOwner, WWindow* InRoot ) : WContainer( InOwner, InRoot ), Pages(), iActive( -1 ), iHighlight( -1 ), iCross( -1 ), DragPage( nullptr ), bWasDrag( false ), bOverflow( false ) { // Grab some place for header. Padding = TArea( 21, 0, 0, 0 ); Align = AL_Client; // Overflow popup menu. Popup = new WPopupMenu( this, InRoot ); } // // Draw a tab control. // void WTabControl::OnPaint( CGUIRenderBase* Render ) { // Call parent. WContainer::OnPaint( Render ); // Precompute. TPoint Base = ClientToWindow(TPoint::Zero); Integer TextY = Base.Y + (19-Root->Font1->Height) / 2; Integer XWalk = Base.X; // Draw a master bar. Render->DrawRegion ( Base, TSize( Size.Width, 20 ), GUI_COLOR_PANEL, /*GUI_COLOR_PANEL_BORDER*/GUI_COLOR_PANEL, BPAT_Solid ); // Draw headers. TColor ActiveColor; Integer iPage; for( iPage=0; iPage<Pages.Num(); iPage++ ) { WTabPage* Page = Pages[iPage]; // Test, maybe list overflow. if( XWalk+Page->TabWidth >= Base.X+Size.Width-15 ) break; // Special highlight required? if( iPage == iActive || iPage == iHighlight ) { TColor DrawColor = iPage == iActive ? Page->Color : TColor( 0x1d, 0x1d, 0x1d, 0xff ) + Page->Color; TColor DarkColor = DrawColor * TColor( 0xdd, 0xdd, 0xdd, 0xff ); // Fade color, if not in focus. if( iPage == iActive ) { #if FADE_TAB if( !IsChildFocused() ) DrawColor = TColor( 0x50, 0x50, 0x50, 0xff )+DrawColor*0.35f; #endif ActiveColor = DrawColor; } Render->DrawRegion ( TPoint( XWalk, Base.Y ), TSize( Page->TabWidth, 19 ), DrawColor, DrawColor, BPAT_Solid ); // Highlight selected cross. if( iCross == iPage ) Render->DrawRegion ( TPoint( XWalk+Page->TabWidth - 21, Base.Y + 3 ), TSize( 13, 13 ), DarkColor, DarkColor, BPAT_Solid ); // Draw cross. Render->DrawPicture ( TPoint( XWalk+Page->TabWidth - 20, Base.Y + 4 ), TSize( 11, 11 ), TPoint( 0, 11 ), TSize( 11, 11 ), Root->Icons ); } // Draw tab title. Render->DrawText ( TPoint( XWalk + 5, TextY ), Page->Caption, GUI_COLOR_TEXT, //COLOR_White, Root->Font1 ); // To next. XWalk+= Page->TabWidth; } // Draw a little marker if list overflow. if( bOverflow = iPage < Pages.Num() ) { TPoint Cursor = Root->MousePos; TPoint Start = TPoint( Base.X+Size.Width-14, Base.Y+3 ); if( Cursor.X>=Start.X && Cursor.Y>=Start.Y && Cursor.X<=Start.X+14 && Cursor.Y<=Start.Y+14 ) Render->DrawRegion ( Start, TSize( 14, 14 ), GUI_COLOR_BUTTON_HIGHLIGHT, GUI_COLOR_BUTTON_HIGHLIGHT, BPAT_Solid ); Render->DrawPicture ( TPoint( Base.X+Size.Width-10, Base.Y+9 ), TSize( 7, 4 ), TPoint( 0, 32 ), TSize( 7, 4 ), Root->Icons ); } // Draw a tiny color bar according to active page. if( iActive != -1 ) { WTabPage* Active = Pages[iActive]; Render->DrawRegion ( TPoint( Base.X, Base.Y + 19 ), TSize( Size.Width, 2 ), ActiveColor, ActiveColor, BPAT_Solid ); } } // // Return the active page, if // no page active return nullptr. // WTabPage* WTabControl::GetActivePage() { return iActive!=-1 && iActive<Pages.Num() ? Pages[iActive] : nullptr; } // // Add a new tab and activate it. // Integer WTabControl::AddTabPage( WTabPage* Page ) { Integer iNew = Pages.Push(Page); Page->TabControl = this; ActivateTabPage( iNew ); return iNew; } // // Close tab by its index. // void WTabControl::CloseTabPage( Integer iPage, Bool bForce ) { assert(iPage>=0 && iPage<Pages.Num()); WTabPage* P = Pages[iPage]; // Is tab prepared for DIE? if( bForce || P->OnQueryClose() ) { Pages.RemoveShift(iPage); if( Pages.Num() ) { // Open new item or just close. if( iActive == iPage ) { // Open new one. ActivateTabPage( Pages.Num()-1 ); iHighlight = -1; } else { // Save selection. iActive = iActive > iPage ? iActive-1 : iActive; } } else { // Nothing to open, all tabs are closed. iHighlight = iActive = -1; } // Destroy widget. delete P; } } // // Mouse click on tabs bar. // void WTabControl::OnMouseUp( EMouseButton Button, Integer X, Integer Y ) { WContainer::OnMouseUp( Button, X, Y ); iCross = XYToCross( X, Y ); // Close tab if cross pressed. if( !bWasDrag && Button == MB_Left && iCross != -1 ) { CloseTabPage(iCross); } // Close tab via middle button. if( Button == MB_Middle ) { Integer iPage = XToIndex(X); if( iPage != -1 ) CloseTabPage(iPage); } // No more drag. DragPage = nullptr; bWasDrag = false; } // // When mouse hover tabs bar. // void WTabControl::OnMouseMove( EMouseButton Button, Integer X, Integer Y ) { WContainer::OnMouseMove( Button, X, Y ); if( !DragPage ) { // No drag, just highlight. iHighlight = XToIndex( X ); iCross = XYToCross( X, Y ); } else { // Process tab drag. Integer XWalk = 0; for( Integer i=0; i<Pages.Num(); i++ ) if( Pages[i] != DragPage ) XWalk += Pages[i]->TabWidth; else break; while( X < XWalk ) { Integer iDrag = Pages.FindItem( DragPage ); if( iDrag <= 0 ) break; XWalk -= Pages[iDrag-1]->TabWidth; Pages.Swap( iDrag, iDrag-1 ); } while( X > XWalk+DragPage->TabWidth ) { Integer iDrag = Pages.FindItem( DragPage ); if( iDrag >= Pages.Num()-1 ) break; XWalk += Pages[iDrag+1]->TabWidth; Pages.Swap( iDrag, iDrag+1 ); } // Refresh highlight. iActive = iHighlight = Pages.FindItem( DragPage ); bWasDrag = true; } } // // When mouse press tabs bar. // void WTabControl::OnMouseDown( EMouseButton Button, Integer X, Integer Y ) { WContainer::OnMouseDown( Button, X, Y ); // Test maybe clicked on little triangle. if( bOverflow && Button==MB_Left && X > Size.Width-14 ) { // Setup popup and show it. Popup->Items.Empty(); for( Integer i=0; i<Pages.Num(); i++ ) Popup->AddItem( Pages[i]->Caption, WIDGET_EVENT(WTabControl::PopupPageClick), true ); Popup->Show( TPoint( Size.Width, 20 ) ); return; } Integer iClicked = XToIndex(X); iCross = XYToCross( X, Y ); // Activate pressed. if( iCross == -1 && iClicked != -1 && iClicked != iActive && !DragPage && Button != MB_Middle ) { ActivateTabPage( iClicked ); } // Prepare to drag active page. bWasDrag = false; if( Button == MB_Left && iActive != -1 ) DragPage = Pages[iActive]; } // // Activate an iPage. // void WTabControl::ActivateTabPage( Integer iPage ) { assert(iPage>=0 && iPage<Pages.Num()); // Hide all. for( Integer i=0; i<Pages.Num(); i++ ) Pages[i]->bVisible = false; // Show and activate. Pages[iPage]->bVisible = true; Pages[iPage]->OnOpen(); iActive = iPage; // Realign. AlignChildren(); //Pages[iPage]->AlignChildren(); Pages[iPage]->WidgetProc( WPE_Resize, TWidProcParms() ); // Make it focused. Root->SetFocused( this ); } // // Activate an Page. // void WTabControl::ActivateTabPage( WTabPage* Page ) { Integer iPage = Pages.FindItem( Page ); assert(iPage != -1); ActivateTabPage( iPage ); } // // When mouse leave tabs. // void WTabControl::OnMouseLeave() { WContainer::OnMouseLeave(); // No highlight any more. iHighlight = -1; iCross = -1; } // // Convert mouse X to tab index, if mouse outside // any tabs return -1. // Integer WTabControl::XToIndex( Integer InX ) { Integer XWalk = 0; for( Integer i=0; i<Pages.Num(); i++ ) { WTabPage* Page = Pages[i]; if( XWalk+Page->TabWidth > Size.Width-15 ) break; if( ( InX >= XWalk ) && ( InX <= XWalk + Page->TabWidth ) ) return i; XWalk += Page->TabWidth; } return -1; } // // Figure out index of close cross on tab. // It no cross around - return -1. // Integer WTabControl::XYToCross( Integer InX, Integer InY ) { Integer XWalk = 0; for( Integer i=0; i<Pages.Num(); i++ ) { WTabPage* Page = Pages[i]; if( XWalk+Page->TabWidth > Size.Width-15 ) break; if( ( InX > XWalk+Page->TabWidth-20 ) && ( InX < XWalk+Page->TabWidth-5 ) && ( InY > 4 && InY < 15 ) ) return i; XWalk += Page->TabWidth; } return -1; } // // Page selected. // void WTabControl::PopupPageClick( WWidget* Sender ) { // Figure out chosen page. WTabPage* Chosen = nullptr; for( Integer i=0; i<Popup->Items.Num(); i++ ) if( Popup->Items[i].bChecked ) { Chosen = Pages[i]; break; } assert(Chosen); // Carousel pages, to make chosen first. while( Pages[0] != Chosen ) { WTabPage* First = Pages[0]; for( Integer i=0; i<Pages.Num()-1; i++ ) Pages[i] = Pages[i+1]; Pages[Pages.Num()-1] = First; } // Make first page active now. ActivateTabPage( 0 ); } // // Tab control has been activated. // void WTabControl::OnActivate() { WContainer::OnActivate(); // Pages switching failure :( #if 0 // Activate selected page. WTabPage* Page = GetActivePage(); if( Page ) Root->SetFocused( Page ); #endif } /*----------------------------------------------------------------------------- The End. -----------------------------------------------------------------------------*/
19.265233
102
0.574233
VladGordienko28
adddaedc9a8c59629f3f2fd012503ac9d6c83d26
336
cpp
C++
net.ssa/Dima/bge.root/bge/bge/ui.cpp
ixray-team/xray-vss-archive
b245c8601dcefb505b4b51f58142da6769d4dc92
[ "Linux-OpenIB" ]
1
2022-03-26T17:00:19.000Z
2022-03-26T17:00:19.000Z
Dima/bge.root/bge/bge/ui.cpp
ixray-team/xray-vss-archive
b245c8601dcefb505b4b51f58142da6769d4dc92
[ "Linux-OpenIB" ]
null
null
null
Dima/bge.root/bge/bge/ui.cpp
ixray-team/xray-vss-archive
b245c8601dcefb505b4b51f58142da6769d4dc92
[ "Linux-OpenIB" ]
1
2022-03-26T17:00:21.000Z
2022-03-26T17:00:21.000Z
//////////////////////////////////////////////////////////////////////////// // Module : ui.cpp // Created : 12.11.2004 // Modified : 12.11.2004 // Author : Dmitriy Iassenev // Description : User interface //////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "ui.h"
30.545455
77
0.330357
ixray-team
ade07f5f3e86790ca6d9be1a00bce643a4edcc95
109
cpp
C++
Engine/src/Engine/Graphics/renderers/RenderAPI.cpp
AustinLynes/Arcana-Tools
ce585d552e30174c4c629a9ea05e7f83947499a5
[ "Apache-2.0" ]
null
null
null
Engine/src/Engine/Graphics/renderers/RenderAPI.cpp
AustinLynes/Arcana-Tools
ce585d552e30174c4c629a9ea05e7f83947499a5
[ "Apache-2.0" ]
null
null
null
Engine/src/Engine/Graphics/renderers/RenderAPI.cpp
AustinLynes/Arcana-Tools
ce585d552e30174c4c629a9ea05e7f83947499a5
[ "Apache-2.0" ]
null
null
null
#include "RenderAPI.h" namespace ArcanaTools { RenderAPI::API RenderAPI::s_API = RenderAPI::API::OPENGL; }
18.166667
58
0.743119
AustinLynes
ade1d45bdeffb800948221a346afcac788e4ec1f
2,740
cpp
C++
codes/CF/CF_911F.cpp
chessbot108/solved-problems
0945be829a8ea9f0d5896c89331460d70d076691
[ "MIT" ]
2
2021-03-07T03:34:02.000Z
2021-03-09T01:22:21.000Z
codes/CF/CF_911F.cpp
chessbot108/solved-problems
0945be829a8ea9f0d5896c89331460d70d076691
[ "MIT" ]
1
2021-03-27T15:01:23.000Z
2021-03-27T15:55:34.000Z
codes/CF/CF_911F.cpp
chessbot108/solved-problems
0945be829a8ea9f0d5896c89331460d70d076691
[ "MIT" ]
1
2021-03-27T05:02:33.000Z
2021-03-27T05:02:33.000Z
//here take a cat #include <iostream> #include <cstdio> #include <cstring> #include <cstdlib> #include <string> #include <utility> #include <cmath> #include <cassert> #include <algorithm> #include <vector> #include <random> #include <chrono> #include <queue> #include <set> #define ll long long #define lb long double #define pii pair<int, int> #define pb push_back #define mp make_pair #define ins insert #define cont continue #define pow2(n) (1 << (n)) #define LC(n) (((n) << 1) + 1) #define RC(n) (((n) << 1) + 2) #define add(a, b) (((a)%mod + (b)%mod)%mod) #define mul(a, b) (((a)%mod * (b)%mod)%mod) #define init(arr, val) memset(arr, val, sizeof(arr)) #define bckt(arr, val, sz) memset(arr, val, sizeof(arr[0]) * (sz)) #define uid(a, b) uniform_int_distribution<int>(a, b)(rng) #define tern(a, b, c) ((a) ? (b) : (c)) #define feq(a, b) (fabs(a - b) < eps) #define moo printf #define oom scanf #define mool puts("") #define orz assert #define fll fflush(stdout) const lb eps = 1e-9; const ll mod = 1e9 + 7, ll_max = (ll)1e18; const int MX = 2e5 +10, int_max = 0x3f3f3f3f; using namespace std; mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count()); struct node{ int u, w; node(){}; node(int a, int b){ u=a, w=b; } bool operator < (const node& b) const{ return w < b.w; //HMMMM } }; int dep[MX], dist[MX][5], vis[MX], par[MX], deg[MX]; int n; priority_queue<node> pq; vector<int> adj[MX]; vector<pair<pii, int>> ans; void dfs(int u, int p, int d, int op){ par[u] = p; dep[u] = d; dist[u][op] = max(d, dist[u][op]); for(int v : adj[u]){ if(v != p) dfs(v, u, d + 1, op); } } void mark(int x){ if(!x || vis[x]) return ; vis[x] = 1; mark(par[x]); } int far(int x, int op){ dfs(x, 0, 0, op); for(int i = 1; i<=n; i++){ if(dep[i] > dep[x]) x = i; } return x; } int main(){ cin.tie(0) -> sync_with_stdio(0); cin >> n; for(int i = 0; i<n-1; i++){ int a, b; cin >> a >> b; adj[a].pb(b); adj[b].pb(a); } int d1 = far(1, 0), d2 = far(d1, 1); far(d2, 2); mark(d1); mark(d2); for(int i = 1; i<=n; i++){ deg[i] = adj[i].size(); if(deg[i] == 1) pq.push(node(i, max(dist[i][1], dist[i][2]))); } ll res = 0ll; while(!pq.empty()){ node cur = pq.top(); pq.pop(); int u = cur.u, w = cur.w, v = tern(dist[u][1] > dist[u][2], d1, d2), p = par[u]; if(vis[u]) cont; ans.pb(mp(mp(u, v), u)); res += w; deg[p]--; if(deg[p] == 1){ pq.push(node(p, max(dist[p][1], dist[p][2]))); } } for(; d1 != d2; d1 = par[d1]){ ans.pb(mp(mp(d1, d2), d1)); res += (ll)dep[d1]; } moo("%lld\n", res); for(const auto& e : ans){ moo("%d %d %d\n", e.first.first, e.first.second, e.second); } return 0; }
21.92
84
0.55438
chessbot108
ade50fce87017a1c81f10895ab73bae9171ceb65
196
cpp
C++
src/main/cpp/miscar/Fix.cpp
MisCar/libmiscar
b7da8ea84f1183ce4a8c5b51bcb29bea7052f7b2
[ "BSD-3-Clause" ]
null
null
null
src/main/cpp/miscar/Fix.cpp
MisCar/libmiscar
b7da8ea84f1183ce4a8c5b51bcb29bea7052f7b2
[ "BSD-3-Clause" ]
null
null
null
src/main/cpp/miscar/Fix.cpp
MisCar/libmiscar
b7da8ea84f1183ce4a8c5b51bcb29bea7052f7b2
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) MisCar 1574 #include "miscar/Fix.h" #include <cmath> double miscar::Fix(double value, double range) { return (std::abs(value) < range) ? 0 : (value - range) / (1 - range); }
19.6
71
0.637755
MisCar
ade5137afabf9677c83d62a9053a95abc5ccfb16
5,038
cpp
C++
LAVFilters/decoder/LAVVideo/VideoInputPin.cpp
lcmftianci/licodeanalysis
62e2722eba1b75ef82f7c1328585873d08bb41cc
[ "Apache-2.0" ]
2
2019-11-17T14:01:21.000Z
2019-12-24T14:29:45.000Z
LAVFilters/decoder/LAVVideo/VideoInputPin.cpp
lcmftianci/licodeanalysis
62e2722eba1b75ef82f7c1328585873d08bb41cc
[ "Apache-2.0" ]
null
null
null
LAVFilters/decoder/LAVVideo/VideoInputPin.cpp
lcmftianci/licodeanalysis
62e2722eba1b75ef82f7c1328585873d08bb41cc
[ "Apache-2.0" ]
3
2019-08-28T14:37:01.000Z
2020-06-17T16:46:32.000Z
/* * Copyright (C) 2010-2019 Hendrik Leppkes * http://www.1f0.de * * 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., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "stdafx.h" #include "VideoInputPin.h" #include "ILAVDynamicAllocator.h" CVideoInputPin::CVideoInputPin(TCHAR* pObjectName, CLAVVideo* pFilter, HRESULT* phr, LPWSTR pName) : CDeCSSTransformInputPin(pObjectName, pFilter, phr, pName) , m_pLAVVideo(pFilter) { } STDMETHODIMP CVideoInputPin::NonDelegatingQueryInterface(REFIID riid, void** ppv) { CheckPointer(ppv, E_POINTER); return QI(IPinSegmentEx) __super::NonDelegatingQueryInterface(riid, ppv); } STDMETHODIMP CVideoInputPin::NotifyAllocator(IMemAllocator * pAllocator, BOOL bReadOnly) { HRESULT hr = __super::NotifyAllocator(pAllocator, bReadOnly); m_bDynamicAllocator = FALSE; if (SUCCEEDED(hr) && pAllocator) { ILAVDynamicAllocator *pDynamicAllocator = nullptr; if (SUCCEEDED(pAllocator->QueryInterface(&pDynamicAllocator))) { m_bDynamicAllocator = pDynamicAllocator->IsDynamicAllocator(); } SafeRelease(&pDynamicAllocator); } return hr; } STDMETHODIMP CVideoInputPin::EndOfSegment() { CAutoLock lck(&m_pLAVVideo->m_csReceive); HRESULT hr = CheckStreaming(); if (S_OK == hr) { hr = m_pLAVVideo->EndOfSegment(); } return hr; } // IKsPropertySet STDMETHODIMP CVideoInputPin::Set(REFGUID PropSet, ULONG Id, LPVOID pInstanceData, ULONG InstanceLength, LPVOID pPropertyData, ULONG DataLength) { if(PropSet != AM_KSPROPSETID_TSRateChange) { return __super::Set(PropSet, Id, pInstanceData, InstanceLength, pPropertyData, DataLength); } switch(Id) { case AM_RATE_SimpleRateChange: { AM_SimpleRateChange* p = (AM_SimpleRateChange*)pPropertyData; if (!m_CorrectTS) { return E_PROP_ID_UNSUPPORTED; } CAutoLock cAutoLock(&m_csRateLock); m_ratechange = *p; } break; case AM_RATE_UseRateVersion: { WORD* p = (WORD*)pPropertyData; if (*p > 0x0101) { return E_PROP_ID_UNSUPPORTED; } } break; case AM_RATE_CorrectTS: { LONG* p = (LONG*)pPropertyData; m_CorrectTS = *p; } break; default: return E_PROP_ID_UNSUPPORTED; } return S_OK; } STDMETHODIMP CVideoInputPin::Get(REFGUID PropSet, ULONG Id, LPVOID pInstanceData, ULONG InstanceLength, LPVOID pPropertyData, ULONG DataLength, ULONG* pBytesReturned) { if(PropSet != AM_KSPROPSETID_TSRateChange) { return __super::Get(PropSet, Id, pInstanceData, InstanceLength, pPropertyData, DataLength, pBytesReturned); } switch(Id) { case AM_RATE_SimpleRateChange: { AM_SimpleRateChange* p = (AM_SimpleRateChange*)pPropertyData; CAutoLock cAutoLock(&m_csRateLock); *p = m_ratechange; *pBytesReturned = sizeof(AM_SimpleRateChange); } break; case AM_RATE_MaxFullDataRate: { AM_MaxFullDataRate* p = (AM_MaxFullDataRate*)pPropertyData; *p = 2 * 10000; *pBytesReturned = sizeof(AM_MaxFullDataRate); } break; case AM_RATE_QueryFullFrameRate: { AM_QueryRate* p = (AM_QueryRate*)pPropertyData; p->lMaxForwardFullFrame = 2 * 10000; p->lMaxReverseFullFrame = 0; *pBytesReturned = sizeof(AM_QueryRate); } break; case AM_RATE_QueryLastRateSegPTS: { //REFERENCE_TIME* p = (REFERENCE_TIME*)pPropertyData; return E_PROP_ID_UNSUPPORTED; } break; default: return E_PROP_ID_UNSUPPORTED; } return S_OK; } STDMETHODIMP CVideoInputPin::QuerySupported(REFGUID PropSet, ULONG Id, ULONG* pTypeSupport) { if(PropSet != AM_KSPROPSETID_TSRateChange) { return __super::QuerySupported(PropSet, Id, pTypeSupport); } switch (Id) { case AM_RATE_SimpleRateChange: *pTypeSupport = KSPROPERTY_SUPPORT_GET | KSPROPERTY_SUPPORT_SET; break; case AM_RATE_MaxFullDataRate: *pTypeSupport = KSPROPERTY_SUPPORT_GET; break; case AM_RATE_UseRateVersion: *pTypeSupport = KSPROPERTY_SUPPORT_SET; break; case AM_RATE_QueryFullFrameRate: *pTypeSupport = KSPROPERTY_SUPPORT_GET; break; case AM_RATE_QueryLastRateSegPTS: *pTypeSupport = KSPROPERTY_SUPPORT_GET; break; case AM_RATE_CorrectTS: *pTypeSupport = KSPROPERTY_SUPPORT_SET; break; default: return E_PROP_ID_UNSUPPORTED; } return S_OK; }
29.121387
166
0.708615
lcmftianci
ade52bb499f53d45cc0770a06faa187155e32b1f
14,504
cpp
C++
Axis.Physalis/application/parsing/parsers/StepParser.cpp
renato-yuzup/axis-fem
2e8d325eb9c8e99285f513b4c1218ef53eb0ab22
[ "MIT" ]
2
2021-07-23T08:49:54.000Z
2021-07-29T22:07:30.000Z
Axis.Physalis/application/parsing/parsers/StepParser.cpp
renato-yuzup/axis-fem
2e8d325eb9c8e99285f513b4c1218ef53eb0ab22
[ "MIT" ]
null
null
null
Axis.Physalis/application/parsing/parsers/StepParser.cpp
renato-yuzup/axis-fem
2e8d325eb9c8e99285f513b4c1218ef53eb0ab22
[ "MIT" ]
null
null
null
#include "StepParser.hpp" #include "SnapshotParser.hpp" #include "ResultCollectorParser.hpp" #include "application/factories/parsers/StepParserProvider.hpp" #include "application/jobs/AnalysisStep.hpp" #include "application/jobs/StructuralAnalysis.hpp" #include "application/locators/ClockworkFactoryLocator.hpp" #include "application/locators/SolverFactoryLocator.hpp" #include "application/output/ResultBucketConcrete.hpp" #include "application/parsing/core/SymbolTable.hpp" #include "application/parsing/core/ParseContext.hpp" #include "application/parsing/parsers/EmptyBlockParser.hpp" #include "application/parsing/error_messages.hpp" #include "domain/algorithms/Solver.hpp" #include "services/language/syntax/evaluation/ParameterList.hpp" #include "services/messaging/ErrorMessage.hpp" #include "foundation/NotSupportedException.hpp" #include "foundation/definitions/AxisInputLanguage.hpp" namespace aaj = axis::application::jobs; namespace aal = axis::application::locators; namespace aao = axis::application::output; namespace aapps = axis::application::parsing::parsers; namespace aafp = axis::application::factories::parsers; namespace aapc = axis::application::parsing::core; namespace adal = axis::domain::algorithms; namespace asli = axis::services::language::iterators; namespace aslse = axis::services::language::syntax::evaluation; namespace aslp = axis::services::language::parsing; namespace asmm = axis::services::messaging; namespace afdf = axis::foundation::definitions; // Enforce instantiation of this specialized template template class aapps::StepParserTemplate<aal::SolverFactoryLocator, aal::ClockworkFactoryLocator>; template <class SolverFactoryLoc, class ClockworkFactoryLoc> aapps::StepParserTemplate<SolverFactoryLoc, ClockworkFactoryLoc>::StepParserTemplate( aafp::StepParserProvider& parentProvider, const axis::String& stepName, SolverFactoryLoc& solverLocator, const axis::String& solverType, real startTime, real endTime, const aslse::ParameterList& solverParams, aal::CollectorFactoryLocator& collectorLocator, aal::WorkbookFactoryLocator& formatLocator) : provider_(parentProvider), stepName_(stepName), solverLocator_(solverLocator), collectorLocator_(collectorLocator), formatLocator_(formatLocator) { Init(solverType, startTime, endTime, solverParams); } template <class SolverFactoryLoc, class ClockworkFactoryLoc> aapps::StepParserTemplate<SolverFactoryLoc, ClockworkFactoryLoc>::StepParserTemplate( aafp::StepParserProvider& parentProvider, const axis::String& stepName, SolverFactoryLoc& solverLocator, ClockworkFactoryLoc& clockworkLocator, const axis::String& solverType, real startTime, real endTime, const aslse::ParameterList& solverParams, const axis::String& clockworkType, const aslse::ParameterList& clockworkParams, aal::CollectorFactoryLocator& collectorLocator, aal::WorkbookFactoryLocator& formatLocator) : provider_(parentProvider), stepName_(stepName), solverLocator_(solverLocator), collectorLocator_(collectorLocator), formatLocator_(formatLocator) { Init(solverType, startTime, endTime, solverParams); isClockworkDeclared_ = true; clockworkTypeName_ = clockworkType; clockworkParams_ = &clockworkParams.Clone(); clockworkLocator_ = &clockworkLocator; } template <class SolverFactoryLoc, class ClockworkFactoryLoc> void aapps::StepParserTemplate<SolverFactoryLoc, ClockworkFactoryLoc>::Init( const axis::String& solverType, real startTime, real endTime, const aslse::ParameterList& solverParams ) { solverTypeName_ = solverType; stepStartTime_ = startTime; stepEndTime_ = endTime; solverParams_ = &solverParams.Clone(); isNewReadRound_ = false; dirtyStepBlock_ = false; isClockworkDeclared_ = false; clockworkParams_ = NULL; clockworkLocator_ = NULL; stepResultBucket_ = NULL; nullParser_ = new axis::application::parsing::parsers::EmptyBlockParser(provider_); } template <class SolverFactoryLoc, class ClockworkFactoryLoc> aapps::StepParserTemplate<SolverFactoryLoc, ClockworkFactoryLoc>::~StepParserTemplate( void ) { delete nullParser_; solverParams_->Destroy(); if (clockworkParams_ != NULL) clockworkParams_->Destroy(); clockworkParams_ = NULL; solverParams_ = NULL; } template <class SolverFactoryLoc, class ClockworkFactoryLoc> aapps::BlockParser& aapps::StepParserTemplate<SolverFactoryLoc, ClockworkFactoryLoc>::GetNestedContext( const axis::String& contextName, const aslse::ParameterList& paramList ) { // if couldn't build a step block, we cannot provide nested // contexts because it probably depends on the step begin // defined if (dirtyStepBlock_) { // throwing this exception shows that we don't know how to // proceed with these blocks throw axis::foundation::NotSupportedException(); } // check if the requested context is the special context // 'SNAPSHOT' if (contextName == afdf::AxisInputLanguage::SnapshotsBlockName && paramList.IsEmpty()) { // yes, it is; let's override the default behavior and trick // the main parser giving him our own snapshot block parser SnapshotParser& p = *new SnapshotParser(isNewReadRound_); p.SetAnalysis(GetAnalysis()); return p; } else if (contextName == afdf::AxisInputLanguage::ResultCollectionSyntax.BlockName) { // no, this is the special context 'OUTPUT' if (!ValidateCollectorBlockInformation(paramList)) { // invalid, insufficient or unknown parameters throw axis::foundation::NotSupportedException(); } BlockParser& p = CreateResultCollectorParser(paramList); p.SetAnalysis(GetAnalysis()); return p; } // any other non-special block registered if (provider_.ContainsProvider(contextName, paramList)) { aafp::BlockProvider& provider = provider_.GetProvider(contextName, paramList); aapps::BlockParser& nestedContext = provider.BuildParser(contextName, paramList); nestedContext.SetAnalysis(GetAnalysis()); return nestedContext; } // no provider found throw axis::foundation::NotSupportedException(); } template <class SolverFactoryLoc, class ClockworkFactoryLoc> aslp::ParseResult aapps::StepParserTemplate<SolverFactoryLoc, ClockworkFactoryLoc>::Parse( const asli::InputIterator& begin, const asli::InputIterator& end ) { return nullParser_->Parse(begin, end); } template <class SolverFactoryLoc, class ClockworkFactoryLoc> void aapps::StepParserTemplate<SolverFactoryLoc, ClockworkFactoryLoc>::DoStartContext( void ) { aapc::SymbolTable& st = GetParseContext().Symbols(); nullParser_->StartContext(GetParseContext()); // first, check if we are able to build the specified solver bool canBuildSolver; if (isClockworkDeclared_) { canBuildSolver = solverLocator_.CanBuild(solverTypeName_, *solverParams_, stepStartTime_, stepEndTime_, clockworkTypeName_, *clockworkParams_); } else { canBuildSolver = solverLocator_.CanBuild(solverTypeName_, *solverParams_, stepStartTime_, stepEndTime_); } if (!canBuildSolver) { // huh? GetParseContext().RegisterEvent(asmm::ErrorMessage(AXIS_ERROR_ID_UNKNOWN_SOLVER_TYPE, AXIS_ERROR_MSG_UNKNOWN_SOLVER_TYPE)); dirtyStepBlock_ = true; return; } // then, check if this is a new read round axis::String symbolName = st.GenerateDecoratedName(aapc::SymbolTable::kAnalysisStep); if (st.IsSymbolDefined(symbolName, aapc::SymbolTable::kAnalysisStep)) { // yes, it is a new read round; we don't need to create a new solver and step objects isNewReadRound_ = true; } st.DefineOrRefreshSymbol(symbolName, aapc::SymbolTable::kAnalysisStep); // set analysis step to work on aaj::StructuralAnalysis& analysis = GetAnalysis(); if (!isNewReadRound_) { // we need to create the new step // build clockwork if we have to adal::Solver *solver = NULL; if (isClockworkDeclared_) { adal::Clockwork *clockwork = NULL; if (clockworkLocator_->CanBuild(clockworkTypeName_, *clockworkParams_, stepStartTime_, stepEndTime_)) { clockwork = &clockworkLocator_->BuildClockwork(clockworkTypeName_, *clockworkParams_, stepStartTime_, stepEndTime_); } else { // there is something wrong with supplied parameters GetParseContext().RegisterEvent( asmm::ErrorMessage(AXIS_ERROR_ID_UNKNOWN_TIME_CONTROL_ALGORITHM, AXIS_ERROR_MSG_UNKNOWN_TIME_CONTROL_ALGORITHM)); dirtyStepBlock_ = true; return; } solver = &solverLocator_.BuildSolver(solverTypeName_, *solverParams_, stepStartTime_, stepEndTime_, *clockwork); } else { solver = &solverLocator_.BuildSolver(solverTypeName_, *solverParams_, stepStartTime_, stepEndTime_); } stepResultBucket_ = new aao::ResultBucketConcrete(); aaj::AnalysisStep& step = aaj::AnalysisStep::Create(stepStartTime_, stepEndTime_, *solver, *stepResultBucket_); step.SetName(stepName_); analysis.AddStep(step); } else { // since we are on a new parse round, retrieve result bucket that we created earlier int stepIndex = GetParseContext().GetStepOnFocusIndex() + 1; aaj::AnalysisStep *step = &GetAnalysis().GetStep(stepIndex); stepResultBucket_ = static_cast<aao::ResultBucketConcrete *>(&step->GetResults()); GetParseContext().SetStepOnFocus(step); GetParseContext().SetStepOnFocusIndex(stepIndex); } if (analysis.GetStepCount() == 1) { // we are parsing the first step GetParseContext().SetStepOnFocus(&analysis.GetStep(0)); GetParseContext().SetStepOnFocusIndex(0); } else { int nextStepIndex = GetParseContext().GetStepOnFocusIndex() + 1; GetParseContext().SetStepOnFocus(&analysis.GetStep(nextStepIndex)); GetParseContext().SetStepOnFocusIndex(nextStepIndex); } } template <class SolverFactoryLoc, class ClockworkFactoryLoc> bool aapps::StepParserTemplate<SolverFactoryLoc, ClockworkFactoryLoc> ::ValidateCollectorBlockInformation( const aslse::ParameterList& contextParams ) { int paramsFound = 2; if (!contextParams.IsDeclared( afdf::AxisInputLanguage::ResultCollectionSyntax.FileNameParameterName)) return false; if (!contextParams.IsDeclared( afdf::AxisInputLanguage::ResultCollectionSyntax.FileFormatParameterName)) return false; // check optional parameters if (contextParams.IsDeclared(afdf::AxisInputLanguage::ResultCollectionSyntax.AppendParameterName)) { String val = contextParams.GetParameterValue( afdf::AxisInputLanguage::ResultCollectionSyntax.AppendParameterName).ToString(); val.to_lower_case().trim(); if (val != _T("yes") && val != _T("no") && val != _T("true") && val != _T("false")) { return false; } paramsFound++; } if (contextParams.IsDeclared( afdf::AxisInputLanguage::ResultCollectionSyntax.FormatArgumentsParameterName)) { aslse::ParameterValue& val = contextParams.GetParameterValue( afdf::AxisInputLanguage::ResultCollectionSyntax.FormatArgumentsParameterName); if (!val.IsArray()) return false; // check if it is an array of parameters try { aslse::ParameterList& test = aslse::ParameterList::FromParameterArray(static_cast<aslse::ArrayValue&>(val)); test.Destroy(); } catch (...) { // uh oh, it is not valid return false; } paramsFound++; } return (contextParams.Count() == paramsFound); } template <class SolverFactoryLoc, class ClockworkFactoryLoc> aapps::BlockParser& aapps::StepParserTemplate<SolverFactoryLoc, ClockworkFactoryLoc> ::CreateResultCollectorParser( const aslse::ParameterList& contextParams ) const { String fileName = contextParams.GetParameterValue( afdf::AxisInputLanguage::ResultCollectionSyntax.FileNameParameterName).ToString(); String formatName = contextParams.GetParameterValue( afdf::AxisInputLanguage::ResultCollectionSyntax.FileFormatParameterName).ToString(); const aslse::ParameterList *formatArgs = NULL; bool append = false; if (contextParams.IsDeclared(afdf::AxisInputLanguage::ResultCollectionSyntax.AppendParameterName)) { String val = contextParams.GetParameterValue( afdf::AxisInputLanguage::ResultCollectionSyntax.AppendParameterName).ToString(); val.to_lower_case().trim(); append = (val != _T("yes") && val != _T("true")); } if (contextParams.IsDeclared( afdf::AxisInputLanguage::ResultCollectionSyntax.FormatArgumentsParameterName)) { aslse::ParameterValue& val = contextParams.GetParameterValue( afdf::AxisInputLanguage::ResultCollectionSyntax.FormatArgumentsParameterName); formatArgs = &aslse::ParameterList::FromParameterArray(static_cast<aslse::ArrayValue&>(val)); } else { formatArgs = &aslse::ParameterList::Empty.Clone(); } aapps::BlockParser *parser = new aapps::ResultCollectorParser(formatLocator_, collectorLocator_, *stepResultBucket_, fileName, formatName, *formatArgs, append); formatArgs->Destroy(); return *parser; }
42.285714
104
0.678089
renato-yuzup
ade991857f9ce165f7166cae00134638ce25675a
7,501
cpp
C++
openstudiocore/src/energyplus/Test/GeneratorMicroTurbine_GTest.cpp
hongyuanjia/OpenStudio
6cc52f1b66c069cf13f2b6ca2a0cc3c137c37cf0
[ "MIT" ]
1
2019-04-21T15:38:54.000Z
2019-04-21T15:38:54.000Z
openstudiocore/src/energyplus/Test/GeneratorMicroTurbine_GTest.cpp
hongyuanjia/OpenStudio
6cc52f1b66c069cf13f2b6ca2a0cc3c137c37cf0
[ "MIT" ]
null
null
null
openstudiocore/src/energyplus/Test/GeneratorMicroTurbine_GTest.cpp
hongyuanjia/OpenStudio
6cc52f1b66c069cf13f2b6ca2a0cc3c137c37cf0
[ "MIT" ]
1
2019-07-18T06:52:29.000Z
2019-07-18T06:52:29.000Z
/********************************************************************** * Copyright (c) 2008-2016, Alliance for Sustainable Energy. * All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA **********************************************************************/ #include <gtest/gtest.h> #include "EnergyPlusFixture.hpp" #include "../ErrorFile.hpp" #include "../ForwardTranslator.hpp" #include "../ReverseTranslator.hpp" // Objects of interest #include "../../model/GeneratorMicroTurbine.hpp" #include "../../model/GeneratorMicroTurbine_Impl.hpp" #include "../../model/GeneratorMicroTurbineHeatRecovery.hpp" #include "../../model/GeneratorMicroTurbineHeatRecovery_Impl.hpp" // Needed resources #include "../../model/PlantLoop.hpp" #include "../../model/PlantLoop_Impl.hpp" #include "../../model/Node.hpp" #include "../../model/Node_Impl.hpp" #include "../../model/Curve.hpp" #include "../../model/Curve_Impl.hpp" #include "../../model/CurveBiquadratic.hpp" #include "../../model/CurveBiquadratic_Impl.hpp" #include "../../model/CurveCubic.hpp" #include "../../model/CurveCubic_Impl.hpp" #include "../../model/CurveQuadratic.hpp" #include "../../model/CurveQuadratic_Impl.hpp" #include "../../model/StraightComponent.hpp" #include "../../model/StraightComponent_Impl.hpp" #include "../../model/Schedule.hpp" #include "../../model/Schedule_Impl.hpp" // For testing PlantEquipOperation #include "../../model/WaterHeaterMixed.hpp" #include "../../model/WaterHeaterMixed_Impl.hpp" #include "../../model/PlantEquipmentOperationHeatingLoad.hpp" #include "../../model/PlantEquipmentOperationHeatingLoad_Impl.hpp" #include "../../model/ElectricLoadCenterDistribution.hpp" #include "../../model/ElectricLoadCenterDistribution_Impl.hpp" // IDF FieldEnums #include <utilities/idd/Generator_MicroTurbine_FieldEnums.hxx> // #include <utilities/idd/OS_Generator_MicroTurbine_HeatRecovery_FieldEnums.hxx> #include <utilities/idd/PlantEquipmentList_FieldEnums.hxx> #include <utilities/idd/IddEnums.hxx> #include <utilities/idd/IddFactory.hxx> // Misc #include "../../model/Version.hpp" #include "../../model/Version_Impl.hpp" #include "../../utilities/core/Optional.hpp" #include "../../utilities/core/Checksum.hpp" #include "../../utilities/core/UUID.hpp" #include "../../utilities/sql/SqlFile.hpp" #include "../../utilities/idf/IdfFile.hpp" #include "../../utilities/idf/IdfObject.hpp" #include "../../utilities/idf/IdfExtensibleGroup.hpp" #include <boost/algorithm/string/predicate.hpp> #include <QThread> #include <resources.hxx> #include <sstream> #include <vector> // Debug #include "../../utilities/core/Logger.hpp" using namespace openstudio::energyplus; using namespace openstudio::model; using namespace openstudio; /** * Tests whether the ForwarTranslator will handle the name of the GeneratorMicroTurbine correctly in the PlantEquipmentOperationHeatingLoad **/ TEST_F(EnergyPlusFixture,ForwardTranslatorGeneratorMicroTurbine_ELCD_PlantLoop) { // TODO: Temporarily output the Log in the console with the Trace (-3) level // for debug // openstudio::Logger::instance().standardOutLogger().enable(); // openstudio::Logger::instance().standardOutLogger().setLogLevel(Trace); // Create a model, a mchp, a mchpHR, a plantLoop and an electricalLoadCenter Model model; GeneratorMicroTurbine mchp = GeneratorMicroTurbine(model); GeneratorMicroTurbineHeatRecovery mchpHR = GeneratorMicroTurbineHeatRecovery(model, mchp); ASSERT_EQ(mchpHR, mchp.generatorMicroTurbineHeatRecovery().get()); PlantLoop plantLoop(model); // Add a supply branch for the mchpHR ASSERT_TRUE(plantLoop.addSupplyBranchForComponent(mchpHR)); // Create a WaterHeater:Mixed WaterHeaterMixed waterHeater(model); // Add it on the same branch as the chpHR, right after it Node mchpHROutletNode = mchpHR.outletModelObject()->cast<Node>(); ASSERT_TRUE(waterHeater.addToNode(mchpHROutletNode)); // Create a plantEquipmentOperationHeatingLoad PlantEquipmentOperationHeatingLoad operation(model); operation.setName(plantLoop.name().get() + " PlantEquipmentOperationHeatingLoad"); ASSERT_TRUE(plantLoop.setPlantEquipmentOperationHeatingLoad(operation)); ASSERT_TRUE(operation.addEquipment(mchpHR)); ASSERT_TRUE(operation.addEquipment(waterHeater)); // Create an ELCD ElectricLoadCenterDistribution elcd = ElectricLoadCenterDistribution(model); elcd.setName("Capstone C65 ELCD"); elcd.setElectricalBussType("AlternatingCurrent"); elcd.addGenerator(mchp); // Forward Translates ForwardTranslator forwardTranslator; Workspace workspace = forwardTranslator.translateModel(model); EXPECT_EQ(0u, forwardTranslator.errors().size()); ASSERT_EQ(1u, workspace.getObjectsByType(IddObjectType::WaterHeater_Mixed).size()); ASSERT_EQ(1u, workspace.getObjectsByType(IddObjectType::ElectricLoadCenter_Distribution).size()); // The MicroTurbine should have been forward translated since there is an ELCD WorkspaceObjectVector microTurbineObjects(workspace.getObjectsByType(IddObjectType::Generator_MicroTurbine)); EXPECT_EQ(1u, microTurbineObjects.size()); // Check that the HR nodes have been set WorkspaceObject idf_mchp(microTurbineObjects[0]); EXPECT_EQ(mchpHR.inletModelObject()->name().get(), idf_mchp.getString(Generator_MicroTurbineFields::HeatRecoveryWaterInletNodeName).get()); EXPECT_EQ(mchpHR.outletModelObject()->name().get(), idf_mchp.getString(Generator_MicroTurbineFields::HeatRecoveryWaterOutletNodeName).get()); OptionalWorkspaceObject idf_operation(workspace.getObjectByTypeAndName(IddObjectType::PlantEquipmentOperation_HeatingLoad,*(operation.name()))); ASSERT_TRUE(idf_operation); // Get the extensible ASSERT_EQ(1u, idf_operation->numExtensibleGroups()); // IdfExtensibleGroup eg = idf_operation.getExtensibleGroup(0); // idf_operation.targets[0] ASSERT_EQ(1u, idf_operation->targets().size()); WorkspaceObject plantEquipmentList(idf_operation->targets()[0]); ASSERT_EQ(2u, plantEquipmentList.extensibleGroups().size()); IdfExtensibleGroup eg(plantEquipmentList.extensibleGroups()[0]); ASSERT_EQ("Generator:MicroTurbine", eg.getString(PlantEquipmentListExtensibleFields::EquipmentObjectType).get()); // This fails EXPECT_EQ(mchp.name().get(), eg.getString(PlantEquipmentListExtensibleFields::EquipmentName).get()); IdfExtensibleGroup eg2(plantEquipmentList.extensibleGroups()[1]); ASSERT_EQ("WaterHeater:Mixed", eg2.getString(PlantEquipmentListExtensibleFields::EquipmentObjectType).get()); EXPECT_EQ(waterHeater.name().get(), eg2.getString(PlantEquipmentListExtensibleFields::EquipmentName).get()); model.save(toPath("./ForwardTranslatorGeneratorMicroTurbine_ELCD_PlantLoop.osm"), true); workspace.save(toPath("./ForwardTranslatorGeneratorMicroTurbine_ELCD_PlantLoop.idf"), true); }
41.441989
146
0.758299
hongyuanjia
adf0c68c4d4e4dff66ea7a9388d9a254bcb27d32
375
cpp
C++
src/libgraphic/src/message/entity/DestroyGraphicEntityMessage.cpp
SimonPiCarter/GameEngine
10d366bd37d202a5a22eb504b2a2dd9a49669dc8
[ "Apache-2.0" ]
null
null
null
src/libgraphic/src/message/entity/DestroyGraphicEntityMessage.cpp
SimonPiCarter/GameEngine
10d366bd37d202a5a22eb504b2a2dd9a49669dc8
[ "Apache-2.0" ]
15
2021-05-18T14:16:03.000Z
2021-06-17T19:36:32.000Z
src/libgraphic/src/message/entity/DestroyGraphicEntityMessage.cpp
SimonPiCarter/GameEngine
10d366bd37d202a5a22eb504b2a2dd9a49669dc8
[ "Apache-2.0" ]
null
null
null
#include "DestroyGraphicEntityMessage.h" #include "message/GraphicMessageHandler.h" DestroyGraphicEntityMessage::DestroyGraphicEntityMessage(GraphicEntity * entity_p, bool delete_p) : GraphicMessage("") , _entity(entity_p) , _delete(delete_p) {} void DestroyGraphicEntityMessage::visit(GraphicMessageHandler &handler_p) { handler_p.visitDestroyGraphicEntity(*this); }
25
97
0.816
SimonPiCarter
adf2f68c4db3313d196b8d7dd7fd4b58bfd933e7
1,253
cpp
C++
src/option.cpp
jserot/rfsm-gui
4eee507ae6e06088fbc66fd2383d5533af49090b
[ "MIT" ]
null
null
null
src/option.cpp
jserot/rfsm-gui
4eee507ae6e06088fbc66fd2383d5533af49090b
[ "MIT" ]
null
null
null
src/option.cpp
jserot/rfsm-gui
4eee507ae6e06088fbc66fd2383d5533af49090b
[ "MIT" ]
null
null
null
/**********************************************************************/ /* */ /* This file is part of the RFSM package */ /* */ /* Copyright (c) 2018-present, Jocelyn SEROT. All rights reserved. */ /* */ /* This source code is licensed under the license found in the */ /* LICENSE file in the root directory of this source tree. */ /* */ /**********************************************************************/ #include "option.h" AppOption::AppOption(QString _category, QString _name, Opt_kind _kind, QString _desc) { category = _category; name = _name; kind = _kind; desc = _desc; switch ( kind ) { case UnitOpt: checkbox = new QCheckBox(); val = NULL; break; case StringOpt: checkbox = NULL; val = new QLineEdit(); //val->setFixedSize(100,20); case IntOpt: checkbox = NULL; val = new QLineEdit(); //val->setFixedSize(100,20); break; } }
35.8
88
0.381484
jserot
adfa2a6509c6eb97a30e4c8cf91e4d188ed88b0c
952
cpp
C++
914C.cpp
basuki57/Codeforces
5227c3deecf13d90e5ea45dab0dfc16b44bd028c
[ "MIT" ]
null
null
null
914C.cpp
basuki57/Codeforces
5227c3deecf13d90e5ea45dab0dfc16b44bd028c
[ "MIT" ]
null
null
null
914C.cpp
basuki57/Codeforces
5227c3deecf13d90e5ea45dab0dfc16b44bd028c
[ "MIT" ]
2
2020-10-03T04:52:14.000Z
2020-10-03T05:19:12.000Z
#include<bits/stdc++.h> using namespace std; typedef long long int ll; ll c[1010][1010], mod = 1e9 + 7; void comb(){ c[0][0] = 1; for(ll i = 1; i < 1010; ++i){ c[i][0] = 1; for(ll j = 1; j < 1010; ++j) c[i][j] = (c[i-1][j-1] + c[i-1][j])%mod; } } void solve(){ comb(); string s; cin >> s; ll k; cin >> k; if(!k){ cout << 1 << endl; return; } ll f[1010] = {0}, cnt = 0, ans = 0, n = s.size(); if(k == 1){ cout << n-1 << endl; return; } for(ll i = 2; i <= n; ++i) f[i] = f[__builtin_popcount(i)] + 1; for(ll i = 0; i < n; i++) if(s[i] == '1'){ for(ll j = (i==0); j < n-i; ++j) ans = (ans + c[n-i-1][j]*(f[cnt + j] == k-1))%mod; cnt++; } ans = (ans + (f[cnt] == k-1))%mod; cout << ans << endl; } int main(){ ios_base::sync_with_stdio(false); cin.tie(0); // int t;cin>>t;for(int i = 0 ;i<t;i++) solve(); return 0; }
21.636364
91
0.422269
basuki57
adfc689d5fd35369ad097c09dc98495f9ec30835
736
cpp
C++
faculdade2020Fatec/lista2/ex4.cpp
DouSam/AnyLiteryAnyThingIDo
48313b1dd0534df15c6b024f2f2118a76bd2ac0a
[ "MIT" ]
1
2018-07-13T23:59:34.000Z
2018-07-13T23:59:34.000Z
faculdade2020Fatec/lista2/ex4.cpp
CoalaDrogado69/AnyLiteryAnyThingIDo
48313b1dd0534df15c6b024f2f2118a76bd2ac0a
[ "MIT" ]
null
null
null
faculdade2020Fatec/lista2/ex4.cpp
CoalaDrogado69/AnyLiteryAnyThingIDo
48313b1dd0534df15c6b024f2f2118a76bd2ac0a
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main() { int vetor[10]; int pares = 0; //Para cada posição eu irei pedir um valor para o usuário for (int i = 0; i < 10; i++) { cout << "Digite um valor para posição " << i << endl; cin >> vetor[i]; }; //Para cada posição irei analisar se essa é par e apenas exibir caso seja. for (int i = 0; i < 10; i++) { if (vetor[i] % 2 == 0) { cout << "Elemento " << i << " é par" << endl; cout << "Valor: " << vetor[i] << endl; //Somando caso seja par. pares++; }; }; cout << "Total de elementos pares: " << pares; return 0; }
22.30303
79
0.45788
DouSam
adfc7e4e1421cd2e7252b8bd45f1a168a4d124e3
5,476
cpp
C++
Compiler/src/AST.cpp
BrandonKi/ARCANE
425d481610125ba89bbe36e4c16b680d6e2b7868
[ "MIT" ]
7
2020-06-24T03:32:36.000Z
2022-01-15T03:59:56.000Z
Compiler/src/AST.cpp
BrandonKi/ARCANE
425d481610125ba89bbe36e4c16b680d6e2b7868
[ "MIT" ]
2
2021-06-25T02:18:41.000Z
2021-06-25T18:59:05.000Z
Compiler/src/AST.cpp
BrandonKi/ARCANE
425d481610125ba89bbe36e4c16b680d6e2b7868
[ "MIT" ]
1
2021-06-25T17:43:20.000Z
2021-06-25T17:43:20.000Z
#include "AST.h" extern ErrorHandler error_log; extern TypeManager type_manager; AST::AST() { PROFILE(); } AST::~AST() { PROFILE(); } //FIXME fix all of this absolute trash // at the moment we are making copies of the vectors and moving some and none of it is good // FIXME use allocator [[nodiscard]] Project* AST::new_project_node(const SourcePos pos, std::vector<File*>& files) { PROFILE(); return new Project{{pos}, files}; } [[nodiscard]] File* AST::new_file_node( const SourcePos pos, const std::string name, std::vector<Import*>& imports, std::vector<Decl*>& decls, std::vector<Function*>& functions, const bool is_main ) { PROFILE(); return new File{{pos}, name, std::move(imports), std::move(decls), std::move(functions), is_main}; } [[nodiscard]] Import* AST::new_import_node(const SourcePos pos, std::string& id, std::string& filename) { PROFILE(); return new Import{{pos}, id, filename}; } [[nodiscard]] Function* AST::new_function_node(const SourcePos pos, std::string& id, std::vector<Arg>& fn_args, type_handle type, Block* body, const bool is_main) { PROFILE(); return new Function{{pos}, id, fn_args, type, body, is_main }; } [[nodiscard]] Block* AST::new_block_node(const SourcePos pos, std::vector<Statement*>& statements) { PROFILE(); return new Block{{pos}, statements}; } [[nodiscard]] WhileStmnt* AST::new_while_node(const SourcePos pos, Expr* expr, Block* block) { PROFILE(); return new WhileStmnt{{pos}, expr, block}; } [[nodiscard]] ForStmnt* AST::new_for_node(const SourcePos pos, Decl* decl, Expr* expr1, Expr* expr2, Block* block) { PROFILE(); return new ForStmnt{{pos}, decl, expr1, expr2, block}; } [[nodiscard]] IfStmnt* AST::new_if_node(const SourcePos pos, Expr* expr, Block* block, Block* else_stmnt) { PROFILE(); return new IfStmnt{{pos}, expr, block, else_stmnt}; } [[nodiscard]] RetStmnt* AST::new_ret_node(const SourcePos pos, Expr* expr) { PROFILE(); return new RetStmnt{{pos}, expr}; } [[nodiscard]] Statement* AST::new_statement_node_while(const SourcePos pos, WhileStmnt* while_stmnt) { PROFILE(); auto *ptr = new Statement{ {pos}, WHILE}; ptr->while_stmnt = while_stmnt; return ptr; } [[nodiscard]] Statement* AST::new_statement_node_for(const SourcePos pos, ForStmnt* for_stmnt) { PROFILE(); auto *ptr = new Statement{ {pos}, FOR}; ptr->for_stmnt = for_stmnt; return ptr; } [[nodiscard]] Statement* AST::new_statement_node_if(const SourcePos pos, IfStmnt* if_stmnt) { PROFILE(); auto *ptr = new Statement{ {pos}, IF}; ptr->if_stmnt = if_stmnt; return ptr; } [[nodiscard]] Statement* AST::new_statement_node_ret(const SourcePos pos, RetStmnt* ret_stmnt) { PROFILE(); auto *ptr = new Statement{ {pos}, RET}; ptr->ret_stmnt = ret_stmnt; return ptr; } Statement* AST::new_statement_node_decl(const SourcePos pos, Decl* decl) { PROFILE(); auto *ptr = new Statement{ {pos}, DECLARATION}; ptr->decl = decl; return ptr; } [[nodiscard]] Statement* AST::new_statement_node_expr(const SourcePos pos, Expr* expr) { PROFILE(); auto *ptr = new Statement { {pos}, EXPRESSION}; ptr->expr = expr; return ptr; } [[nodiscard]] Expr* AST::new_expr_node_int_literal(const SourcePos pos, const i64 int_literal, type_handle type) { PROFILE(); auto *ptr = new Expr{{pos}, EXPR_INT_LIT, type}; ptr->int_literal.val = int_literal; return ptr; } [[nodiscard]] Expr* AST::new_expr_node_float_literal(const SourcePos pos, const f64 float_literal, type_handle type) { PROFILE(); auto *ptr = new Expr{{pos}, EXPR_FLOAT_LIT, type}; ptr->float_literal.val = float_literal; return ptr; } [[nodiscard]] Expr* AST::new_expr_node_string_literal(const SourcePos pos, std::string& string_literal, type_handle type) { PROFILE(); auto *ptr = new Expr{{pos}, EXPR_STRING_LIT, type}; ptr->string_literal.val = new std::string(string_literal); return ptr; } [[nodiscard]] Expr* AST::new_expr_node_variable(const SourcePos pos, std::string& id, type_handle type) { PROFILE(); auto *ptr = new Expr{{pos}, EXPR_ID, type}; // FIXME allocator ptr->id.val = new std::string(id); return ptr; } [[nodiscard]] Expr* AST::new_expr_node_fn_call(const SourcePos pos, std::string& id, u32 argc, Expr** argv, type_handle type) { PROFILE(); auto *ptr = new Expr{{pos}, EXPR_FN_CALL, type}; // FIXME allocator ptr->fn_call.val = new std::string(id); ptr->fn_call.argc = argc; ptr->fn_call.args = argv; return ptr; } [[nodiscard]] Expr* AST::new_expr_node_bin_expr(const SourcePos pos, const TokenKind op, Expr* left, Expr* right, type_handle type) { PROFILE(); auto *ptr = new Expr{ {pos}, EXPR_BIN, type}; ptr->binary_expr.op = op; ptr->binary_expr.left = left; ptr->binary_expr.right = right; return ptr; } [[nodiscard]] Expr* AST::new_expr_node_unary_expr(const SourcePos pos, const TokenKind op, Expr* expr, type_handle type) { PROFILE(); auto* ptr = new Expr{ {pos}, EXPR_UNARY, type}; ptr->unary_expr.op = op; ptr->unary_expr.expr = expr; return ptr; } [[nodiscard]] Decl* AST::new_decl_node(const SourcePos pos, std::string& id, const type_handle type, Expr* val) { PROFILE(); // FIXME allocator auto* ptr = new Decl{ {pos}, new std::string(id), type, val }; return ptr; }
31.471264
164
0.669467
BrandonKi
adfd0ca913de67a10322e8feb232510d30d79519
2,588
cpp
C++
Procedural Programming I/tema10.cpp
dindareanualin/School-Work
3ce04376e0a22d4c709303540a91ba17d0b63096
[ "MIT" ]
null
null
null
Procedural Programming I/tema10.cpp
dindareanualin/School-Work
3ce04376e0a22d4c709303540a91ba17d0b63096
[ "MIT" ]
null
null
null
Procedural Programming I/tema10.cpp
dindareanualin/School-Work
3ce04376e0a22d4c709303540a91ba17d0b63096
[ "MIT" ]
null
null
null
//10. Given an n lines, m columns matrix, write an algorithm which will // first display the matrix with each line sorted in ascending order, //then display the matrix with each column sorted in ascending order. #include <iostream> using namespace std; int main(){ int m, n; int matrice[50][50], copie_matrice[50][50]; cout << "\nIntroduceti m,n positive integers, 1 > m,n <= 50 (size of the matrix):"; cout << "\nm = "; cin >> m; cout << "\nn = "; cin >> n; for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++){ cout << "\nelement [" << j << "][" << i << "] = "; cin >> matrice[j][i]; copie_matrice[j][i] = matrice[j][i]; } cout << "\nInitial matrix:"; cout << "\n"; for (int i = 1; i <= n; i++){ for (int j = 1; j <= m; j++){ cout << " " << matrice[j][i] << " "; } cout << "\n"; } for (int i = 1; i <= n; i++){ bool sortat = false; while (not sortat){ sortat = true; for (int j = 1; j <= m - 1; j++){ if (matrice[j + 1][i] < matrice[j][i]){ int temp = matrice[j][i]; matrice[j][i] = matrice[j + 1][i]; matrice[j + 1][i] = temp; sortat = false; } } } } cout << "\nLines sorted in ascending order: "; cout << "\n"; for (int i = 1; i <= n; i++){ for (int j = 1; j <= m; j++){ cout << " " << matrice[j][i] << " "; } cout << "\n"; } //matrice = copie_matrice; for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) matrice[j][i] = copie_matrice[j][i]; for (int i = 1; i <= n; i++){ bool sortat = false; while (not sortat){ sortat = true; for (int j = 1; j <= m - 1; j++){ if (matrice[i][j + 1] < matrice[i][j]){ int temp = matrice[j][i]; matrice[i][j] = matrice[i][j + 1]; matrice[i][j + 1] = temp; sortat = false; } } } } cout << "\nColumns sorted in ascending order: "; cout << "\n"; for (int i = 1; i <= n; i++){ for (int j = 1; j <= m; j++){ cout << " " << matrice[j][i] << " "; } cout << "\n"; } char ch; cin >> ch; return 0; }
25.372549
88
0.376739
dindareanualin
bc0287b34fa8cbfa7b7c45fb81aa69b519d9f986
284
cpp
C++
src/hir/crate_ptr.cpp
spacekookie/mrustc
e49cd3b71a5b5458ecd3f3937c04d1a35871a190
[ "MIT" ]
null
null
null
src/hir/crate_ptr.cpp
spacekookie/mrustc
e49cd3b71a5b5458ecd3f3937c04d1a35871a190
[ "MIT" ]
null
null
null
src/hir/crate_ptr.cpp
spacekookie/mrustc
e49cd3b71a5b5458ecd3f3937c04d1a35871a190
[ "MIT" ]
null
null
null
/* */ #include "crate_ptr.hpp" #include "hir.hpp" ::HIR::CratePtr::CratePtr(): m_ptr(nullptr) { } ::HIR::CratePtr::CratePtr(HIR::Crate c): m_ptr( new ::HIR::Crate(mv$(c)) ) { } ::HIR::CratePtr::~CratePtr() { if( m_ptr ) { delete m_ptr, m_ptr = nullptr; } }
13.52381
40
0.559859
spacekookie
bc06002ef7dfd4b4baffe42fa63ee98eb66c952d
3,190
cpp
C++
Code/exec/BCHLaiTest.cpp
amihashemi/cs294project
7d0f67a40f72cd58a86fb7d7fcb3ed40f5ddc1ec
[ "MIT" ]
null
null
null
Code/exec/BCHLaiTest.cpp
amihashemi/cs294project
7d0f67a40f72cd58a86fb7d7fcb3ed40f5ddc1ec
[ "MIT" ]
null
null
null
Code/exec/BCHLaiTest.cpp
amihashemi/cs294project
7d0f67a40f72cd58a86fb7d7fcb3ed40f5ddc1ec
[ "MIT" ]
null
null
null
// Final project for CS 294-73 at Berkeley // Amirreza Hashemi and Júlio Caineta // 2017 #include "RectMDArray.H" #include "FFT1DW.H" #include "FieldData.H" #include "RK4.H" #include "WriteRectMDArray.H" #include "RHSNavierStokes.H" void computeVorticity(RectMDArray< double >& vorticity, const DBox box, FieldData& velocities, double dx) { for (Point pt = box.getLowCorner(); box.notDone(pt); box.increment(pt)) { Point lowShift; Point highShift; double dudy; double dvdx; lowShift[0] = pt[0]; lowShift[1] = pt[1] - 1; highShift[0] = pt[0]; highShift[1] = pt[1] + 1; dudy = (velocities.m_data(highShift, 0) - velocities.m_data(lowShift, 0)) / (2 * dx); lowShift[0] = pt[0] - 1; lowShift[1] = pt[1]; highShift[0] = pt[0] + 1; highShift[1] = pt[1]; dvdx = (velocities.m_data(highShift, 1) - velocities.m_data(lowShift, 1)) / (2 * dx); vorticity[pt] = dudy - dvdx; } }; double maxVelocity(RectMDArray< double, DIM > velocities) { // only working for 2D double umax = 0.; double vmax = 0.; DBox box = velocities.getDBox(); for (Point pt = box.getLowCorner(); box.notDone(pt); box.increment(pt)) { double velocity[2]; velocity[0] = velocities(pt, 0); velocity[1] = velocities(pt, 1); umax = max(velocity[0], umax); vmax = max(velocity[1], vmax); } return max(umax, vmax); }; int main(int argc, char* argv[]) { int M; // int M = 8; cout << "input log_2(number of grid points) [e.g., 8]" << endl; cin >> M; int N = Power(2, M); std::shared_ptr< FFT1D > fft1dPtr(new FFT1DW(M)); FieldData velocities(fft1dPtr, 1); Point low = {{{0, 0}}}; Point high = {{{N - 1, N - 1}}}; DBox box(low, high); double dx = 1.0 / ((double) N); double timeEnd = 0.8; char filename[10]; int nstop = 400; double sigma = 0.04; double x_0 = 0.4; double y_0 = 0.5; for (Point pt = box.getLowCorner(); box.notDone(pt); box.increment(pt)) { velocities.m_data(pt, 0) = exp(-(pow((pt[0] * dx - x_0), 2) + pow((pt[1] * dx - y_0), 2)) / (2 * pow(sigma, 2.))) / pow(sigma, 2.); velocities.m_data(pt, 1) = exp(-(pow((pt[0] * dx - x_0), 2) + pow((pt[1] * dx - y_0), 2)) / (2 * pow(sigma, 2.))) / pow(sigma, 2.); } RK4 <FieldData, RHSNavierStokes, DeltaVelocity> integrator; double dt = 0.0001; double time = 0.0; RectMDArray< double > vorticity(box); computeVorticity(vorticity, box, velocities, dx); sprintf(filename, "Vorticity.%.4f.%.4f", timeEnd, time); MDWrite(string(filename), vorticity); int nstep = 0; while (nstep < nstop) { velocities.setBoundaries(); integrator.advance(time, dt, velocities); sprintf(filename, "velocity.%d", nstep); MDWrite(string(filename), velocities.m_data); velocities.setBoundaries(); time += dt; nstep++; computeVorticity(vorticity, box, velocities, dx); sprintf(filename, "Vorticity.%d", nstep); MDWrite(string(filename), vorticity); cout << "iter = " << nstep << endl; } };
27.5
74
0.577429
amihashemi
bc0c4d6a5d840e43582c8b9398cfc22a90a2e49b
7,266
cpp
C++
lib/https/server/src/session.cpp
solosTec/node
e35e127867a4f66129477b780cbd09c5231fc7da
[ "MIT" ]
2
2020-03-03T12:40:29.000Z
2021-05-06T06:20:19.000Z
lib/https/server/src/session.cpp
solosTec/node
e35e127867a4f66129477b780cbd09c5231fc7da
[ "MIT" ]
7
2020-01-14T20:38:04.000Z
2021-05-17T09:52:07.000Z
lib/https/server/src/session.cpp
solosTec/node
e35e127867a4f66129477b780cbd09c5231fc7da
[ "MIT" ]
2
2019-11-09T09:14:48.000Z
2020-03-03T12:40:30.000Z
/* * The MIT License (MIT) * * Copyright (c) 2018 Sylko Olzscher * */ #include <smf/https/srv/session.h> #include <smf/https/srv/connections.h> #include <cyng/vm/controller.h> #include <cyng/vm/generator.h> #include <boost/uuid/uuid_io.hpp> namespace node { namespace https { plain_session::plain_session(cyng::logging::log_ptr logger , connections& cm , boost::uuids::uuid tag , boost::asio::ip::tcp::socket socket , boost::beast::flat_buffer buffer , std::string const& doc_root , auth_dirs const& ad) : session<plain_session>(logger, cm, tag, socket.get_executor().context(), std::move(buffer), doc_root, ad) , socket_(std::move(socket)) , strand_(socket_.get_executor()) {} plain_session::~plain_session() {} // Called by the base class boost::asio::ip::tcp::socket& plain_session::stream() { return socket_; } // Called by the base class boost::asio::ip::tcp::socket plain_session::release_stream() { return std::move(socket_); } // Start the asynchronous operation void plain_session::run(cyng::object obj) { // // substitute cb_ // this->connection_manager_.vm().async_run(cyng::generate_invoke("http.session.launch", tag(), false, stream().lowest_layer().remote_endpoint())); // Run the timer. The timer is operated // continuously, this simplifies the code. //on_timer({}); on_timer(obj, boost::system::error_code{}); do_read(obj); } void plain_session::do_eof(cyng::object obj) { // Send a TCP shutdown boost::system::error_code ec; socket_.shutdown(boost::asio::ip::tcp::socket::shutdown_send, ec); // // substitute cb_ // //this->connection_manager_.vm().async_run(cyng::generate_invoke("http.session.eof", tag(), false)); //cb_(cyng::generate_invoke("https.eof.session.plain", obj)); // At this point the connection is closed gracefully } void plain_session::do_timeout(cyng::object obj) { // Closing the socket cancels all outstanding operations. They // will complete with boost::asio::error::operation_aborted boost::system::error_code ec; socket_.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec); socket_.close(ec); } ssl_session::ssl_session(cyng::logging::log_ptr logger , connections& cm , boost::uuids::uuid tag , boost::asio::ip::tcp::socket socket , boost::asio::ssl::context& ctx , boost::beast::flat_buffer buffer , std::string const& doc_root , auth_dirs const& ad) : session<ssl_session>(logger, cm, tag, socket.get_executor().context(), std::move(buffer), doc_root, ad) , stream_(std::move(socket), ctx) , strand_(stream_.get_executor()) {} ssl_session::~ssl_session() { //std::cerr << "ssl_session::~ssl_session()" << std::endl; } // Called by the base class boost::beast::ssl_stream<boost::asio::ip::tcp::socket>& ssl_session::stream() { return stream_; } // Called by the base class boost::beast::ssl_stream<boost::asio::ip::tcp::socket> ssl_session::release_stream() { return std::move(stream_); } // Start the asynchronous operation void ssl_session::run(cyng::object obj) { // // ToDo: substitute cb_ // this->connection_manager_.vm().async_run(cyng::generate_invoke("http.session.launch", tag(), true, stream().lowest_layer().remote_endpoint())); // Run the timer. The timer is operated // continuously, this simplifies the code. //on_timer({}); on_timer(obj, boost::system::error_code{}); // Set the timer timer_.expires_after(std::chrono::seconds(15)); // Perform the SSL handshake // Note, this is the buffered version of the handshake. stream_.async_handshake( boost::asio::ssl::stream_base::server, buffer_.data(), boost::asio::bind_executor( strand_, std::bind( &ssl_session::on_handshake, this, obj, // hold reference std::placeholders::_1, std::placeholders::_2))); } void ssl_session::on_handshake(cyng::object obj , boost::system::error_code ec , std::size_t bytes_used) { // Happens when the handshake times out if (ec == boost::asio::error::operation_aborted) { CYNG_LOG_ERROR(logger_, "handshake timeout "); return; } if (ec) { CYNG_LOG_FATAL(logger_, "handshake: " << ec.message()); return; } // Consume the portion of the buffer used by the handshake buffer_.consume(bytes_used); do_read(obj); } void ssl_session::do_eof(cyng::object obj) { eof_ = true; // Set the timer timer_.expires_after(std::chrono::seconds(15)); // Perform the SSL shutdown stream_.async_shutdown( boost::asio::bind_executor( strand_, std::bind( &ssl_session::on_shutdown, this, obj, std::placeholders::_1))); // // ToDo: substitute cb_ // CYNG_LOG_WARNING(logger_, tag() << " - SSL shutdown"); //cb_(cyng::generate_invoke("https.eof.session.ssl", obj)); } void ssl_session::on_shutdown(cyng::object obj, boost::system::error_code ec) { // Happens when the shutdown times out if (ec == boost::asio::error::operation_aborted) { CYNG_LOG_WARNING(logger_, tag() << " - SSL shutdown timeout"); connection_manager_.stop_session(tag()); return; } if (ec) { //return fail(ec, "shutdown"); CYNG_LOG_WARNING(logger_, tag() << " - SSL shutdown failed"); connection_manager_.stop_session(tag()); return; } // // ToDo: substitute cb_ // //cb_(cyng::generate_invoke("https.on.shutdown.session.ssl", obj)); connection_manager_.stop_session(tag()); // At this point the connection is closed gracefully } void ssl_session::do_timeout(cyng::object obj) { // If this is true it means we timed out performing the shutdown if (eof_) { return; } // Start the timer again timer_.expires_at((std::chrono::steady_clock::time_point::max)()); //on_timer({}); on_timer(obj, boost::system::error_code()); do_eof(obj); } } } namespace cyng { namespace traits { #if defined(CYNG_LEGACY_MODE_ON) const char type_tag<node::https::plain_session>::name[] = "plain-session"; const char type_tag<node::https::ssl_session>::name[] = "ssl-session"; #endif } // traits } namespace std { size_t hash<node::https::plain_session>::operator()(node::https::plain_session const& s) const noexcept { return s.hash(); } bool equal_to<node::https::plain_session>::operator()(node::https::plain_session const& s1, node::https::plain_session const& s2) const noexcept { return s1.hash() == s2.hash(); } bool less<node::https::plain_session>::operator()(node::https::plain_session const& s1, node::https::plain_session const& s2) const noexcept { return s1.hash() < s2.hash(); } size_t hash<node::https::ssl_session>::operator()(node::https::ssl_session const& s) const noexcept { return s.hash(); } bool equal_to<node::https::ssl_session>::operator()(node::https::ssl_session const& s1, node::https::ssl_session const& s2) const noexcept { return s1.hash() == s2.hash(); } bool less<node::https::ssl_session>::operator()(node::https::ssl_session const& s1, node::https::ssl_session const& s2) const noexcept { return s1.hash() < s2.hash(); } }
25.674912
147
0.664052
solosTec
bc12089b2c6c25751953acfb23eec71c208d6e35
7,391
cpp
C++
moai/src/moaicore/MOAIFrameBufferTexture.cpp
jjimenezg93/ai-pathfinding
e32ae8be30d3df21c7e64be987134049b585f1e6
[ "MIT" ]
null
null
null
moai/src/moaicore/MOAIFrameBufferTexture.cpp
jjimenezg93/ai-pathfinding
e32ae8be30d3df21c7e64be987134049b585f1e6
[ "MIT" ]
null
null
null
moai/src/moaicore/MOAIFrameBufferTexture.cpp
jjimenezg93/ai-pathfinding
e32ae8be30d3df21c7e64be987134049b585f1e6
[ "MIT" ]
null
null
null
// Copyright (c) 2010-2011 Zipline Games, Inc. All Rights Reserved. // http://getmoai.com #include "pch.h" #include <moaicore/MOAIGfxDevice.h> #include <moaicore/MOAILogMessages.h> #include <moaicore/MOAIFrameBufferTexture.h> //================================================================// // local //================================================================// //----------------------------------------------------------------// /** @name init @text Initializes frame buffer. @in MOAIFrameBufferTexture self @in number width @in number height @out nil */ int MOAIFrameBufferTexture::_init ( lua_State* L ) { MOAI_LUA_SETUP ( MOAIFrameBufferTexture, "UNN" ) u32 width = state.GetValue < u32 >( 2, 0 ); u32 height = state.GetValue < u32 >( 3, 0 ); // TODO: fix me #ifdef MOAI_OS_ANDROID GLenum colorFormat = state.GetValue < GLenum >( 4, GL_RGB565 ); #else GLenum colorFormat = state.GetValue < GLenum >( 4, GL_RGBA8 ); #endif GLenum depthFormat = state.GetValue < GLenum >( 5, 0 ); GLenum stencilFormat = state.GetValue < GLenum >( 6, 0 ); self->Init ( width, height, colorFormat, depthFormat, stencilFormat ); return 0; } //================================================================// // MOAIFrameBufferTexture //================================================================// //----------------------------------------------------------------// void MOAIFrameBufferTexture::Init ( u32 width, u32 height, GLenum colorFormat, GLenum depthFormat, GLenum stencilFormat ) { this->Clear (); if ( MOAIGfxDevice::Get ().IsFramebufferSupported ()) { this->mWidth = width; this->mHeight = height; this->mColorFormat = colorFormat; this->mDepthFormat = depthFormat; this->mStencilFormat = stencilFormat; this->Load (); } else { MOAILog ( 0, MOAILogMessages::MOAITexture_NoFramebuffer ); } } //----------------------------------------------------------------// bool MOAIFrameBufferTexture::IsRenewable () { return true; } //----------------------------------------------------------------// bool MOAIFrameBufferTexture::IsValid () { return ( this->mGLFrameBufferID != 0 ); } //----------------------------------------------------------------// MOAIFrameBufferTexture::MOAIFrameBufferTexture () : mGLColorBufferID ( 0 ), mGLDepthBufferID ( 0 ), mGLStencilBufferID ( 0 ), mColorFormat ( 0 ), mDepthFormat ( 0 ), mStencilFormat ( 0 ) { RTTI_BEGIN RTTI_EXTEND ( MOAIFrameBuffer ) RTTI_EXTEND ( MOAITextureBase ) RTTI_END } //----------------------------------------------------------------// MOAIFrameBufferTexture::~MOAIFrameBufferTexture () { this->Clear (); } //----------------------------------------------------------------// void MOAIFrameBufferTexture::OnCreate () { if ( !( this->mWidth && this->mHeight && ( this->mColorFormat || this->mDepthFormat || this->mStencilFormat ))) { return; } this->mBufferWidth = this->mWidth; this->mBufferHeight = this->mHeight; // bail and retry (no error) if GL cannot generate buffer ID glGenFramebuffers ( 1, &this->mGLFrameBufferID ); if ( !this->mGLFrameBufferID ) return; if ( this->mColorFormat ) { glGenRenderbuffers( 1, &this->mGLColorBufferID ); glBindRenderbuffer ( GL_RENDERBUFFER, this->mGLColorBufferID ); glRenderbufferStorage ( GL_RENDERBUFFER, this->mColorFormat, this->mWidth, this->mHeight ); } if ( this->mDepthFormat ) { glGenRenderbuffers ( 1, &this->mGLDepthBufferID ); glBindRenderbuffer ( GL_RENDERBUFFER, this->mGLDepthBufferID ); glRenderbufferStorage ( GL_RENDERBUFFER, this->mDepthFormat, this->mWidth, this->mHeight ); } if ( this->mStencilFormat ) { glGenRenderbuffers ( 1, &this->mGLStencilBufferID ); glBindRenderbuffer ( GL_RENDERBUFFER, this->mGLStencilBufferID ); glRenderbufferStorage ( GL_RENDERBUFFER, this->mStencilFormat, this->mWidth, this->mHeight ); } glBindFramebuffer ( GL_FRAMEBUFFER, this->mGLFrameBufferID ); if ( this->mGLColorBufferID ) { glFramebufferRenderbuffer ( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, this->mGLColorBufferID ); } if ( this->mGLDepthBufferID ) { glFramebufferRenderbuffer ( GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, this->mGLDepthBufferID ); } if ( this->mGLStencilBufferID ) { glFramebufferRenderbuffer ( GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, this->mGLStencilBufferID ); } // TODO: handle error; clear GLenum status = glCheckFramebufferStatus ( GL_FRAMEBUFFER ); if ( status == GL_FRAMEBUFFER_COMPLETE ) { glGenTextures ( 1, &this->mGLTexID ); glBindTexture ( GL_TEXTURE_2D, this->mGLTexID ); glTexImage2D ( GL_TEXTURE_2D, 0, GL_RGBA, this->mWidth, this->mHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0 ); glFramebufferTexture2D ( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, this->mGLTexID, 0 ); // refresh tex params on next bind this->mIsDirty = true; } else { this->Clear (); } } //----------------------------------------------------------------// void MOAIFrameBufferTexture::OnDestroy () { if ( this->mGLFrameBufferID ) { MOAIGfxDevice::Get ().PushDeleter ( MOAIGfxDeleter::DELETE_FRAMEBUFFER, this->mGLFrameBufferID ); this->mGLFrameBufferID = 0; } if ( this->mGLColorBufferID ) { MOAIGfxDevice::Get ().PushDeleter ( MOAIGfxDeleter::DELETE_RENDERBUFFER, this->mGLColorBufferID ); this->mGLColorBufferID = 0; } if ( this->mGLDepthBufferID ) { MOAIGfxDevice::Get ().PushDeleter ( MOAIGfxDeleter::DELETE_RENDERBUFFER, this->mGLDepthBufferID ); this->mGLDepthBufferID = 0; } if ( this->mGLStencilBufferID ) { MOAIGfxDevice::Get ().PushDeleter ( MOAIGfxDeleter::DELETE_RENDERBUFFER, this->mGLStencilBufferID ); this->mGLStencilBufferID = 0; } this->MOAITextureBase::OnDestroy (); } //----------------------------------------------------------------// void MOAIFrameBufferTexture::OnInvalidate () { this->mGLFrameBufferID = 0; this->mGLColorBufferID = 0; this->mGLDepthBufferID = 0; this->mGLStencilBufferID = 0; this->MOAITextureBase::OnInvalidate (); } //----------------------------------------------------------------// void MOAIFrameBufferTexture::OnLoad () { } //----------------------------------------------------------------// void MOAIFrameBufferTexture::RegisterLuaClass ( MOAILuaState& state ) { MOAIFrameBuffer::RegisterLuaClass ( state ); MOAITextureBase::RegisterLuaClass ( state ); } //----------------------------------------------------------------// void MOAIFrameBufferTexture::RegisterLuaFuncs ( MOAILuaState& state ) { MOAIFrameBuffer::RegisterLuaFuncs ( state ); MOAITextureBase::RegisterLuaFuncs ( state ); luaL_Reg regTable [] = { { "init", _init }, { NULL, NULL } }; luaL_register ( state, 0, regTable ); } //----------------------------------------------------------------// void MOAIFrameBufferTexture::Render () { if ( this->Affirm ()) { MOAIFrameBuffer::Render (); } } //----------------------------------------------------------------// void MOAIFrameBufferTexture::SerializeIn ( MOAILuaState& state, MOAIDeserializer& serializer ) { MOAITextureBase::SerializeIn ( state, serializer ); } //----------------------------------------------------------------// void MOAIFrameBufferTexture::SerializeOut ( MOAILuaState& state, MOAISerializer& serializer ) { MOAITextureBase::SerializeOut ( state, serializer ); }
30.290984
123
0.593154
jjimenezg93
bc13edf112b8f9d50bc5a4620b431ef1d143ae80
498
cpp
C++
coding/if else condition.cpp
tusharkumar2005/developer
b371cedcd77b7926db7b6b7c7d6a144f48eed07b
[ "CC0-1.0" ]
1
2021-09-21T11:49:50.000Z
2021-09-21T11:49:50.000Z
coding/if else condition.cpp
tusharkumar2005/developer
b371cedcd77b7926db7b6b7c7d6a144f48eed07b
[ "CC0-1.0" ]
null
null
null
coding/if else condition.cpp
tusharkumar2005/developer
b371cedcd77b7926db7b6b7c7d6a144f48eed07b
[ "CC0-1.0" ]
null
null
null
#include <iostream> using namespace std; int main(){ int age; cout<<"enter your age"<<endl; cin>>age; /* if (age>=150){ cout<<"invalid age"; } else if (age >=18){ cout<<"you can vote"; } else { cout<<"sorry,you can not vote"; } */ switch (age){ case 12: cout<<"you are 10 year old"; break; case 18: cout<<"you are 18 year old"; break; default : cout<<"you are dis match"; break; } }
10.375
34
0.487952
tusharkumar2005
bc1fc1a8a367e5db98a479107f426247edc329ae
1,561
cpp
C++
scm_gl_core/src/scm/gl_classic/utilities/volume_generator_checkerboard.cpp
Nyran/schism
c2cdb8884e3e6714a3b291f0f754220b7f5cbc7b
[ "BSD-3-Clause" ]
10
2015-09-17T06:01:03.000Z
2019-10-23T07:10:20.000Z
scm_gl_core/src/scm/gl_classic/utilities/volume_generator_checkerboard.cpp
Nyran/schism
c2cdb8884e3e6714a3b291f0f754220b7f5cbc7b
[ "BSD-3-Clause" ]
5
2015-01-06T14:11:32.000Z
2016-12-12T10:26:53.000Z
scm_gl_core/src/scm/gl_classic/utilities/volume_generator_checkerboard.cpp
Nyran/schism
c2cdb8884e3e6714a3b291f0f754220b7f5cbc7b
[ "BSD-3-Clause" ]
15
2015-01-29T20:56:13.000Z
2020-07-02T19:03:20.000Z
// Copyright (c) 2012 Christopher Lux <[email protected]> // Distributed under the Modified BSD License, see license.txt. #include "volume_generator_checkerboard.h" #include <scm/core/math/math.h> #include <exception> #include <new> namespace scm { namespace gl_classic { bool volume_generator_checkerboard::generate_float_volume(unsigned dim_x, unsigned dim_y, unsigned dim_z, unsigned components, boost::scoped_array<float>& buffer) { if (dim_x < 1 || dim_y < 1 || dim_z < 1 || components < 1) { return (false); } try { buffer.reset(new float[dim_x * dim_y * dim_z * components]); } catch (std::bad_alloc&) { return (false); } float val; unsigned offset_dst; for (unsigned z = 0; z < dim_z; z++) { for (unsigned y = 0; y < dim_y; y++) { for (unsigned x = 0; x < dim_x; x++) { val = float(scm::math::sign(-int((x+y+z) % 2))); offset_dst = x * components + y * dim_x * components + z * dim_x * dim_y * components; for (unsigned c = 0; c < components; c++) { buffer[offset_dst + c] = val; } } } } return (true); } } // namespace gl_classic } // namespace scm
28.381818
93
0.467008
Nyran
bc22c3e20e78c425c89b39a2d6243c4cae9717a0
4,390
cpp
C++
Atom.AI_Contest/main/Distance.cpp
mocxi/Arduino
3133f7416238c448347ef39bb259ac7dcf016d19
[ "BSD-3-Clause" ]
null
null
null
Atom.AI_Contest/main/Distance.cpp
mocxi/Arduino
3133f7416238c448347ef39bb259ac7dcf016d19
[ "BSD-3-Clause" ]
null
null
null
Atom.AI_Contest/main/Distance.cpp
mocxi/Arduino
3133f7416238c448347ef39bb259ac7dcf016d19
[ "BSD-3-Clause" ]
null
null
null
#include "Distance.h" #include <DebugUtils.h> #if USE_IR #include "IR_Distance.h" #endif //Init int avr_front , avr_right , avr_left, avr_TOTAL = 0; //int angle, delta_angle; NewPing sonar_front (PING_PIN_FRONT, PING_PIN_FRONT, MAX_DISTANCE); NewPing sonar_right (PING_PIN_RIGHT, PING_PIN_RIGHT, MAX_DISTANCE); NewPing sonar_left (PING_PIN_LEFT, PING_PIN_LEFT, MAX_DISTANCE); distance* distance::GetInstance() { static distance* _distance = NULL; if(!_distance) { _distance = new distance(); } return _distance; } distance::distance(): isFollowLeft(false), isWallOnLeft(false), isWallOnRight(false), isWallInFront(false), isSlowSpeed(false), m_isMinFront(false) { Last_active_sensor = millis(); Last_distance_check = millis(); } const int& distance::getAvrTotal() { return avr_TOTAL; } void distance::init() { d_front = get_distance(sonar_front, MIN_DISTANCE, MAX_DISTANCE); DEBUG_PRINTLN("Setup d_front!"); d_right = get_distance(sonar_right, MIN_DISTANCE, MAX_DISTANCE); DEBUG_PRINTLN("Setup d_right!"); d_left = get_distance(sonar_left, MIN_DISTANCE, MAX_DISTANCE); DEBUG_PRINTLN("Setup d_left!"); for (uint8_t i = 0; i < DISTANCE_STACK_MAX; i++) { arr_front_stack[i] = d_front + 10 ; arr_right_stack[i] = d_right + 10; arr_left_stack[i] = d_left + 10; } #if USE_IR IR_DISTANCE->init(); #endif isFollowLeft = (d_right > d_left); } uint8_t distance::getAvrDistance(uint8_t stack[], uint8_t max_count) { int sum = 0; for(uint8_t i = 0; i < max_count; i++) { sum += stack[i]; } return sum/max_count; } void distance::updateDistanceStack() { arr_front_stack[g_DistanceStackIndex] = d_front; arr_right_stack[g_DistanceStackIndex] = d_right; arr_left_stack[g_DistanceStackIndex] = d_left; g_DistanceStackIndex++; if (g_DistanceStackIndex >= DISTANCE_STACK_MAX) g_DistanceStackIndex = 0; avr_front = getAvrDistance(arr_front_stack,DISTANCE_STACK_MAX); avr_right = getAvrDistance(arr_right_stack,DISTANCE_STACK_MAX); avr_left = getAvrDistance(arr_left_stack,DISTANCE_STACK_MAX); avr_TOTAL = avr_front + avr_right + avr_left ; // Debug Log + DEBUG_PRINT(">>>>>>>> g_DistanceStackIndex "); DEBUG_PRINTLN(g_DistanceStackIndex); DEBUG_PRINTLN("updateDistanceStack ______________ BEGIN"); DEBUG_PRINT("avr_front "); DEBUG_PRINT(avr_front); DEBUG_PRINT(" avr_right "); DEBUG_PRINT(avr_right); DEBUG_PRINT(" avr_left "); DEBUG_PRINT(avr_left); DEBUG_PRINT(" [[avr_TOTAL]] "); DEBUG_PRINTLN(avr_TOTAL); DEBUG_PRINT("d_front "); DEBUG_PRINT(d_front); DEBUG_PRINT(" d_right "); DEBUG_PRINT(d_right); DEBUG_PRINT(" d_left "); DEBUG_PRINT(d_left); DEBUG_PRINT(" <<d_TOTAL>> "); DEBUG_PRINTLN(d_front + d_right + d_left); DEBUG_PRINTLN(" ______________ END "); // Debug Log - } int distance::ping_mean_cm(NewPing& sonar, int N, int max_cm_distance) { int sum_dist = 0; int temp_dist = 0; int i = 0; unsigned long t; while(i<=N) { t = micros(); temp_dist = sonar.ping_cm(max_cm_distance); if(temp_dist > 0 && temp_dist <= max_cm_distance) { sum_dist += temp_dist; i++; } else { if(N==1) { return 0; //error result every ping } N--; } //add delay between ping (hardware limitation) if(i<=N && (micros() - t) < PING_MEAN_DELAY) { delay((PING_MEAN_DELAY + t - micros())/1000); } } return (sum_dist/N); } int distance::get_distance(NewPing sonar , int min , int max , int last_distance) { int d = ping_mean_cm(sonar, GET_DISTANCE_COUNTS, MAX_DISTANCE); if (last_distance > 0 && (d < min || d > max)) { d = last_distance; } else { if (d < min) d = min; if (d > max) d = max; } return d; } void distance::updateDistance() { #if USE_IR IR_DISTANCE->updateIR_distance(); #endif if(Last_distance_check < (millis()-CHECK_DISTANCE_DELAY)) { updateDistanceStack(); d_front = get_distance(sonar_front, MIN_DISTANCE, MAX_DISTANCE, MAX_DISTANCE );// phphat the 4th param should be previous value , not MAX_DISTANCE !!! d_right = get_distance(sonar_right, MIN_DISTANCE, MAX_DISTANCE, MAX_DISTANCE); d_left = get_distance(sonar_left, MIN_DISTANCE, MAX_DISTANCE, MAX_DISTANCE); Last_distance_check = millis(); } }
23.475936
153
0.680182
mocxi
bc22fe2cac68d6912490bbd1c953818a646c3f94
2,110
cpp
C++
nau/src/nau/material/materialGroup.cpp
Khirion/nau
47a2ad8e0355a264cd507da5e7bba1bf7abbff95
[ "MIT" ]
29
2015-09-16T22:28:30.000Z
2022-03-11T02:57:36.000Z
nau/src/nau/material/materialGroup.cpp
Khirion/nau
47a2ad8e0355a264cd507da5e7bba1bf7abbff95
[ "MIT" ]
1
2017-03-29T13:32:58.000Z
2017-03-31T13:56:03.000Z
nau/src/nau/material/materialGroup.cpp
Khirion/nau
47a2ad8e0355a264cd507da5e7bba1bf7abbff95
[ "MIT" ]
10
2015-10-15T14:20:15.000Z
2022-02-17T10:37:29.000Z
#include "nau/material/materialGroup.h" #include "nau.h" #include "nau/geometry/vertexData.h" #include "nau/render/opengl/glMaterialGroup.h" #include "nau/math/vec3.h" #include "nau/clogger.h" using namespace nau::material; using namespace nau::render; using namespace nau::render::opengl; using namespace nau::math; std::shared_ptr<MaterialGroup> MaterialGroup::Create(IRenderable *parent, std::string materialName) { #ifdef NAU_OPENGL return std::shared_ptr<MaterialGroup>(new GLMaterialGroup(parent, materialName)); #endif } MaterialGroup::MaterialGroup() : m_Parent (0), m_MaterialName ("default") { //ctor } MaterialGroup::MaterialGroup(IRenderable *parent, std::string materialName) : m_Parent(parent), m_MaterialName(materialName) { //ctor } MaterialGroup::~MaterialGroup() { } void MaterialGroup::setParent(std::shared_ptr<nau::render::IRenderable> &parent) { this->m_Parent = parent.get(); } void MaterialGroup::setMaterialName (std::string name) { this->m_MaterialName = name; m_IndexData->setName(getName()); } std::string & MaterialGroup::getName() { m_Name = m_Parent->getName() + ":" + m_MaterialName; return m_Name; } const std::string& MaterialGroup::getMaterialName () { return m_MaterialName; } std::shared_ptr<nau::geometry::IndexData>& MaterialGroup::getIndexData (void) { if (!m_IndexData) { m_IndexData = IndexData::Create(getName()); } return (m_IndexData); } size_t MaterialGroup::getIndexOffset(void) { return 0; } size_t MaterialGroup::getIndexSize(void) { if (!m_IndexData) { return 0; } return m_IndexData->getIndexSize(); } void MaterialGroup::setIndexList (std::shared_ptr<std::vector<unsigned int>> &indices) { if (!m_IndexData) { m_IndexData.reset(); m_IndexData = IndexData::Create(getName()); } m_IndexData->setIndexData (indices); } unsigned int MaterialGroup::getNumberOfPrimitives(void) { return RENDERER->getNumberOfPrimitives(this); } IRenderable& MaterialGroup::getParent () { return *(this->m_Parent); } void MaterialGroup::updateIndexDataName() { m_IndexData->setName(getName()); }
16.10687
83
0.729858
Khirion
bc2e1cac9ed2df3f1065af958a3136f3415fa07e
1,866
hpp
C++
src/cc/Books/ElementsOfProgrammingInterviews/ch8.hpp
nuggetwheat/study
1e438a995c3c6ce783af9ae6a537c349afeedbb8
[ "MIT" ]
null
null
null
src/cc/Books/ElementsOfProgrammingInterviews/ch8.hpp
nuggetwheat/study
1e438a995c3c6ce783af9ae6a537c349afeedbb8
[ "MIT" ]
null
null
null
src/cc/Books/ElementsOfProgrammingInterviews/ch8.hpp
nuggetwheat/study
1e438a995c3c6ce783af9ae6a537c349afeedbb8
[ "MIT" ]
null
null
null
#ifndef Books_ElementsOfProgrammingInterviews_ch8_hpp #define Books_ElementsOfProgrammingInterviews_ch8_hpp #include "reference/ch8.hpp" #include <cstdlib> #include <memory> #include <string> #include <vector> namespace study { extern std::shared_ptr<reference::ListNode<int>> MergeTwoSortedLists(std::shared_ptr<reference::ListNode<int>> l1, std::shared_ptr<reference::ListNode<int>> l2); extern std::shared_ptr<reference::ListNode<int>> ReverseLinkedList(const std::shared_ptr<reference::ListNode<int>> &list); extern std::shared_ptr<reference::ListNode<int>> HasCycle(const std::shared_ptr<reference::ListNode<int>> &list); extern std::shared_ptr<reference::ListNode<int>> OverlappingNoCycleLists(const std::shared_ptr<reference::ListNode<int>> &l1, const std::shared_ptr<reference::ListNode<int>> &l2); extern void DeleteFromList(const std::shared_ptr<reference::ListNode<int>> &list); extern std::shared_ptr<reference::ListNode<int>> RemoveKthLast(std::shared_ptr<reference::ListNode<int>> &list, int k); extern void RemoveDuplicates(const std::shared_ptr<reference::ListNode<int>> &list); extern void CyclicallyRightShiftList(std::shared_ptr<reference::ListNode<int>> &list, int k); extern void EvenOddMerge(std::shared_ptr<reference::ListNode<int>> &list); extern bool IsPalindrome(std::shared_ptr<reference::ListNode<int>> &list); extern void PivotList(std::shared_ptr<reference::ListNode<int>> &list, int k); extern std::shared_ptr<reference::ListNode<int>> AddNumbers(const std::shared_ptr<reference::ListNode<int>> &l1, const std::shared_ptr<reference::ListNode<int>> &l2); } #endif // Books_ElementsOfProgrammingInterviews_ch8_hpp
40.565217
127
0.700429
nuggetwheat
bc2f0548b0855345014ca64feeb3ad37eadb0d7f
10,012
cc
C++
build/X86_MESI_Two_Level/python/m5/internal/param_X86ACPIRSDP.py.cc
hoho20000000/gem5-fy
b59f6feed22896d6752331652c4d8a41a4ca4435
[ "BSD-3-Clause" ]
null
null
null
build/X86_MESI_Two_Level/python/m5/internal/param_X86ACPIRSDP.py.cc
hoho20000000/gem5-fy
b59f6feed22896d6752331652c4d8a41a4ca4435
[ "BSD-3-Clause" ]
1
2020-08-20T05:53:30.000Z
2020-08-20T05:53:30.000Z
build/X86_MESI_Two_Level/python/m5/internal/param_X86ACPIRSDP.py.cc
hoho20000000/gem5-fy
b59f6feed22896d6752331652c4d8a41a4ca4435
[ "BSD-3-Clause" ]
null
null
null
#include "sim/init.hh" namespace { const uint8_t data_m5_internal_param_X86ACPIRSDP[] = { 120,156,197,88,109,115,220,72,17,238,209,190,121,109,175,189, 142,223,242,226,196,162,136,47,11,199,217,192,85,224,224,66, 138,92,46,64,170,14,39,37,135,74,98,168,82,201,171,177, 45,103,87,218,90,141,237,236,149,205,7,28,94,254,6,31, 169,226,27,63,16,250,233,145,20,197,113,114,87,5,89,214, 222,217,209,168,103,166,123,158,167,123,122,166,75,217,103,158, 191,191,116,137,210,127,40,162,144,255,21,189,32,234,41,218, 118,72,105,135,194,121,58,168,81,114,133,84,88,163,87,68, 219,21,210,21,58,227,74,149,126,95,161,248,83,43,181,80, 72,53,46,146,106,241,11,30,123,130,94,84,165,201,161,209, 36,233,26,109,215,233,105,60,79,85,221,160,131,73,74,26, 164,248,19,243,204,207,70,109,202,122,76,208,118,147,165,86, 89,106,82,164,230,69,42,123,219,196,91,233,17,54,41,156, 164,87,172,249,20,133,83,162,197,52,133,211,82,105,81,216, 146,202,12,133,51,82,153,205,135,111,211,246,92,94,191,84, 170,207,151,234,11,165,250,98,169,190,84,170,47,75,125,150, 244,28,69,151,41,186,66,209,85,218,85,20,182,49,29,175, 196,243,237,107,164,171,20,173,208,246,10,105,254,191,70,103, 138,151,101,174,212,227,186,244,184,84,244,184,33,61,86,105, 123,149,52,255,223,176,61,38,104,171,179,200,176,69,255,230, 79,135,97,35,51,205,197,145,30,166,81,18,251,81,188,155, 68,14,222,55,80,0,228,46,138,10,127,235,252,189,15,180, 135,36,80,179,238,140,246,41,143,160,136,251,132,14,102,8, 43,116,229,84,225,33,170,208,9,87,170,180,43,47,162,106, 38,113,202,248,205,209,9,143,94,163,19,105,217,122,26,95, 167,170,169,11,64,115,2,144,125,205,157,241,154,225,33,86, 187,198,211,110,138,222,6,122,175,139,118,230,18,23,254,32, 24,6,125,255,217,103,63,185,119,255,241,67,111,235,203,199, 29,168,111,154,176,161,63,72,134,166,23,237,152,9,72,250, 113,208,215,190,111,38,249,97,200,221,76,100,216,110,83,229, 199,131,36,138,13,140,236,165,102,24,13,76,171,232,237,247, 147,240,176,167,205,20,183,60,148,150,7,195,97,50,236,96, 85,60,20,6,197,224,197,158,129,142,125,76,209,129,114,82, 164,191,227,98,99,63,233,107,46,226,189,209,225,198,158,238, 223,254,100,119,180,177,115,24,245,194,13,214,218,255,237,131, 173,135,254,147,227,196,255,74,31,233,222,198,96,100,88,116, 163,127,123,131,53,210,195,56,224,166,243,22,174,179,16,108, 79,143,163,61,63,83,115,95,247,6,122,8,171,211,25,76, 173,166,213,188,186,161,42,106,78,205,168,168,158,131,137,181, 105,229,96,254,51,3,211,201,92,151,241,84,25,184,14,157, 74,5,136,117,0,38,48,172,0,58,182,147,129,217,83,116, 230,208,31,42,16,56,229,178,202,158,230,22,64,46,88,79, 179,67,53,232,148,209,174,1,203,175,87,100,168,9,25,202, 161,19,46,25,230,42,157,178,59,179,40,55,113,121,208,164, 100,134,20,63,68,77,208,89,197,76,222,103,39,117,166,65, 181,160,129,165,47,172,9,163,33,22,221,3,115,59,147,121, 107,146,174,15,2,179,239,181,114,132,120,153,4,233,205,36, 182,96,238,70,113,152,131,107,233,177,27,245,152,30,30,214, 80,70,19,177,94,18,20,98,64,184,219,75,82,45,20,147, 177,189,89,8,66,122,119,32,195,96,86,232,35,157,67,157, 118,65,39,166,153,29,17,26,96,180,113,80,196,131,115,47, 96,138,171,66,136,54,83,162,206,132,232,48,33,108,109,197, 105,169,89,181,25,97,45,187,181,204,205,171,57,59,254,69, 22,17,69,7,142,248,230,137,68,5,150,102,220,196,55,79, 196,243,241,246,7,164,140,147,181,179,243,51,188,104,189,196, 125,132,51,76,30,150,189,3,87,22,52,65,130,26,49,43, 45,226,204,36,75,17,193,189,134,30,24,202,193,20,85,26, 44,243,224,19,32,195,9,101,172,57,171,48,43,88,35,118, 101,142,19,220,188,196,243,254,73,232,150,197,10,33,129,217, 143,210,228,216,122,56,234,18,238,182,216,105,30,143,30,237, 28,232,174,73,87,185,225,121,114,232,118,131,56,78,140,27, 132,161,27,24,142,0,59,135,70,167,174,73,220,181,180,3, 32,189,171,57,143,138,241,70,3,237,73,197,146,39,140,186, 134,99,203,188,60,136,99,166,218,48,13,246,147,48,229,118, 116,221,211,198,107,163,7,150,57,17,5,132,37,62,68,49, 45,203,193,119,239,229,26,216,72,83,207,137,147,234,222,174, 4,175,110,47,72,83,31,26,72,187,208,13,86,31,5,189, 67,45,163,167,60,30,43,132,170,213,97,44,49,233,50,140, 201,109,23,131,226,36,14,71,172,95,212,253,20,83,95,22, 34,182,56,38,181,212,18,127,155,106,81,53,152,142,13,181, 236,116,171,25,249,138,189,102,9,134,147,160,174,50,224,153, 140,103,28,73,58,142,4,2,177,9,228,245,190,143,26,58, 123,55,81,172,161,248,8,197,173,220,236,15,109,123,235,188, 237,247,49,159,35,6,119,43,153,105,133,111,249,111,248,214, 76,201,183,206,224,35,39,178,171,70,149,146,127,84,96,126, 50,149,123,148,248,31,131,206,254,7,97,241,36,222,108,203, 126,128,73,55,189,43,80,227,59,92,220,90,75,111,185,150, 117,238,126,144,186,113,242,154,234,46,94,218,160,6,162,123, 43,88,249,18,149,247,74,84,246,92,72,128,199,222,119,81, 84,223,181,244,223,27,255,210,239,217,165,255,53,230,155,206, 184,54,35,28,155,82,93,16,5,120,52,114,16,182,184,50, 90,6,8,229,213,95,230,141,239,105,188,194,123,153,32,128, 237,172,101,183,51,217,19,109,202,152,71,181,168,150,87,234, 192,97,183,66,75,217,46,149,98,27,25,12,147,151,35,55, 217,117,13,229,42,221,89,75,215,215,210,207,57,176,184,119, 95,175,120,22,68,134,122,128,32,96,131,2,214,197,68,49, 63,99,168,7,47,187,90,54,18,121,242,125,27,3,108,50, 227,103,27,20,131,35,104,56,57,26,18,5,57,163,65,240, 27,11,20,147,5,20,48,229,49,38,155,20,28,42,106,153, 189,190,132,2,190,21,160,0,154,253,149,36,129,85,244,23, 194,26,243,74,102,46,46,158,147,123,207,60,196,145,197,156, 168,11,119,37,39,243,10,39,11,25,236,54,131,150,108,54, 217,46,197,105,201,223,74,241,164,216,69,42,89,106,83,246, 158,106,225,61,2,208,183,218,41,170,111,58,16,22,159,61, 13,98,226,42,54,103,188,249,102,108,146,60,166,34,209,221, 124,104,116,38,236,52,62,52,122,254,26,27,196,227,235,106, 193,177,12,17,242,252,20,197,103,133,3,171,188,237,3,42, 183,122,62,128,150,54,15,223,70,159,103,208,160,42,58,207, 54,204,13,254,229,49,30,110,221,243,239,63,250,234,209,230, 150,143,225,242,58,134,149,140,23,31,108,142,95,128,61,63, 230,138,230,83,156,34,45,145,245,149,36,192,40,29,112,224, 204,81,124,2,229,148,226,149,156,64,237,65,211,179,41,133, 48,55,255,74,252,64,220,121,35,110,151,22,176,96,129,5, 24,197,203,177,120,32,48,190,211,11,250,59,97,112,247,5, 166,194,124,221,220,227,156,92,247,118,89,119,248,138,122,135, 250,242,248,121,110,195,209,88,18,215,59,36,199,75,171,187, 56,71,152,116,37,80,60,217,215,110,95,247,119,248,200,186, 31,13,220,221,94,176,39,184,84,50,219,30,229,182,25,1, 182,228,207,18,78,82,228,9,155,137,219,77,98,142,138,135, 93,147,12,221,80,243,73,64,135,238,39,174,132,84,55,74, 221,96,135,223,6,93,99,121,255,166,235,74,198,21,12,247, 82,73,174,94,28,163,58,54,96,125,62,164,71,156,102,246, 169,200,45,236,30,34,145,7,41,150,36,144,214,141,120,243, 225,19,161,25,217,32,118,15,197,109,20,27,84,222,151,63, 52,150,63,231,145,15,48,5,150,171,174,174,57,77,199,204, 89,207,205,197,30,163,95,250,182,179,254,253,219,56,171,174, 210,118,45,119,217,58,36,117,3,39,76,148,77,108,1,219, 147,121,227,148,148,211,210,216,202,27,103,164,156,149,198,118, 222,56,39,229,37,105,156,167,236,2,107,65,26,23,105,123, 137,194,186,180,44,35,54,52,254,203,216,32,206,53,54,183, 50,255,203,144,224,253,226,255,162,186,119,151,178,188,225,93, 225,64,149,237,106,217,190,145,202,243,102,89,246,77,107,134, 156,202,47,95,196,71,191,59,212,129,209,22,163,155,99,50, 84,130,138,157,248,248,181,143,23,73,83,45,183,233,87,133, 77,103,146,49,141,22,4,186,252,230,13,215,125,114,243,105, 36,69,69,14,219,182,119,107,178,8,190,147,165,177,84,44, 70,189,88,12,220,16,198,250,216,127,107,65,108,162,10,193, 96,48,208,113,232,253,16,125,126,68,229,132,83,100,198,194, 8,196,179,63,82,145,195,76,115,134,185,192,121,204,219,158, 136,208,88,50,84,224,108,23,206,55,46,96,133,193,127,206, 25,220,1,227,94,7,109,239,11,20,18,166,139,8,237,61, 40,16,89,185,144,158,137,238,251,81,136,35,207,251,5,56, 155,178,23,14,242,152,103,77,231,100,135,250,40,146,75,96, 12,247,13,34,24,16,155,81,222,96,174,94,44,159,134,70, 134,123,207,107,12,133,85,192,195,59,228,94,190,127,152,151, 229,97,240,32,196,16,143,14,117,79,27,253,54,143,13,208, 207,14,182,161,230,157,62,25,241,57,170,33,141,220,199,247, 199,183,57,222,207,8,145,226,154,142,55,71,85,231,237,113, 81,201,159,211,172,55,149,228,29,231,46,229,75,109,245,162, 205,165,252,24,49,74,61,180,24,208,41,75,4,68,27,191, 124,207,47,119,131,150,93,114,105,153,167,10,32,162,28,48, 55,131,190,189,126,146,247,217,81,52,181,46,47,23,164,200, 164,188,143,81,124,82,240,246,103,232,125,157,139,254,237,245, 220,240,245,243,134,63,145,219,210,254,109,243,209,57,193,76, 100,107,148,126,169,211,238,147,96,135,15,180,71,26,57,154, 89,123,223,152,229,14,230,218,133,146,91,81,223,94,248,73, 234,81,126,31,14,3,174,47,158,107,77,245,48,10,122,209, 215,250,253,214,60,131,53,88,159,252,181,193,109,240,249,41, 177,92,197,147,228,67,230,99,250,166,163,139,32,55,212,123, 81,202,35,203,176,197,16,89,52,6,119,222,225,170,229,190, 99,35,179,61,121,216,139,136,187,114,239,240,27,46,218,184, 229,155,104,170,6,126,103,249,215,225,72,237,84,212,164,154, 81,53,254,109,243,239,156,51,221,110,86,155,77,150,155,154, 86,229,191,85,118,129,73,103,117,190,169,254,3,9,41,59, 195, }; EmbeddedPython embedded_m5_internal_param_X86ACPIRSDP( "m5/internal/param_X86ACPIRSDP.py", "/home/hongyu/gem5-fy/build/X86_MESI_Two_Level/python/m5/internal/param_X86ACPIRSDP.py", "m5.internal.param_X86ACPIRSDP", data_m5_internal_param_X86ACPIRSDP, 2465, 7288); } // anonymous namespace
58.209302
92
0.6669
hoho20000000
bc30785f43a2059b7a6e9c87e32c84d9a2157470
1,228
cpp
C++
aws-cpp-sdk-shield/source/model/ProtectionGroupArbitraryPatternLimits.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-01-05T18:20:03.000Z
2022-01-05T18:20:03.000Z
aws-cpp-sdk-shield/source/model/ProtectionGroupArbitraryPatternLimits.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-shield/source/model/ProtectionGroupArbitraryPatternLimits.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-12-30T04:25:33.000Z
2021-12-30T04:25:33.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/shield/model/ProtectionGroupArbitraryPatternLimits.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace Shield { namespace Model { ProtectionGroupArbitraryPatternLimits::ProtectionGroupArbitraryPatternLimits() : m_maxMembers(0), m_maxMembersHasBeenSet(false) { } ProtectionGroupArbitraryPatternLimits::ProtectionGroupArbitraryPatternLimits(JsonView jsonValue) : m_maxMembers(0), m_maxMembersHasBeenSet(false) { *this = jsonValue; } ProtectionGroupArbitraryPatternLimits& ProtectionGroupArbitraryPatternLimits::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("MaxMembers")) { m_maxMembers = jsonValue.GetInt64("MaxMembers"); m_maxMembersHasBeenSet = true; } return *this; } JsonValue ProtectionGroupArbitraryPatternLimits::Jsonize() const { JsonValue payload; if(m_maxMembersHasBeenSet) { payload.WithInt64("MaxMembers", m_maxMembers); } return payload; } } // namespace Model } // namespace Shield } // namespace Aws
19.806452
108
0.762215
perfectrecall
bc308fc74a58e7d9e4929425df42b0800ce878d4
2,010
cpp
C++
aoapcbac2nd/example9-4_unidirectionaltsp.cpp
aoibird/pc
b72c0b10117f95d45e2e7423614343b5936b260a
[ "MIT" ]
null
null
null
aoapcbac2nd/example9-4_unidirectionaltsp.cpp
aoibird/pc
b72c0b10117f95d45e2e7423614343b5936b260a
[ "MIT" ]
null
null
null
aoapcbac2nd/example9-4_unidirectionaltsp.cpp
aoibird/pc
b72c0b10117f95d45e2e7423614343b5936b260a
[ "MIT" ]
null
null
null
// UVa 116 #include <cctype> #include <cmath> #include <cstdio> #include <cstdlib> #include <cstring> #include <iostream> #include <algorithm> using namespace std; const int MAXR = 10+10; const int MAXC = 100+10; const int INF = 1 << 30; int F[MAXR][MAXC]; int dp[MAXR][MAXC]; int nxt[MAXR][MAXC]; int R, C; void print_table() { for (int i = 0; i < R; i++) { for (int j = 0; j < C; j++) printf("%d(%d) ", dp[i][j], nxt[i][j]); printf("\n"); } printf("\n"); } void solve() { for (int r = 0; r < R; r++) for (int c = 0; c < C; c++) dp[r][c] = INF; for (int r = 0; r < R; r++) dp[r][C-1] = F[r][C-1]; for (int c = C-2; c >= 0; c--) { for (int r = 0; r < R; r++) { int up = (r-1+R)%R; int down = (r+1)%R; if (dp[r][c] > dp[up][c+1] + F[r][c] || (dp[r][c] == dp[up][c+1] + F[r][c] && nxt[r][c] > up)) { dp[r][c] = dp[up][c+1] + F[r][c]; nxt[r][c] = up; } if (dp[r][c] > dp[r][c+1] + F[r][c] || (dp[r][c] == dp[r][c+1] + F[r][c] && nxt[r][c] > r)) { dp[r][c] = dp[r][c+1] + F[r][c]; nxt[r][c] = r; } if (dp[r][c] > dp[down][c+1] + F[r][c] || (dp[r][c] == dp[down][c+1] + F[r][c] && nxt[r][c] > down)) { dp[r][c] = dp[down][c+1] + F[r][c]; nxt[r][c] = down; } } } // print_table(); int row, ans = INF; for (int r = 0; r < R; r++) if (dp[r][0] < ans) { ans = dp[r][0]; row = r; } printf("%d", row+1); for (int i = 0; i < C-1; i++) { printf(" %d", nxt[row][i]+1); row = nxt[row][i]; } printf("\n%d\n", ans); } int main() { while (scanf("%d%d", &R, &C) == 2) { memset(dp, 0, sizeof(dp)); for (int i = 0; i < R; i++) for (int j = 0; j < C; j++) scanf("%d", &F[i][j]); // printf("INF = %d\n", INF); solve(); } }
26.103896
79
0.374129
aoibird
bc343ef1acf95d594fd021c9dc93956ae9b51c7d
2,807
cpp
C++
[Lib]__RanClientUI/Sources/InnerUI/ItemBankWindow.cpp
yexiuph/RanOnline
7f7be07ef740c8e4cc9c7bef1790b8d099034114
[ "Apache-2.0" ]
null
null
null
[Lib]__RanClientUI/Sources/InnerUI/ItemBankWindow.cpp
yexiuph/RanOnline
7f7be07ef740c8e4cc9c7bef1790b8d099034114
[ "Apache-2.0" ]
null
null
null
[Lib]__RanClientUI/Sources/InnerUI/ItemBankWindow.cpp
yexiuph/RanOnline
7f7be07ef740c8e4cc9c7bef1790b8d099034114
[ "Apache-2.0" ]
null
null
null
#include "pch.h" #include "ItemBankWindow.h" #include "ItemBankPage.h" #include "../[Lib]__EngineUI/Sources/BasicButton.h" #include "GLGaeaClient.h" #include "../[Lib]__EngineUI/Sources/BasicTextBox.h" #include "InnerInterface.h" #include "ModalCallerID.h" #include "../[Lib]__Engine/Sources/DxTools/DxFontMan.h" #include "ModalWindow.h" #include "UITextControl.h" #include "GameTextControl.h" #include "BasicTextButton.h" #ifdef _DEBUG #define new DEBUG_NEW #endif CItemBankWindow::CItemBankWindow () : m_pPage ( NULL ) { } CItemBankWindow::~CItemBankWindow () { } void CItemBankWindow::CreateSubControl () { // CreateTextButton ( "ITEMBANK_REFRESH_BUTTON", ITEMBANK_REFRESH_BUTTON, const_cast<char*>(ID2GAMEWORD("ITEMBANK_REFRESH_BUTTON")) ); CItemBankPage* pItemBankPage = new CItemBankPage; pItemBankPage->CreateSub ( this, "ITEMBANK_PAGE", UI_FLAG_DEFAULT, ITEMBANK_PAGE ); pItemBankPage->CreateSubControl (); RegisterControl ( pItemBankPage ); m_pPage = pItemBankPage; } CBasicTextButton* CItemBankWindow::CreateTextButton ( char* szButton, UIGUID ControlID, char* szText ) { const int nBUTTONSIZE = CBasicTextButton::SIZE14; CBasicTextButton* pTextButton = new CBasicTextButton; pTextButton->CreateSub ( this, "BASIC_TEXT_BUTTON14", UI_FLAG_XSIZE, ControlID ); pTextButton->CreateBaseButton ( szButton, nBUTTONSIZE, CBasicButton::CLICK_FLIP, szText ); RegisterControl ( pTextButton ); return pTextButton; } void CItemBankWindow::InitItemBank () { m_pPage->UnLoadItemPage (); GLCharacter* pCharacter = GLGaeaClient::GetInstance().GetCharacter(); m_pPage->LoadItemPage ( pCharacter->m_cInvenCharged ); } void CItemBankWindow::ClearItemBank() { m_pPage->UnLoadItemPage (); } void CItemBankWindow::TranslateUIMessage ( UIGUID ControlID, DWORD dwMsg ) { CUIWindowEx::TranslateUIMessage ( ControlID, dwMsg ); if ( ET_CONTROL_TITLE == ControlID || ET_CONTROL_TITLE_F == ControlID ) { if ( (dwMsg & UIMSG_LB_DUP) && CHECK_MOUSE_IN ( dwMsg ) ) { CInnerInterface::GetInstance().SetDefaultPosInterface( ITEMBANK_WINDOW ); return; } } else if ( ITEMBANK_PAGE == ControlID ) { if ( CHECK_MOUSE_IN ( dwMsg ) ) { int nPosX, nPosY; m_pPage->GetItemIndex ( &nPosX, &nPosY ); //CDebugSet::ToView ( 1, 3, "[itembank] Page:%d %d / %d", nPosX, nPosY ); if ( nPosX < 0 || nPosY < 0 ) return ; SINVENITEM sInvenItem = m_pPage->GetItem ( nPosX, nPosY ); if ( sInvenItem.sItemCustom.sNativeID != NATIVEID_NULL () ) { CInnerInterface::GetInstance().SHOW_ITEM_INFO ( sInvenItem.sItemCustom, FALSE, FALSE, FALSE, sInvenItem.wPosX, sInvenItem.wPosY ); } if ( dwMsg & UIMSG_LB_UP ) { GLGaeaClient::GetInstance().GetCharacter()->ReqChargedItemTo ( static_cast<WORD>(nPosX), static_cast<WORD>(nPosY) ); return ; } } } }
27.519608
134
0.728892
yexiuph