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
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
8a1e6d8d630308d7c6df2b85177f21ab9f00efc7
11,647
cpp
C++
test/performance-regression/full-apps/qmcpack/src/QMCWaveFunctions/Experimental/Bspline3DSet.cpp
JKChenFZ/hclib
50970656ac133477c0fbe80bb674fe88a19d7177
[ "BSD-3-Clause" ]
55
2015-07-28T01:32:58.000Z
2022-02-27T16:27:46.000Z
test/performance-regression/full-apps/qmcpack/src/QMCWaveFunctions/Experimental/Bspline3DSet.cpp
JKChenFZ/hclib
50970656ac133477c0fbe80bb674fe88a19d7177
[ "BSD-3-Clause" ]
66
2015-06-15T20:38:19.000Z
2020-08-26T00:11:43.000Z
test/performance-regression/full-apps/qmcpack/src/QMCWaveFunctions/Experimental/Bspline3DSet.cpp
JKChenFZ/hclib
50970656ac133477c0fbe80bb674fe88a19d7177
[ "BSD-3-Clause" ]
26
2015-10-26T22:11:51.000Z
2021-03-02T22:09:15.000Z
///////////////////////////////////////////////////////////////// // (c) Copyright 2007- Jeongnim Kim ////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////// // Modified by Jeongnim Kim for qmcpack // National Center for Supercomputing Applications & // Materials Computation Center // University of Illinois, Urbana-Champaign // Urbana, IL 61801 // e-mail: jnkim@ncsa.uiuc.edu // // Supported by // National Center for Supercomputing Applications, UIUC // Materials Computation Center, UIUC ////////////////////////////////////////////////////////////////// // -*- C++ -*- /** @file Bspline3DSet.cpp * @brief Implement derived classes from Bspline3DBase */ #include "QMCWaveFunctions/Bspline3DSet.h" namespace qmcplusplus { //////////////////////////////////////////////////////////// //Implementation of Bspline3DSet_Ortho //////////////////////////////////////////////////////////// SPOSetBase* Bspline3DSet_Ortho::makeClone() const { return new Bspline3DSet_Ortho(*this); } void Bspline3DSet_Ortho::evaluate(const ParticleSet& e, int iat, ValueVector_t& vals) { if(bKnots.Find(e.R[iat][0],e.R[iat][1],e.R[iat][2])) { #pragma ivdep for(int j=0; j<NumOrbitals; j++) vals[j]=bKnots.evaluate(*P[j]); } else { vals=0.0; } } void Bspline3DSet_Ortho::evaluate(const ParticleSet& e, int iat, ValueVector_t& vals, GradVector_t& grads, ValueVector_t& laps) { if(bKnots.FindAll(e.R[iat][0],e.R[iat][1],e.R[iat][2])) { #pragma ivdep for(int j=0; j<NumOrbitals; j++) vals[j]=bKnots.evaluate(*P[j],grads[j],laps[j]); } else { vals=0.0; grads=0.0; laps=0.0; } } void Bspline3DSet_Ortho::evaluate_notranspose(const ParticleSet& e, int first, int last, ValueMatrix_t& vals, GradMatrix_t& grads, ValueMatrix_t& laps) { for(int iat=first,i=0; iat<last; iat++,i++) { if(bKnots.FindAll(e.R[iat][0],e.R[iat][1],e.R[iat][2])) { #pragma ivdep for(int j=0; j<OrbitalSetSize; j++) vals(i,j)=bKnots.evaluate(*P[j],grads(i,j),laps(i,j)); } else { for(int j=0; j<OrbitalSetSize; j++) { vals(i,j)=0.0; grads(i,j)=0.0; laps(i,j)=0.0; } } } } //////////////////////////////////////////////////////////// //Implementation of Bspline3DSet_Gen //////////////////////////////////////////////////////////// SPOSetBase* Bspline3DSet_Gen::makeClone() const { return new Bspline3DSet_Gen(*this); } void Bspline3DSet_Gen::evaluate(const ParticleSet& e, int iat, ValueVector_t& vals) { PosType ru(Lattice.toUnit(e.R[iat])); if(bKnots.Find(ru[0],ru[1],ru[2])) for(int j=0; j<OrbitalSetSize; j++) vals[j]=bKnots.evaluate(*P[j]); else vals=0.0; } void Bspline3DSet_Gen::evaluate(const ParticleSet& e, int iat, ValueVector_t& vals, GradVector_t& grads, ValueVector_t& laps) { PosType ru(Lattice.toUnit(e.R[iat])); if(bKnots.FindAll(ru[0],ru[1],ru[2])) { TinyVector<ValueType,3> gu; Tensor<ValueType,3> hess; #pragma ivdep for(int j=0; j<OrbitalSetSize; j++) { vals[j]=bKnots.evaluate(*P[j],gu,hess); grads[j]=dot(Lattice.G,gu); laps[j]=trace(hess,GGt); } } else { vals=0.0; grads=0.0; laps=0.0; } } void Bspline3DSet_Gen::evaluate_notranspose(const ParticleSet& e, int first, int last, ValueMatrix_t& vals, GradMatrix_t& grads, ValueMatrix_t& laps) { for(int iat=first,i=0; iat<last; iat++,i++) { PosType ru(Lattice.toUnit(e.R[iat])); if(bKnots.FindAll(ru[0],ru[1],ru[2])) { TinyVector<ValueType,3> gu; Tensor<ValueType,3> hess; #pragma ivdep for(int j=0; j<OrbitalSetSize; j++) { vals(i,j)=bKnots.evaluate(*P[j],gu,hess); grads(i,j)=dot(Lattice.G,gu); laps(i,j)=trace(hess,GGt); } } else { for(int j=0; j<OrbitalSetSize; j++) { vals(i,j)=0.0; grads(i,j)=0.0; laps(i,j)=0.0; } //for(int j=0; j<OrbitalSetSize; j++) vals(j,i)=0.0; //std::copy(grads[i],grads[i]+OrbitalSetSize,0.0); //std::copy(laps[i],laps[i]+OrbitalSetSize,0.0); } } } //////////////////////////////////////////////////////////// //Implementation of Bspline3DSet_Ortho_Trunc //////////////////////////////////////////////////////////// SPOSetBase* Bspline3DSet_Ortho_Trunc::makeClone() const { return new Bspline3DSet_Ortho_Trunc(*this); } void Bspline3DSet_Ortho_Trunc::evaluate(const ParticleSet& e, int iat, ValueVector_t& vals) { PosType r(e.R[iat]); bKnots.Find(r[0],r[1],r[2]); #pragma ivdep for(int j=0; j<Centers.size(); j++) { if(bKnots.getSep2(r[0]-Centers[j][0],r[1]-Centers[j][1],r[2]-Centers[j][2])>Rcut2) vals[j]=0.0;//numeric_limits<T>::epsilon(); else vals[j]=bKnots.evaluate(*P[j]); } } void Bspline3DSet_Ortho_Trunc::evaluate(const ParticleSet& e, int iat, ValueVector_t& vals, GradVector_t& grads, ValueVector_t& laps) { PosType r(e.R[iat]); bKnots.FindAll(r[0],r[1],r[2]); #pragma ivdep for(int j=0; j<Centers.size(); j++) { if(bKnots.getSep2(r[0]-Centers[j][0],r[1]-Centers[j][1],r[2]-Centers[j][2])>Rcut2) { vals[j]=0.0;//numeric_limits<T>::epsilon(); grads[j]=0.0; laps[j]=0.0; } else vals[j]=bKnots.evaluate(*P[j],grads[j],laps[j]); } } void Bspline3DSet_Ortho_Trunc::evaluate_notranspose(const ParticleSet& e, int first, int last, ValueMatrix_t& vals, GradMatrix_t& grads, ValueMatrix_t& laps) { for(int iat=first,i=0; iat<last; iat++,i++) { PosType r(e.R[iat]); bKnots.FindAll(r[0],r[1],r[2]); #pragma ivdep for(int j=0; j<Centers.size(); j++) { if(bKnots.getSep2(r[0]-Centers[j][0],r[1]-Centers[j][1],r[2]-Centers[j][2])>Rcut2) { vals(i,j)=0.0; //numeric_limits<T>::epsilon(); grads(i,j)=0.0; laps(i,j)=0.0; } else { vals(i,j)=bKnots.evaluate(*P[j],grads(i,j),laps(i,j)); } } } } //////////////////////////////////////////////////////////// //Implementation of Bspline3DSet_Gen_Trunc //////////////////////////////////////////////////////////// SPOSetBase* Bspline3DSet_Gen_Trunc::makeClone() const { return new Bspline3DSet_Gen_Trunc(*this); } void Bspline3DSet_Gen_Trunc::evaluate(const ParticleSet& e, int iat, ValueVector_t& vals) { PosType r(e.R[iat]); PosType ru(Lattice.toUnit(r)); bKnots.Find(ru[0],ru[1],ru[2]); #pragma ivdep for(int j=0; j<Centers.size(); j++) { if(bKnots.getSep2(r[0]-Centers[j][0],r[1]-Centers[j][1],r[2]-Centers[j][2])>Rcut2) vals[j]=0.0;//numeric_limits<T>::epsilon(); else vals[j]=bKnots.evaluate(*P[j]); } } void Bspline3DSet_Gen_Trunc::evaluate(const ParticleSet& e, int iat, ValueVector_t& vals, GradVector_t& grads, ValueVector_t& laps) { PosType r(e.R[iat]); PosType ru(Lattice.toUnit(r)); bKnots.FindAll(ru[0],ru[1],ru[2]); TinyVector<ValueType,3> gu; Tensor<ValueType,3> hess; #pragma ivdep for(int j=0; j<Centers.size(); j++) { if(bKnots.getSep2(r[0]-Centers[j][0],r[1]-Centers[j][1],r[2]-Centers[j][2])>Rcut2) { vals[j]=0.0;//numeric_limits<T>::epsilon(); grads[j]=0.0; laps[j]=0.0; } else { vals[j]=bKnots.evaluate(*P[j],gu,hess); grads[j]=dot(Lattice.G,gu); laps[j]=trace(hess,GGt); //vals[j]=bKnots.evaluate(*P[j],grads[j],laps[j]); } } } void Bspline3DSet_Gen_Trunc::evaluate_notranspose(const ParticleSet& e, int first, int last, ValueMatrix_t& vals, GradMatrix_t& grads, ValueMatrix_t& laps) { for(int iat=first,i=0; iat<last; iat++,i++) { PosType r(e.R[iat]); PosType ru(Lattice.toUnit(r)); bKnots.FindAll(ru[0],ru[1],ru[2]); TinyVector<ValueType,3> gu; Tensor<ValueType,3> hess; #pragma ivdep for(int j=0; j<Centers.size(); j++) { if(bKnots.getSep2(r[0]-Centers[j][0],r[1]-Centers[j][1],r[2]-Centers[j][2])>Rcut2) { vals(i,j)=0.0; //numeric_limits<T>::epsilon(); grads(i,j)=0.0; laps(i,j)=0.0; } else { vals(i,j)=bKnots.evaluate(*P[j],gu,hess); grads(i,j)=dot(Lattice.G,gu); laps(i,j)=trace(hess,GGt); //vals(j,i)=bKnots.evaluate(*P[j],grads(i,j),laps(i,j)); } } } } #if defined(QMC_COMPLEX) //////////////////////////////////////////////////////////// //Implementation of Bspline3DSet_Twist //////////////////////////////////////////////////////////// SPOSetBase* Bspline3DSet_Twist::makeClone() const { return new Bspline3DSet_Twist(*this); } void Bspline3DSet_Twist::evaluate(const ParticleSet& e, int iat, ValueVector_t& vals) { PosType r(e.R[iat]); PosType ru(Lattice.toUnit(r)); if(bKnots.Find(ru[0],ru[1],ru[2])) { RealType phi(dot(TwistAngle,r)); ValueType phase(std::cos(phi),std::sin(phi)); #pragma ivdep for(int j=0; j <OrbitalSetSize; j++) vals[j]=phase*bKnots.evaluate(*P[j]); } else vals=0.0; } void Bspline3DSet_Twist::evaluate(const ParticleSet& e, int iat, ValueVector_t& vals, GradVector_t& grads, ValueVector_t& laps) { PosType r(e.R[iat]); PosType ru(Lattice.toUnit(r)); if(bKnots.FindAll(ru[0],ru[1],ru[2])) { RealType phi(dot(TwistAngle,r)); RealType c=std::cos(phi),s=std::sin(phi); ValueType phase(c,s); //ik e^{i{\bf k}\cdot {\bf r}} GradType dk(ValueType(-TwistAngle[0]*s,TwistAngle[0]*c), ValueType(-TwistAngle[1]*s,TwistAngle[1]*c), ValueType(-TwistAngle[2]*s,TwistAngle[2]*c)); TinyVector<ValueType,3> gu; Tensor<ValueType,3> hess; #pragma ivdep for(int j=0; j<OrbitalSetSize; j++) { ValueType v= bKnots.evaluate(*P[j],gu,hess); GradType g= dot(Lattice.G,gu); ValueType l=trace(hess,GGt); vals[j]=phase*v; grads[j]=v*dk+phase*g; laps[j]=phase*(mK2*v+l)+2.0*dot(dk,g); } } else { vals=0.0; grads=0.0; laps=0.0; } } void Bspline3DSet_Twist::evaluate_notranspose(const ParticleSet& e, int first, int last, ValueMatrix_t& vals, GradMatrix_t& grads, ValueMatrix_t& laps) { for(int iat=first,i=0; iat<last; iat++,i++) { PosType r(e.R[iat]); PosType ru(Lattice.toUnit(r)); if(bKnots.FindAll(ru[0],ru[1],ru[2])) { RealType phi(dot(TwistAngle,r)); RealType c=std::cos(phi),s=std::sin(phi); ValueType phase(c,s); GradType dk(ValueType(-TwistAngle[0]*s,TwistAngle[0]*c), ValueType(-TwistAngle[1]*s,TwistAngle[1]*c), ValueType(-TwistAngle[2]*s,TwistAngle[2]*c)); TinyVector<ValueType,3> gu; Tensor<ValueType,3> hess; #pragma ivdep for(int j=0; j<OrbitalSetSize; j++) { ValueType v=bKnots.evaluate(*P[j],gu,hess); GradType g=dot(Lattice.G,gu); ValueType l=trace(hess,GGt); vals(i,j)=phase*v; grads(i,j)=v*dk+phase*g; laps(i,j)=phase*(mK2*v+l)+2.0*dot(dk,g); } } else { for(int j=0; j<OrbitalSetSize; j++) { vals(i,j)=0.0; grads(i,j)=0.0; laps(i,j)=0.0; } } } } #endif } /*************************************************************************** * $RCSfile$ $Author: jnkim $ * $Revision: 2013 $ $Date: 2007-05-22 16:47:09 -0500 (Tue, 22 May 2007) $ * $Id: TricubicBsplineSet.h 2013 2007-05-22 21:47:09Z jnkim $ ***************************************************************************/
27.665083
102
0.54675
JKChenFZ
8a1f108fb7792e52e56938e92c576707b6dd88aa
674
cpp
C++
examples/TailExample.cpp
sbeanie/Glasgow-MicroStream
eb0e214b0c16b22ff59b1633db4f76be380948d4
[ "Apache-2.0" ]
1
2019-06-17T20:52:56.000Z
2019-06-17T20:52:56.000Z
examples/TailExample.cpp
sbeanie/Glasgow-MicroStream
eb0e214b0c16b22ff59b1633db4f76be380948d4
[ "Apache-2.0" ]
null
null
null
examples/TailExample.cpp
sbeanie/Glasgow-MicroStream
eb0e214b0c16b22ff59b1633db4f76be380948d4
[ "Apache-2.0" ]
null
null
null
#include "Stream.hpp" using namespace glasgow_ustream; int main (int, char**) { void (*print_int_list) (std::list<int>) = [] (std::list<int> values) { std::cout << "Tail stream outputted: ["; for (auto &val : values) { std::cout << val << ","; } std::cout << "]" << std::endl; }; // Create a topology with networking disabled. Topology topology = Topology(true); FixedDataSource<int>* source = topology.addFixedDataSource(std::list<int>{1,2,3,4,5,6,7}); TailStream<int>* tail_stream = source->tail(3); tail_stream->sink(print_int_list); topology.run_with_threads(); topology.shutdown(); }
28.083333
94
0.60089
sbeanie
8a1fdcc115ffb19336a2570347aa0ceb87fbdb93
1,296
cpp
C++
cpp/library/benchmark/main.cpp
KaiserLancelot/Cpp-Primer
a4791a6765f0b6c864e8881e6a5328e2a3d68974
[ "MIT" ]
2
2019-12-21T00:53:47.000Z
2020-01-01T10:36:30.000Z
cpp/library/benchmark/main.cpp
KaiserLancelot/Cpp-Primer
a4791a6765f0b6c864e8881e6a5328e2a3d68974
[ "MIT" ]
null
null
null
cpp/library/benchmark/main.cpp
KaiserLancelot/Cpp-Primer
a4791a6765f0b6c864e8881e6a5328e2a3d68974
[ "MIT" ]
null
null
null
#include <algorithm> #include <cstdint> #include <random> #include <vector> #include <benchmark/benchmark.h> void dense_range(benchmark::State& state) { for (auto _ : state) { std::vector<int> v(state.range(0), state.range(0)); // 下面两个防止优化 benchmark::DoNotOptimize(v.data()); // TODO ClobberMemory ??? benchmark::ClobberMemory(); } } // 从范围中挑选几个数运行 benchmark, 默认为 8 的倍数(8, 64, 512) // 可以用 RangeMultiplier 修改默认倍数 BENCHMARK(dense_range)->Range(8, 512); // 对范围中每一个数运行 benchmark BENCHMARK(dense_range)->DenseRange(0, 256, 128); void sort_vector(benchmark::State& state) { std::default_random_engine e{std::random_device{}()}; for (auto _ : state) { state.PauseTiming(); std::vector<std::int32_t> v; v.reserve(state.range(0)); for (std::int32_t i{0}; i < state.range(0); ++i) { v.push_back(e()); } state.ResumeTiming(); std::sort(std::begin(v), std::end(v)); } state.SetComplexityN(state.range(0)); } BENCHMARK(sort_vector) ->RangeMultiplier(2) ->Range(1 << 10, 1 << 18) // 计算时间复杂度 ->Complexity(); // --benchmark_format=<console|json|csv> // --benchmark_out=<filename> // 禁用/启用 CPU频率缩放 // sudo cpupower frequency-set --governor performance // sudo cpupower frequency-set --governor powersave BENCHMARK_MAIN();
24
55
0.660494
KaiserLancelot
8a21344249d71c7972478fc4dfe504ab2b43f7f2
653
hpp
C++
include/yukihttp/mime.hpp
Yuki-cpp/yuki-http
07fc0d194ab528f4554aef25813c565a9fce6542
[ "MIT" ]
null
null
null
include/yukihttp/mime.hpp
Yuki-cpp/yuki-http
07fc0d194ab528f4554aef25813c565a9fce6542
[ "MIT" ]
null
null
null
include/yukihttp/mime.hpp
Yuki-cpp/yuki-http
07fc0d194ab528f4554aef25813c565a9fce6542
[ "MIT" ]
null
null
null
#pragma once #include <string> #include <vector> #include <memory> namespace yuki::http { class part; class mime { friend class request; public: mime() = default; mime(const mime&) = delete; mime& operator=(const mime&) = delete; mime(mime&&) = default; mime& operator=(mime && ) = default; ~mime() = default; void add_data_part(const std::string & name, const std::string & data); void add_file_part(const std::string & name, const std::string & content, const std::string & file_name); void add_file_part(const std::string & name, const std::string & path); private: std::vector<std::unique_ptr<yuki::http::part>> m_parts; }; }
17.648649
106
0.684533
Yuki-cpp
8a248b27f73ccad15cd8c5fd65e5ea7c0760425c
10,240
cc
C++
optickscore/Animator.cc
seriksen/opticks
2173ea282bdae0bbd1abf4a3535bede334413ec1
[ "Apache-2.0" ]
1
2020-05-13T06:55:49.000Z
2020-05-13T06:55:49.000Z
optickscore/Animator.cc
seriksen/opticks
2173ea282bdae0bbd1abf4a3535bede334413ec1
[ "Apache-2.0" ]
null
null
null
optickscore/Animator.cc
seriksen/opticks
2173ea282bdae0bbd1abf4a3535bede334413ec1
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2019 Opticks Team. All Rights Reserved. * * This file is part of Opticks * (see https://bitbucket.org/simoncblyth/opticks). * * 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 <cfloat> #include <cstring> #include <cmath> #include <cstdio> #include <cassert> #include <sstream> #include "OpticksConst.hh" #include "Animator.hh" #include "PLOG.hh" const char* Animator::OFF_ = "OFF" ; const char* Animator::SLOW32_ = "SLOW32" ; const char* Animator::SLOW16_ = "SLOW16" ; const char* Animator::SLOW8_ = "SLOW8" ; const char* Animator::SLOW4_ = "SLOW4" ; const char* Animator::SLOW2_ = "SLOW2" ; const char* Animator::NORM_ = "NORM" ; const char* Animator::FAST_ = "FAST" ; const char* Animator::FAST2_ = "FAST2" ; const char* Animator::FAST4_ = "FAST4" ; const int Animator::period_low = 25 ; const int Animator::period_high = 10000 ; Animator::Animator(float* target, unsigned int period, float low, float high) : m_mode(OFF), m_restrict(NUM_MODE), m_low(low), m_high(high), m_count(0), m_index(0), m_target(target), m_increment(1), m_cmd_slots(8), m_cmd_index(0), m_cmd_offset(0), m_cmd_tranche(0) { m_period[OFF] = 0 ; m_period[SLOW32] = period*32 ; m_period[SLOW16] = period*16 ; m_period[SLOW8] = period*8 ; m_period[SLOW4] = period*4 ; m_period[SLOW2] = period*2 ; m_period[NORM] = period ; m_period[FAST] = period/2 ; m_period[FAST2] = period/4 ; m_period[FAST4] = period/8 ; m_fractions[OFF] = NULL ; m_fractions[SLOW32] = make_fractions(m_period[SLOW32]) ; m_fractions[SLOW16] = make_fractions(m_period[SLOW16]) ; m_fractions[SLOW8] = make_fractions(m_period[SLOW8]) ; m_fractions[SLOW4] = make_fractions(m_period[SLOW4]) ; m_fractions[SLOW2] = make_fractions(m_period[SLOW2]) ; m_fractions[NORM] = make_fractions(m_period[NORM]) ; m_fractions[FAST] = make_fractions(m_period[FAST]) ; m_fractions[FAST2] = make_fractions(m_period[FAST2]) ; m_fractions[FAST4] = make_fractions(m_period[FAST4]) ; m_cmd[OFF] = "T0" ; m_cmd[SLOW32] = "T1" ; m_cmd[SLOW16] = "T2" ; m_cmd[SLOW8] = "T3" ; m_cmd[SLOW4] = "T4" ; m_cmd[SLOW2] = "T5" ; m_cmd[NORM] = "T6" ; m_cmd[FAST] = "T7" ; m_cmd[FAST2] = "T8" ; m_cmd[FAST4] = "T9" ; } /** SLOW32 128*32 4096 128*16 2048 SLOW8 128*8 1024 128*4 512 SLOW2 128*2 256 NORM 128 128 FAST 128/2 64 FAST2 128/4 32 FAST4 128/8 16 **/ Animator::Mode_t Animator::getMode() { return m_mode ; } bool Animator::isModeChanged(Mode_t prior) { return m_mode != prior ; } int* Animator::getModePtr() { int* mode = (int*)&m_mode ; // address of enum cast to int* return mode ; } bool Animator::isSlowEnabled() { return SLOW2 < m_restrict ; } bool Animator::isNormEnabled() { return NORM < m_restrict ; } bool Animator::isFastEnabled() { return FAST < m_restrict ; } float Animator::getLow() { return m_low ; } float Animator::getHigh() { return m_high ; } float* Animator::getTarget() { return m_target ; } float* Animator::make_fractions(unsigned int num) { float low(0.f); float high(1.f); float* frac = new float[num] ; float step_ = (high - low)/float(num-1) ; // from i=0 to i=num-1 for(unsigned int i=0 ; i < num ; i++) frac[i] = low + step_*i ; return frac ; // In [13]: np.linspace(0.,1.,11) // Out[13]: array([ 0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1. ]) } void Animator::setModeRestrict(Mode_t restrict_) { m_restrict = restrict_ ; } void Animator::setMode(Mode_t mode) { if(mode == m_mode) return ; float fraction = getFractionForValue(*m_target); m_mode = mode ; LOG(info) << description() ; modeTransition(fraction); } unsigned int Animator::getNumMode() { return m_restrict > 0 ? m_restrict : NUM_MODE ; } void Animator::commandMode(const char* cmd) { //LOG(info) << cmd ; assert(strlen(cmd) == 2); assert( cmd[0] == 'T' || cmd[0] == 'A' ); int mode = (int)cmd[1] - (int)'0' ; if( mode > -1 && mode < NUM_MODE ) { setMode((Mode_t)mode) ; } else { LOG(info) << cmd ; setMode(OFF); home(); } } void Animator::nextMode(unsigned int modifiers) { if(modifiers & OpticksConst::e_shift) m_increment = -m_increment ; bool option = 0 != (modifiers & OpticksConst::e_option) ; bool control = 0 != (modifiers & OpticksConst::e_control) ; //bool command = 0 != (modifiers & OpticksConst::e_command) ; unsigned int num_mode = getNumMode(); int mode = ( option ? m_mode - 1 : m_mode + 1) % num_mode ; if(mode < 0) mode = num_mode - 1 ; if(control) mode = OFF ; setMode((Mode_t)mode) ; } void Animator::modeTransition(float fraction) { // adjust the count to new raster, to avoid animation jumps if(m_mode == OFF) return ; int count = find_closest_index(fraction); #ifdef ANIMATOR_DEBUG //printf("Animator::modeTransition fraction %10.3f closest count %d \n", fraction, count ); #endif m_count = count ; } bool Animator::isActive() { return m_mode != OFF ; } void Animator::setTarget(float* target) { m_target = target ; } void Animator::scrub_to(float , float , float , float dy) // Interactor:K scrub_mode { // hmm maybe easier to make separate mostly transparent ImGui window with just the time scrubber // to avoid wheel reinvention if(m_mode == OFF) return ; float val = getValue(); val += 30.f*dy ; LOG(info) << "Animator::scrub_to" << " dy " << dy << " val " << val ; setTargetValue(val); } void Animator::setTargetValue(float val) { if(val < m_low) val = m_high ; else if( val > m_high ) val = m_low ; float f = getFractionForValue(val); setFraction(f); } void Animator::setFraction(float f) { *m_target = m_low + (m_high-m_low)*f ; } bool Animator::isBump() { return m_count > 0 && m_count % m_period[m_mode] == 0 ; } unsigned int Animator::getIndex() { m_index = m_count % m_period[m_mode] ; // modulo, responsible for the sawtooth return m_index ; } float Animator::getFraction() { unsigned int index = getIndex(); return m_fractions[m_mode][index] ; } float Animator::getValue() { return m_low + (m_high-m_low)*getFraction() ; } float Animator::getFractionForValue(float value) { return (value - m_low)/(m_high - m_low) ; } float Animator::getFractionFromTarget() { return getFractionForValue(*m_target); } bool Animator::step(bool& bump, unsigned& cmd_index, unsigned& cmd_offset ) { bool st = step(bump) ; if(!st) return st ; m_cmd_tranche = m_period[m_mode]/m_cmd_slots ; // NB keep animator_period a suitable power of two, such as 128 m_cmd_index = m_index/m_cmd_tranche ; assert( m_cmd_index < m_cmd_slots ) ; m_cmd_offset = m_index - m_cmd_index*m_cmd_tranche ; assert( m_cmd_offset < m_cmd_tranche ) ; cmd_index = m_cmd_index ; cmd_offset = m_cmd_offset ; return st ; } bool Animator::step(bool& bump) { // still seeing occasional jumps, but cannot reproduce if(m_mode == OFF) return false ; bump = isBump(); #ifdef ANIMATOR_DEBUG if(bump) printf("Animator::step bump m_count %d \n", m_count ); #endif float value = getValue() ; m_count += m_increment ; // NB increment only after getting the value (which depends on m_count) and bump *m_target = value ; return true ; } void Animator::reset() { m_count = 0 ; } void Animator::home() { m_count = 0 ; bool bump(false); step(bump); } unsigned int Animator::find_closest_index(float f ) { float fmin(FLT_MAX); int ic(-1); unsigned int period = m_period[m_mode]; //printf("Animator::find_closest_index f %10.3f period %d \n", f, period); for(unsigned int i=0 ; i < period ; i++) { float ifrac = m_fractions[m_mode][i]; float diff = fabs(f - ifrac) ; //printf(" i %d ifrac %10.4f diff %10.4f ic %d \n", i, ifrac, diff, ic ) ; if( diff < fmin ) { fmin = diff ; ic = i ; } } return ic ; } char* Animator::description() { snprintf(m_desc, 64, " %2s:%5s %d/%d/%10.4f", getModeCmd(), getModeName() , m_index, m_period[m_mode], *m_target ); return m_desc ; } void Animator::Summary(const char* msg) { LOG(info) << msg << description() ; } const char* Animator::getModeCmd() const { return m_cmd[m_mode] ; } const char* Animator::getModeName() const { const char* mode(NULL); switch(m_mode) { case OFF:mode = OFF_ ; break ; case SLOW32:mode = SLOW32_ ; break ; case SLOW16:mode = SLOW16_ ; break ; case SLOW8:mode = SLOW8_ ; break ; case SLOW4:mode = SLOW4_ ; break ; case SLOW2:mode = SLOW2_ ; break ; case NORM:mode = NORM_ ; break ; case FAST:mode = FAST_ ; break ; case FAST2:mode = FAST2_ ; break ; case FAST4:mode = FAST4_ ; break ; case NUM_MODE:assert(0) ; break ; } return mode ; } std::string Animator::desc() const { std::stringstream ss ; ss << "Animator " << getModeName() << " ci:" << m_cmd_index << " co:" << m_cmd_offset << " ct:" << m_cmd_tranche ; return ss.str(); }
21.927195
119
0.604883
seriksen
8a257902f7bf9c601eaabe904b47d194e7b42e7d
989
hh
C++
include/rediswraps/utils.hh
woldaker/hiredis-cpp
545c8479944a678777c17a39614cecfa1dc35cd8
[ "BSD-3-Clause" ]
1
2020-07-04T23:35:59.000Z
2020-07-04T23:35:59.000Z
include/rediswraps/utils.hh
woldaker/hiredis-cpp
545c8479944a678777c17a39614cecfa1dc35cd8
[ "BSD-3-Clause" ]
null
null
null
include/rediswraps/utils.hh
woldaker/hiredis-cpp
545c8479944a678777c17a39614cecfa1dc35cd8
[ "BSD-3-Clause" ]
null
null
null
#ifndef REDISWRAPS_UTILS_HH #define REDISWRAPS_UTILS_HH #include <string> #include <type_traits> namespace rediswraps { namespace utils { template<typename Token, typename ArgConstructibleFromString = typename std::enable_if< std::is_constructible<std::string, Token>::value >::type, typename Dummy = void > std::string ToString(Token const &item); template<typename Token, typename ArgNotConstructibleFromString = typename std::enable_if< !std::is_constructible<std::string, Token>::value >::type > std::string ToString(Token const &item); template<typename TargetType, typename ReturnsNonVoidDefaultConstructible = typename std::enable_if< std::is_default_constructible<TargetType>::value && !std::is_void<TargetType>::value >::type > TargetType Convert(std::string const &target); std::string const ReadFile(std::string const &filepath); } // namespace utils } // namespace rediswraps #include <rediswraps/utils.inl> #endif
23.547619
74
0.741153
woldaker
8a2618e032296ee4aba1a4ab8f883534321b5833
78,168
cc
C++
CryoMEM/cacti/io.cc
SNU-HPCS/CryoModel
07a3fbe3f3d44c7960b5aed562a90e204014eea0
[ "MIT" ]
2
2021-05-26T12:32:46.000Z
2021-12-15T13:10:37.000Z
CryoMEM/cacti/io.cc
SNU-HPCS/CryoModel
07a3fbe3f3d44c7960b5aed562a90e204014eea0
[ "MIT" ]
1
2022-03-02T01:49:20.000Z
2022-03-18T10:37:59.000Z
CryoMEM/cacti/io.cc
SNU-HPCS/CryoModel
07a3fbe3f3d44c7960b5aed562a90e204014eea0
[ "MIT" ]
null
null
null
/***************************************************************************** * CACTI 7.0 * SOFTWARE LICENSE AGREEMENT * Copyright 2015 Hewlett-Packard Development Company, L.P. * All Rights Reserved * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders 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 <iostream> #include <fstream> #include <string> #include <cstring> #include <cassert> #include <boost/archive/text_oarchive.hpp> #include "io.h" #include "version_cacti.h" #include "const.h" #include "input_parameter.h" #include "dynamic_parameter.h" #include "global_cacti_input.h" #include "uca_org_t.h" #include "mem_array.h" #include "wire.h" using namespace std; double scan_single_input_double(char* line, const char* name, const char* unit_name, bool print) { double temp; char unit[300]; memset(unit, 0, 300); sscanf(&line[strlen(name)], "%*[ \t]%s%*[ \t]%lf", unit, &temp); if (print) cout << name << ": " << temp << " " << unit << endl; return temp; } double scan_five_input_double(char* line, const char* name, const char* unit_name, int flavor, bool print) { double temp[5]; char unit[300]; memset(unit, 0, 300); sscanf( &line[strlen(name)], "%*[ \t]%s%*[ \t]%lf%*[ \t]%lf%*[ \t]%lf%*[ \t]%lf%*[ \t]%lf", unit, &(temp[0]), &(temp[1]), &(temp[2]), &(temp[3]), &(temp[4])); if (print) cout << name << "[" << flavor << "]: " << temp[flavor] << " " << unit << endl; return temp[flavor]; } void scan_five_input_double_temperature(char* line, const char* name, const char* unit_name, int flavor, unsigned int temperature, bool print, double& result) { double temp[5]; unsigned int thermal_temp; char unit[300]; memset(unit, 0, 300); sscanf( &line[strlen(name)], "%*[ \t]%s%*[ \t]%u%*[ \t]%lf%*[ \t]%lf%*[ \t]%lf%*[ \t]%lf%*[ \t]%lf", unit, &thermal_temp, &(temp[0]), &(temp[1]), &(temp[2]), &(temp[3]), &(temp[4])); if (thermal_temp == (temperature - 300)) { if (print) cout << name << ": " << temp[flavor] << " " << unit << endl; result = temp[flavor]; } } double scan_input_double_inter_type(char* line, const char* name, const char* unit_name, int proj_type, int tech_flavor, bool print) { assert(proj_type < NUMBER_INTERCONNECT_PROJECTION_TYPES); int index = proj_type * NUMBER_WIRE_TYPES + tech_flavor; // cout << name << " index: " << index << endl; double temp[8]; char unit[300]; memset(unit, 0, 300); sscanf( &line[strlen(name)], "%*[ \t]%s%*[ \t]%lf%*[ \t]%lf%*[ \t]%lf%*[ \t]%lf%*[ \t]%lf%*[ \t]%lf%*[ \t]%lf%*[ \t]%lf", unit, &(temp[0]), &(temp[1]), &(temp[2]), &(temp[3]), &(temp[4]), &(temp[5]), &(temp[6]), &(temp[7])); if (print) cout << name << " " << temp[index] << " " << unit << endl; return temp[index]; } void scan_five_input_double_mem_type(char* line, const char* name, const char* unit_name, int flavor, int cell_type, bool print, double& result) { double temp[5]; int cell_type_temp; char unit[300]; memset(unit, 0, 300); sscanf( &line[strlen(name)], "%*[ \t]%s%*[ \t]%d%*[ \t]%lf%*[ \t]%lf%*[ \t]%lf%*[ \t]%lf%*[ \t]%lf", unit, &cell_type_temp, &(temp[0]), &(temp[1]), &(temp[2]), &(temp[3]), &(temp[4])); if (cell_type_temp == cell_type) { if (print) cout << name << ": " << temp[flavor] << " " << unit << endl; result = temp[flavor]; } } double scan_input_double_tsv_type(char* line, const char* name, const char* unit_name, int proj_type, int tsv_type, bool print) { assert(proj_type < NUMBER_INTERCONNECT_PROJECTION_TYPES); int index = proj_type * NUMBER_TSV_TYPES + tsv_type; double temp[6]; char unit[300]; memset(unit, 0, 300); sscanf( &line[strlen(name)], "%*[ \t]%s%*[ \t]%lf%*[ \t]%lf%*[ \t]%lf%*[ \t]%lf%*[ \t]%lf%*[ \t]%lf", unit, &(temp[0]), &(temp[1]), &(temp[2]), &(temp[3]), &(temp[4]), &(temp[5])); if (print) cout << name << ": " << temp[index] << " " << unit << endl; return temp[index]; } void output_data_csv(const uca_org_t& fin_res, string fn) { // TODO: the csv output should remain fstream file(fn.c_str(), ios::in); bool print_index = file.fail(); file.close(); file.open(fn.c_str(), ios::out | ios::app); if (file.fail() == true) { cerr << "File out.csv could not be opened successfully" << endl; } else { if (print_index == true) { file << "Tech node (nm), "; file << "Capacity (bytes), "; file << "Number of banks, "; file << "Associativity, "; file << "Output width (bits), "; file << "Access time (ns), "; file << "Random cycle time (ns), "; // file << "Multisubbank interleave cycle time (ns), "; // file << "Delay request network (ns), "; // file << "Delay inside mat (ns), "; // file << "Delay reply network (ns), "; // file << "Tag array access time (ns), "; // file << "Data array access time (ns), "; // file << "Refresh period (microsec), "; // file << "DRAM array availability (%), "; file << "Dynamic search energy (nJ), "; file << "Dynamic read energy (nJ), "; file << "Dynamic write energy (nJ), "; // file << "Tag Dynamic read energy (nJ), "; // file << "Data Dynamic read energy (nJ), "; // file << "Dynamic read power (mW), "; file << "Standby leakage per bank(mW), "; // file << "Leakage per bank with leak power management (mW), "; // file << "Leakage per bank with leak power management (mW), "; // file << "Refresh power as percentage of standby leakage, "; file << "Area (mm2), "; file << "Ndwl, "; file << "Ndbl, "; file << "Nspd, "; file << "Ndcm, "; file << "Ndsam_level_1, "; file << "Ndsam_level_2, "; file << "Data arrary area efficiency %, "; file << "Ntwl, "; file << "Ntbl, "; file << "Ntspd, "; file << "Ntcm, "; file << "Ntsam_level_1, "; file << "Ntsam_level_2, "; file << "Tag arrary area efficiency %, "; // file << "Resistance per unit micron (ohm-micron), "; // file << "Capacitance per unit micron (fF per micron), "; // file << "Unit-length wire delay (ps), "; // file << "FO4 delay (ps), "; // file << "delay route to bank (including crossb delay) (ps), "; // file << "Crossbar delay (ps), "; // file << "Dyn read energy per access from closed page (nJ), "; // file << "Dyn read energy per access from open page (nJ), "; // file << "Leak power of an subbank with page closed (mW), "; // file << "Leak power of a subbank with page open (mW), "; // file << "Leak power of request and reply networks (mW), "; // file << "Number of subbanks, "; // file << "Page size in bits, "; // file << "Activate power, "; // file << "Read power, "; // file << "Write power, "; // file << "Precharge power, "; // file << "tRCD, "; // file << "CAS latency, "; // file << "Precharge delay, "; // file << "Perc dyn energy bitlines, "; // file << "perc dyn energy wordlines, "; // file << "perc dyn energy outside mat, "; // file << "Area opt (perc), "; // file << "Delay opt (perc), "; // file << "Repeater opt (perc), "; // file << "Aspect ratio"; file << endl; } file << g_ip->F_sz_nm << ", "; file << g_ip->cache_sz << ", "; file << g_ip->nbanks << ", "; file << g_ip->tag_assoc << ", "; file << g_ip->out_w << ", "; file << fin_res.access_time * 1e+9 << ", "; file << fin_res.cycle_time * 1e+9 << ", "; // file << fin_res.data_array2->multisubbank_interleave_cycle_time*1e+9 << ", "; // file << fin_res.data_array2->delay_request_network*1e+9 << ", "; // file << fin_res.data_array2->delay_inside_mat*1e+9 << ", "; // file << fin_res.data_array2.delay_reply_network*1e+9 << ", "; // if (!(g_ip->fully_assoc || g_ip->pure_cam || g_ip->pure_ram)) // { // file << fin_res.tag_array2->access_time*1e+9 << ", "; // } // else // { // file << 0 << ", "; // } // file << fin_res.data_array2->access_time*1e+9 << ", "; // file << fin_res.data_array2->dram_refresh_period*1e+6 << ", "; // file << fin_res.data_array2->dram_array_availability << ", "; if (g_ip->fully_assoc || g_ip->pure_cam) { file << fin_res.power.searchOp.dynamic * 1e+9 << ", "; } else { file << "N/A" << ", "; } file << fin_res.power.readOp.dynamic * 1e+9 << ", "; file << fin_res.power.writeOp.dynamic * 1e+9 << ", "; // if (!(g_ip->fully_assoc || g_ip->pure_cam || g_ip->pure_ram)) // { // file << fin_res.tag_array2->power.readOp.dynamic*1e+9 << ", "; // } // else // { // file << "NA" << ", "; // } // file << fin_res.data_array2->power.readOp.dynamic*1e+9 << ", "; // if (g_ip->fully_assoc || g_ip->pure_cam) // { // file << fin_res.power.searchOp.dynamic*1000/fin_res.cycle_time << ", "; // } // else // { // file << fin_res.power.readOp.dynamic*1000/fin_res.cycle_time << ", "; // } file << (fin_res.power.readOp.leakage + fin_res.power.readOp.gate_leakage) * 1000 << ", "; // file << fin_res.leak_power_with_sleep_transistors_in_mats*1000 << ", "; // file << fin_res.data_array.refresh_power / fin_res.data_array.total_power.readOp.leakage << ", "; file << fin_res.area * 1e-6 << ", "; file << fin_res.data_array2->Ndwl << ", "; file << fin_res.data_array2->Ndbl << ", "; file << fin_res.data_array2->Nspd << ", "; file << fin_res.data_array2->deg_bl_muxing << ", "; file << fin_res.data_array2->Ndsam_lev_1 << ", "; file << fin_res.data_array2->Ndsam_lev_2 << ", "; file << fin_res.data_array2->area_efficiency << ", "; if (!(g_ip->fully_assoc || g_ip->pure_cam || g_ip->pure_ram)) { file << fin_res.tag_array2->Ndwl << ", "; file << fin_res.tag_array2->Ndbl << ", "; file << fin_res.tag_array2->Nspd << ", "; file << fin_res.tag_array2->deg_bl_muxing << ", "; file << fin_res.tag_array2->Ndsam_lev_1 << ", "; file << fin_res.tag_array2->Ndsam_lev_2 << ", "; file << fin_res.tag_array2->area_efficiency << ", "; } else { file << "N/A" << ", "; file << "N/A" << ", "; file << "N/A" << ", "; file << "N/A" << ", "; file << "N/A" << ", "; file << "N/A" << ", "; file << "N/A" << ", "; } // file << g_tp.wire_inside_mat.R_per_um << ", "; // file << g_tp.wire_inside_mat.C_per_um / 1e-15 << ", "; // file << g_tp.unit_len_wire_del / 1e-12 << ", "; // file << g_tp.FO4 / 1e-12 << ", "; // file << fin_res.data_array.delay_route_to_bank / 1e-9 << ", "; // file << fin_res.data_array.delay_crossbar / 1e-9 << ", "; // file << fin_res.data_array.dyn_read_energy_from_closed_page / 1e-9 << ", "; // file << fin_res.data_array.dyn_read_energy_from_open_page / 1e-9 << ", "; // file << fin_res.data_array.leak_power_subbank_closed_page / 1e-3 << ", "; // file << fin_res.data_array.leak_power_subbank_open_page / 1e-3 << ", "; // file << fin_res.data_array.leak_power_request_and_reply_networks / 1e-3 << ", "; // file << fin_res.data_array.number_subbanks << ", " ; // file << fin_res.data_array.page_size_in_bits << ", " ; // file << fin_res.data_array.activate_energy * 1e9 << ", " ; // file << fin_res.data_array.read_energy * 1e9 << ", " ; // file << fin_res.data_array.write_energy * 1e9 << ", " ; // file << fin_res.data_array.precharge_energy * 1e9 << ", " ; // file << fin_res.data_array.trcd * 1e9 << ", " ; // file << fin_res.data_array.cas_latency * 1e9 << ", " ; // file << fin_res.data_array.precharge_delay * 1e9 << ", " ; // file << fin_res.data_array.all_banks_height / fin_res.data_array.all_banks_width; file << endl; } file.close(); } void output_UCA(uca_org_t* fr) { #ifndef CACTI_REPRODUCE // printing dynamic parameters if (GlobalCactiInput::get().has_dyn_param_prefix()){ if (g_ip->print_detail_debug) cout << "printing dynamic parameters" << endl; if (fr->tag_array2){ ofstream ofs(GlobalCactiInput::get().dyn_param_prefix() + "dyn_param.tag.txt"); boost::archive::text_oarchive oa(ofs); oa << *(fr->tag_array2->dp); } if (fr->data_array2){ ofstream ofs(GlobalCactiInput::get().dyn_param_prefix() + "dyn_param.data.txt"); boost::archive::text_oarchive oa(ofs); oa << *(fr->data_array2->dp); } } #endif if (g_ip->is_3d_mem) { cout << "------- CACTI (version " << VER_MAJOR_CACTI << "." << VER_MINOR_CACTI << "." VER_COMMENT_CACTI << " of " << VER_UPDATE_CACTI << ") 3D DRAM Main Memory -------" << endl; cout << "\nMemory Parameters:\n"; cout << " Total memory size (Gb): " << (int)(g_ip->cache_sz) << endl; if (g_ip->num_die_3d > 1) { cout << " Stacked die count: " << (int)g_ip->num_die_3d << endl; if (g_ip->TSV_proj_type == 1) cout << " TSV projection: industrial conservative" << endl; else cout << " TSV projection: ITRS aggressive" << endl; } cout << " Number of banks: " << (int)g_ip->nbanks << endl; cout << " Technology size (nm): " << g_ip->F_sz_nm << endl; cout << " Page size (bits): " << g_ip->page_sz_bits << endl; cout << " Burst depth: " << g_ip->burst_depth << endl; cout << " Chip IO width: " << g_ip->io_width << endl; cout << " Best Ndwl: " << fr->data_array2->Ndwl << endl; cout << " Best Ndbl: " << fr->data_array2->Ndbl << endl; cout << " # rows in subarray: " << fr->data_array2->num_row_subarray << endl; cout << " # columns in subarray: " << fr->data_array2->num_col_subarray << endl; cout << "\nMore detail Configuration:\n"; cout << "\t\tNdcm:\t" << fr->data_array2->Ndcm << endl; cout << "\t\tNdwl:\t" << fr->data_array2->Ndwl << endl; cout << "\t\tNdbl:\t" << fr->data_array2->Ndbl << endl; cout << "\t\tNspd:\t" << fr->data_array2->Nspd << endl; cout << "\t\tNdsam lev1:\t" << fr->data_array2->Ndsam_lev_1 << endl; cout << "\t\tNdsam lev2:\t" << fr->data_array2->Ndsam_lev_2 << endl; cout << "\t\tbank length:\t" << fr->data_array2->bank_length << endl; cout << "\t\tbank_height:\t" << fr->data_array2->bank_height << endl; cout << "\t\tmat length:\t" << fr->data_array2->mat_length << endl; cout << "\t\tmat height:\t" << fr->data_array2->mat_height << endl; cout << "\t\tsubarray length:\t" << fr->data_array2->subarray_length << endl; cout << "\t\tsubarray height:\t" << fr->data_array2->subarray_height << endl; cout << "\t\tarea per bank:\t" << fr->data_array2->area_per_bank << endl; cout << "\nResults:\n"; cout << "Timing Components:" << endl; cout << " t_RCD (Row to column command delay): " << fr->data_array2->t_RCD * 1e9 << " ns" << endl; cout << " t_RAS (Row access strobe latency): " << fr->data_array2->t_RAS * 1e9 << " ns" << endl; cout << " t_RC (Row cycle): " << fr->data_array2->t_RC * 1e9 << " ns" << endl; cout << " t_CAS (Column access strobe latency): " << fr->data_array2->t_CAS * 1e9 << " ns" << endl; cout << " t_RP (Row precharge latency): " << fr->data_array2->t_RP * 1e9 << " ns" << endl; // cout<<" t_RRD (Rank to rank latency): "<< fr->data_array2->t_RRD* 1e9 << " ns" <<endl; cout << " t_RRD (Row activation to row activation delay): " << fr->data_array2->t_RRD * 1e9 << " ns" << endl; cout << "Power Components:" << endl; cout << " Activation energy: " << fr->data_array2->activate_energy * 1e9 << " nJ" << endl; cout << " Read energy: " << fr->data_array2->read_energy * 1e9 << " nJ" << endl; cout << " Write energy: " << fr->data_array2->write_energy * 1e9 << " nJ" << endl; cout << " Precharge energy: " << fr->data_array2->precharge_energy * 1e9 << " nJ" << endl; cout << " Standby leakage per bank: " << (fr->power.readOp.leakage + fr->power.readOp.gate_leakage) * 1000 << " mW" << endl; if (g_ip->print_detail_debug) { cout << " leakage: " << fr->power.readOp.leakage * 1000 << " mW" << endl; cout << " gate leakage: " << fr->power.readOp.gate_leakage * 1000 << " mW" << endl; } // cout<<" Activation power: "<< fr->data_array2->activate_power * 1e3 << " mW" <<endl; // cout<<" Read power: "<< fr->data_array2->read_power * 1e3 << " mW" <<endl; // cout<<" Write power: "<< fr->data_array2->write_power * 1e3 << " mW" <<endl; // cout<<" Peak read power: "<< read_energy/((g_ip->burst_depth)/(g_ip->sys_freq_MHz*1e6)/2) * 1e3 << " mW" <<endl; cout << "Area Components:" << endl; // cout<<" Height: "<<area.h/1e3<<" mm"<<endl; // cout<<" Length: "<<area.w/1e3<<" mm"<<endl; // cout<<" DRAM+peri Area: "<< fr->data_array2->area/1e6<<" mm2"<<endl; // double DRAM_area_per_die = (g_ip->partition_gran>0) ? fr->data_array2->area : (fr->data_array2->area/0.5); double DRAM_area_per_die = (g_ip->partition_gran > 0) ? fr->data_array2->area : (fr->data_array2->area + fr->data_array2->area_ram_cells * 0.65); // double DRAM_area_per_die = (g_ip->partition_gran>0) ? fr->data_array2->area : (fr->data_array2->area + // 2.5e9*(double)(g_ip->F_sz_um)*(g_ip->F_sz_um)); double area_efficiency_per_die = (g_ip->partition_gran > 0) ? fr->data_array2->area_efficiency : (fr->data_array2->area_ram_cells / DRAM_area_per_die * 100); double DRAM_width = (g_ip->partition_gran > 0) ? fr->data_array2->all_banks_width : (fr->data_array2->all_banks_width + (DRAM_area_per_die - fr->data_array2->area) / fr->data_array2->all_banks_height); cout << " DRAM core area: " << fr->data_array2->area / 1e6 << " mm2" << endl; if (g_ip->partition_gran == 0) cout << " DRAM area per die: " << DRAM_area_per_die / 1e6 << " mm2" << endl; cout << " Area efficiency: " << area_efficiency_per_die << "%" << endl; cout << " DRAM die width: " << DRAM_width / 1e3 << " mm" << endl; cout << " DRAM die height: " << fr->data_array2->all_banks_height / 1e3 << " mm" << endl; cout << " DRAM area per bank: " << fr->data_array2->area_per_bank / 1e6 << " mm" << endl; if (g_ip->num_die_3d > 1) { cout << "TSV Components:" << endl; cout << " TSV area overhead: " << fr->data_array2->area_TSV_tot / 1e6 << " mm2" << endl; cout << " TSV latency overhead: " << fr->data_array2->delay_TSV_tot * 1e9 << " ns" << endl; cout << " TSV energy overhead per access: " << fr->data_array2->dyn_pow_TSV_per_access * 1e9 << " nJ" << endl; } } else // if(!g_ip->is_3d_mem) { // if (NUCA) if (0) { cout << "\n\n Detailed Bank Stats:\n"; cout << " Bank Size (bytes): %d\n" << (int)(g_ip->cache_sz); } else { if (g_ip->data_arr_ram_cell_tech_type == 3) { cout << "\n---------- CACTI (version " << VER_MAJOR_CACTI << "." << VER_MINOR_CACTI << "." VER_COMMENT_CACTI << " of " << VER_UPDATE_CACTI << "), Uniform Cache Access " << "Logic Process Based DRAM Model ----------\n"; } else if (g_ip->data_arr_ram_cell_tech_type == 4) { cout << "\n---------- CACTI (version " << VER_MAJOR_CACTI << "." << VER_MINOR_CACTI << "." VER_COMMENT_CACTI << " of " << VER_UPDATE_CACTI << "), Uniform" << "Cache Access Commodity DRAM Model ----------\n"; } else { cout << "\n---------- CACTI (version " << VER_MAJOR_CACTI << "." << VER_MINOR_CACTI << "." VER_COMMENT_CACTI << " of " << VER_UPDATE_CACTI << "), Uniform Cache Access " "SRAM Model ----------\n"; } cout << "\nCache Parameters:\n"; cout << " Total cache size (bytes): " << (int)(g_ip->cache_sz) << endl; } cout << " Number of banks: " << (int)g_ip->nbanks << endl; if (g_ip->fully_assoc || g_ip->pure_cam) cout << " Associativity: fully associative\n"; else { if (g_ip->tag_assoc == 1) cout << " Associativity: direct mapped\n"; else cout << " Associativity: " << g_ip->tag_assoc << endl; } cout << " Block size (bytes): " << g_ip->line_sz << endl; cout << " Read/write Ports: " << g_ip->num_rw_ports << endl; cout << " Read ports: " << g_ip->num_rd_ports << endl; cout << " Write ports: " << g_ip->num_wr_ports << endl; if (g_ip->fully_assoc || g_ip->pure_cam) cout << " search ports: " << g_ip->num_search_ports << endl; cout << " Technology size (nm): " << g_ip->F_sz_nm << endl << endl; cout << " Access time (ns): " << fr->access_time * 1e9 << endl; cout << " Cycle time (ns): " << fr->cycle_time * 1e9 << endl; if (g_ip->data_arr_ram_cell_tech_type >= 4) { cout << " Precharge Delay (ns): " << fr->data_array2->precharge_delay * 1e9 << endl; cout << " Activate Energy (nJ): " << fr->data_array2->activate_energy * 1e9 << endl; cout << " Read Energy (nJ): " << fr->data_array2->read_energy * 1e9 << endl; cout << " Write Energy (nJ): " << fr->data_array2->write_energy * 1e9 << endl; cout << " Precharge Energy (nJ): " << fr->data_array2->precharge_energy * 1e9 << endl; cout << " Leakage Power Closed Page (mW): " << fr->data_array2->leak_power_subbank_closed_page * 1e3 << endl; cout << " Leakage Power Open Page (mW): " << fr->data_array2->leak_power_subbank_open_page * 1e3 << endl; cout << " Leakage Power I/O (mW): " << fr->data_array2->leak_power_request_and_reply_networks * 1e3 << endl; cout << " Refresh power (mW): " << fr->data_array2->refresh_power * 1e3 << endl; } else { if ((g_ip->fully_assoc || g_ip->pure_cam)) { cout << " Total dynamic associative search energy per access (nJ): " << fr->power.searchOp.dynamic * 1e9 << endl; // cout << " Total dynamic read energy per access (nJ): " << // fr->power.readOp.dynamic*1e9 << endl; // cout << " Total dynamic write energy per access (nJ): " << // fr->power.writeOp.dynamic*1e9 << endl; } // else // { cout << " Total dynamic read energy per access (nJ): " << fr->power.readOp.dynamic * 1e9 << endl; cout << " Total dynamic write energy per access (nJ): " << fr->power.writeOp.dynamic * 1e9 << endl; // } cout << " Total leakage power of a bank" " (mW): " << fr->power.readOp.leakage * 1e3 << endl; cout << " Total gate leakage power of a bank" " (mW): " << fr->power.readOp.gate_leakage * 1e3 << endl; } if (g_ip->data_arr_ram_cell_tech_type == 3 || g_ip->data_arr_ram_cell_tech_type == 4) { } cout << " Cache height x width (mm): " << fr->cache_ht * 1e-3 << " x " << fr->cache_len * 1e-3 << endl << endl; cout << " Best Ndwl : " << fr->data_array2->Ndwl << endl; cout << " Best Ndbl : " << fr->data_array2->Ndbl << endl; cout << " Best Nspd : " << fr->data_array2->Nspd << endl; cout << " Best Ndcm : " << fr->data_array2->deg_bl_muxing << endl; cout << " Best Ndsam L1 : " << fr->data_array2->Ndsam_lev_1 << endl; cout << " Best Ndsam L2 : " << fr->data_array2->Ndsam_lev_2 << endl << endl; if ((!(g_ip->pure_ram || g_ip->pure_cam || g_ip->fully_assoc)) && !g_ip->is_main_mem) { cout << " Best Ntwl : " << fr->tag_array2->Ndwl << endl; cout << " Best Ntbl : " << fr->tag_array2->Ndbl << endl; cout << " Best Ntspd : " << fr->tag_array2->Nspd << endl; cout << " Best Ntcm : " << fr->tag_array2->deg_bl_muxing << endl; cout << " Best Ntsam L1 : " << fr->tag_array2->Ndsam_lev_1 << endl; cout << " Best Ntsam L2 : " << fr->tag_array2->Ndsam_lev_2 << endl; } switch (fr->data_array2->wt) { case (0): cout << " Data array, H-tree wire type: Delay optimized global wires\n"; break; case (1): cout << " Data array, H-tree wire type: Global wires with 5\% delay penalty\n"; break; case (2): cout << " Data array, H-tree wire type: Global wires with 10\% delay penalty\n"; break; case (3): cout << " Data array, H-tree wire type: Global wires with 20\% delay penalty\n"; break; case (4): cout << " Data array, H-tree wire type: Global wires with 30\% delay penalty\n"; break; case (5): cout << " Data array, wire type: Low swing wires\n"; break; default: cout << "ERROR - Unknown wire type " << (int)fr->data_array2->wt << endl; exit(0); } if (!(g_ip->pure_ram || g_ip->pure_cam || g_ip->fully_assoc)) { switch (fr->tag_array2->wt) { case (0): cout << " Tag array, H-tree wire type: Delay optimized global wires\n"; break; case (1): cout << " Tag array, H-tree wire type: Global wires with 5\% delay penalty\n"; break; case (2): cout << " Tag array, H-tree wire type: Global wires with 10\% delay penalty\n"; break; case (3): cout << " Tag array, H-tree wire type: Global wires with 20\% delay penalty\n"; break; case (4): cout << " Tag array, H-tree wire type: Global wires with 30\% delay penalty\n"; break; case (5): cout << " Tag array, wire type: Low swing wires\n"; break; default: cout << "ERROR - Unknown wire type " << (int)fr->tag_array2->wt << endl; exit(-1); } } } // end if(!g_ip->is_3d_mem) if (g_ip->print_detail) { // if(g_ip->fully_assoc) return; if (g_ip->is_3d_mem) { cout << endl << endl << "3D DRAM Detail Components:" << endl << endl; cout << endl << "Time Components:" << endl << endl; cout << "\t row activation bus delay (ns): " << fr->data_array2->delay_row_activate_net * 1e9 << endl; cout << "\t row predecoder delay (ns): " << fr->data_array2->delay_row_predecode_driver_and_block * 1e9 << endl; cout << "\t row decoder delay (ns): " << fr->data_array2->delay_row_decoder * 1e9 << endl; cout << "\t local wordline delay (ns): " << fr->data_array2->delay_local_wordline * 1e9 << endl; cout << "\t bitline delay (ns): " << fr->data_array2->delay_bitlines * 1e9 << endl; cout << "\t sense amp delay (ns): " << fr->data_array2->delay_sense_amp * 1e9 << endl; cout << "\t column access bus delay (ns): " << fr->data_array2->delay_column_access_net * 1e9 << endl; cout << "\t column predecoder delay (ns): " << fr->data_array2->delay_column_predecoder * 1e9 << endl; cout << "\t column decoder delay (ns): " << fr->data_array2->delay_column_decoder * 1e9 << endl; // cout << "\t column selectline delay (ns): " << fr->data_array2->delay_column_selectline*1e9 << endl; cout << "\t datapath bus delay (ns): " << fr->data_array2->delay_datapath_net * 1e9 << endl; cout << "\t global dataline delay (ns): " << fr->data_array2->delay_global_data * 1e9 << endl; cout << "\t local dataline delay (ns): " << fr->data_array2->delay_local_data_and_drv * 1e9 << endl; cout << "\t data buffer delay (ns): " << fr->data_array2->delay_data_buffer * 1e9 << endl; cout << "\t subarray output driver delay (ns): " << fr->data_array2->delay_subarray_output_driver * 1e9 << endl; cout << endl << "Energy Components:" << endl << endl; cout << "\t row activation bus energy (nJ): " << fr->data_array2->energy_row_activate_net * 1e9 << endl; cout << "\t row predecoder energy (nJ): " << fr->data_array2->energy_row_predecode_driver_and_block * 1e9 << endl; cout << "\t row decoder energy (nJ): " << fr->data_array2->energy_row_decoder * 1e9 << endl; cout << "\t local wordline energy (nJ): " << fr->data_array2->energy_local_wordline * 1e9 << endl; cout << "\t bitline energy (nJ): " << fr->data_array2->energy_bitlines * 1e9 << endl; cout << "\t sense amp energy (nJ): " << fr->data_array2->energy_sense_amp * 1e9 << endl; cout << "\t column access bus energy (nJ): " << fr->data_array2->energy_column_access_net * 1e9 << endl; cout << "\t column predecoder energy (nJ): " << fr->data_array2->energy_column_predecoder * 1e9 << endl; cout << "\t column decoder energy (nJ): " << fr->data_array2->energy_column_decoder * 1e9 << endl; cout << "\t column selectline energy (nJ): " << fr->data_array2->energy_column_selectline * 1e9 << endl; cout << "\t datapath bus energy (nJ): " << fr->data_array2->energy_datapath_net * 1e9 << endl; cout << "\t global dataline energy (nJ): " << fr->data_array2->energy_global_data * 1e9 << endl; cout << "\t local dataline energy (nJ): " << fr->data_array2->energy_local_data_and_drv * 1e9 << endl; cout << "\t data buffer energy (nJ): " << fr->data_array2->energy_subarray_output_driver * 1e9 << endl; // cout << "\t subarray output driver energy (nJ): " << fr->data_array2->energy_data_buffer*1e9 << endl; cout << endl << "Area Components:" << endl << endl; // cout << "\t subarray area (mm2): " << fr->data_array2->area_subarray/1e6 << endl; cout << "\t DRAM cell area (mm2): " << fr->data_array2->area_ram_cells / 1e6 << endl; cout << "\t local WL driver area (mm2): " << fr->data_array2->area_lwl_drv / 1e6 << endl; cout << "\t subarray sense amp area (mm2): " << fr->data_array2->area_sense_amp / 1e6 << endl; cout << "\t row predecoder/decoder area (mm2): " << fr->data_array2->area_row_predec_dec / 1e6 << endl; cout << "\t column predecoder/decoder area (mm2): " << fr->data_array2->area_col_predec_dec / 1e6 << endl; cout << "\t center stripe bus area (mm2): " << fr->data_array2->area_bus / 1e6 << endl; cout << "\t address bus area (mm2): " << fr->data_array2->area_address_bus / 1e6 << endl; cout << "\t data bus area (mm2): " << fr->data_array2->area_data_bus / 1e6 << endl; cout << "\t data driver area (mm2): " << fr->data_array2->area_data_drv / 1e6 << endl; cout << "\t IO secondary sense amp area (mm2): " << fr->data_array2->area_IOSA / 1e6 << endl; cout << "\t TSV area (mm2): " << fr->data_array2->area_TSV_tot / 1e6 << endl; } else // if (!g_ip->is_3d_mem) { if (g_ip->power_gating) { /* Energy/Power stats */ cout << endl << endl << "Power-gating Components:" << endl << endl; /* Data array power-gating stats */ if (!(g_ip->pure_cam || g_ip->fully_assoc)) cout << " Data array: " << endl; else if (g_ip->pure_cam) cout << " CAM array: " << endl; else cout << " Fully associative cache array: " << endl; cout << "\t Sub-array Sleep Tx size (um) - " << fr->data_array2->sram_sleep_tx_width << endl; // cout << "\t Sub-array Sleep Tx total size (um) - " << // fr->data_array2->sram_sleep_tx_width << endl; cout << "\t Sub-array Sleep Tx total area (mm^2) - " << fr->data_array2->sram_sleep_tx_area * 1e-6 << endl; cout << "\t Sub-array wakeup time (ns) - " << fr->data_array2->sram_sleep_wakeup_latency * 1e9 << endl; cout << "\t Sub-array Tx energy (nJ) - " << fr->data_array2->sram_sleep_wakeup_energy * 1e9 << endl; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++ cout << endl; cout << "\t WL Sleep Tx size (um) - " << fr->data_array2->wl_sleep_tx_width << endl; // cout << "\t WL Sleep total Tx size (um) - " << // fr->data_array2->wl_sleep_tx_width << endl; cout << "\t WL Sleep Tx total area (mm^2) - " << fr->data_array2->wl_sleep_tx_area * 1e-6 << endl; cout << "\t WL wakeup time (ns) - " << fr->data_array2->wl_sleep_wakeup_latency * 1e9 << endl; cout << "\t WL Tx energy (nJ) - " << fr->data_array2->wl_sleep_wakeup_energy * 1e9 << endl; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++ cout << endl; cout << "\t BL floating wakeup time (ns) - " << fr->data_array2->bl_floating_wakeup_latency * 1e9 << endl; cout << "\t BL floating Tx energy (nJ) - " << fr->data_array2->bl_floating_wakeup_energy * 1e9 << endl; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++ cout << endl; cout << "\t Active mats per access - " << fr->data_array2->num_active_mats << endl; cout << "\t Active subarrays per mat - " << fr->data_array2->num_submarray_mats << endl; cout << endl; /* Tag array area stats */ if ((!(g_ip->pure_ram || g_ip->pure_cam || g_ip->fully_assoc)) && !g_ip->is_main_mem) { cout << " Tag array: " << endl; cout << "\t Sub-array Sleep Tx size (um) - " << fr->tag_array2->sram_sleep_tx_width << endl; // cout << "\t Sub-array Sleep Tx total size (um) - " << // fr->tag_array2->sram_sleep_tx_width << endl; cout << "\t Sub-array Sleep Tx total area (mm^2) - " << fr->tag_array2->sram_sleep_tx_area * 1e-6 << endl; cout << "\t Sub-array wakeup time (ns) - " << fr->tag_array2->sram_sleep_wakeup_latency * 1e9 << endl; cout << "\t Sub-array Tx energy (nJ) - " << fr->tag_array2->sram_sleep_wakeup_energy * 1e9 << endl; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++ cout << endl; cout << "\t WL Sleep Tx size (um) - " << fr->tag_array2->wl_sleep_tx_width << endl; // cout << "\t WL Sleep total Tx size (um) - " << // fr->tag_array2->wl_sleep_tx_width << endl; cout << "\t WL Sleep Tx total area (mm^2) - " << fr->tag_array2->wl_sleep_tx_area * 1e-6 << endl; cout << "\t WL wakeup time (ns) - " << fr->tag_array2->wl_sleep_wakeup_latency * 1e9 << endl; cout << "\t WL Tx energy (nJ) - " << fr->tag_array2->wl_sleep_wakeup_energy * 1e9 << endl; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++ cout << endl; cout << "\t BL floating wakeup time (ns) - " << fr->tag_array2->bl_floating_wakeup_latency * 1e9 << endl; cout << "\t BL floating Tx energy (nJ) - " << fr->tag_array2->bl_floating_wakeup_energy * 1e9 << endl; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++ cout << endl; cout << "\t Active mats per access - " << fr->tag_array2->num_active_mats << endl; cout << "\t Active subarrays per mat - " << fr->tag_array2->num_submarray_mats << endl; cout << endl; } } /* Delay stats */ /* data array stats */ cout << endl << "Time Components:" << endl << endl; cout << " Data side (with Output driver) (ns): " << fr->data_array2->access_time / 1e-9 << endl; cout << "\tH-tree input delay (ns): " << fr->data_array2->delay_route_to_bank * 1e9 + fr->data_array2->delay_input_htree * 1e9 << endl; if (!(g_ip->pure_cam || g_ip->fully_assoc)) { cout << "\tDecoder + wordline delay (ns): " << fr->data_array2->delay_row_predecode_driver_and_block * 1e9 + fr->data_array2->delay_row_decoder * 1e9 << endl; } else { cout << "\tCAM search delay (ns): " << fr->data_array2->delay_matchlines * 1e9 << endl; } cout << "\tBitline delay (ns): " << fr->data_array2->delay_bitlines / 1e-9 << endl; cout << "\tSense Amplifier delay (ns): " << fr->data_array2->delay_sense_amp * 1e9 << endl; cout << "\tH-tree output delay (ns): " << fr->data_array2->delay_subarray_output_driver * 1e9 + fr->data_array2->delay_dout_htree * 1e9 << endl; if ((!(g_ip->pure_ram || g_ip->pure_cam || g_ip->fully_assoc)) && !g_ip->is_main_mem) { /* tag array stats */ cout << endl << " Tag side (with Output driver) (ns): " << fr->tag_array2->access_time / 1e-9 << endl; cout << "\tH-tree input delay (ns): " << fr->tag_array2->delay_route_to_bank * 1e9 + fr->tag_array2->delay_input_htree * 1e9 << endl; cout << "\tDecoder + wordline delay (ns): " << fr->tag_array2->delay_row_predecode_driver_and_block * 1e9 + fr->tag_array2->delay_row_decoder * 1e9 << endl; cout << "\tBitline delay (ns): " << fr->tag_array2->delay_bitlines / 1e-9 << endl; cout << "\tSense Amplifier delay (ns): " << fr->tag_array2->delay_sense_amp * 1e9 << endl; cout << "\tComparator delay (ns): " << fr->tag_array2->delay_comparator * 1e9 << endl; cout << "\tH-tree output delay (ns): " << fr->tag_array2->delay_subarray_output_driver * 1e9 + fr->tag_array2->delay_dout_htree * 1e9 << endl; } /* Energy/Power stats */ cout << endl << endl << "Power Components:" << endl << endl; if (!(g_ip->pure_cam || g_ip->fully_assoc)) { cout << " Data array: Total dynamic read energy/access (nJ): " << fr->data_array2->power.readOp.dynamic * 1e9 << endl; cout << "\tTotal energy in H-tree (that includes both " "address and data transfer) (nJ): " << (fr->data_array2->power_addr_input_htree.readOp.dynamic + fr->data_array2->power_data_output_htree.readOp.dynamic + fr->data_array2->power_routing_to_bank.readOp.dynamic) * 1e9 << endl; cout << "\tOutput Htree inside bank Energy (nJ): " << fr->data_array2->power_data_output_htree.readOp.dynamic * 1e9 << endl; cout << "\tDecoder (nJ): " << fr->data_array2->power_row_predecoder_drivers.readOp.dynamic * 1e9 + fr->data_array2->power_row_predecoder_blocks.readOp.dynamic * 1e9 << endl; cout << "\tWordline (nJ): " << fr->data_array2->power_row_decoders.readOp.dynamic * 1e9 << endl; cout << "\tBitline mux & associated drivers (nJ): " << fr->data_array2->power_bit_mux_predecoder_drivers.readOp.dynamic * 1e9 + fr->data_array2->power_bit_mux_predecoder_blocks.readOp.dynamic * 1e9 + fr->data_array2->power_bit_mux_decoders.readOp.dynamic * 1e9 << endl; cout << "\tSense amp mux & associated drivers (nJ): " << fr->data_array2->power_senseamp_mux_lev_1_predecoder_drivers.readOp.dynamic * 1e9 + fr->data_array2->power_senseamp_mux_lev_1_predecoder_blocks.readOp.dynamic * 1e9 + fr->data_array2->power_senseamp_mux_lev_1_decoders.readOp.dynamic * 1e9 + fr->data_array2->power_senseamp_mux_lev_2_predecoder_drivers.readOp.dynamic * 1e9 + fr->data_array2->power_senseamp_mux_lev_2_predecoder_blocks.readOp.dynamic * 1e9 + fr->data_array2->power_senseamp_mux_lev_2_decoders.readOp.dynamic * 1e9 << endl; cout << "\tBitlines precharge and equalization circuit (nJ): " << fr->data_array2->power_prechg_eq_drivers.readOp.dynamic * 1e9 << endl; cout << "\tBitlines (nJ): " << fr->data_array2->power_bitlines.readOp.dynamic * 1e9 << endl; cout << "\tSense amplifier energy (nJ): " << fr->data_array2->power_sense_amps.readOp.dynamic * 1e9 << endl; cout << "\tSub-array output driver (nJ): " << fr->data_array2->power_output_drivers_at_subarray.readOp.dynamic * 1e9 << endl; cout << "\tTotal leakage power of a bank (mW): " << fr->data_array2->power.readOp.leakage * 1e3 << endl; cout << "\tTotal leakage power in H-tree (that includes both " "address and data network) ((mW)): " << (fr->data_array2->power_addr_input_htree.readOp.leakage + fr->data_array2->power_data_output_htree.readOp.leakage + fr->data_array2->power_routing_to_bank.readOp.leakage) * 1e3 << endl; cout << "\tTotal leakage power in cells (mW): " << (fr->data_array2->array_leakage) * 1e3 << endl; cout << "\tTotal leakage power in row logic(mW): " << (fr->data_array2->wl_leakage) * 1e3 << endl; cout << "\tTotal leakage power in column logic(mW): " << (fr->data_array2->cl_leakage) * 1e3 << endl; cout << "\tTotal gate leakage power in H-tree (that includes both " "address and data network) ((mW)): " << (fr->data_array2->power_addr_input_htree.readOp.gate_leakage + fr->data_array2->power_data_output_htree.readOp.gate_leakage + fr->data_array2->power_routing_to_bank.readOp.gate_leakage) * 1e3 << endl; } else if (g_ip->pure_cam) { cout << " CAM array:" << endl; cout << " Total dynamic associative search energy/access (nJ): " << fr->data_array2->power.searchOp.dynamic * 1e9 << endl; cout << "\tTotal energy in H-tree (that includes both " "match key and data transfer) (nJ): " << (fr->data_array2->power_htree_in_search.searchOp.dynamic + fr->data_array2->power_htree_out_search.searchOp.dynamic + fr->data_array2->power_routing_to_bank.searchOp.dynamic) * 1e9 << endl; cout << "\tKeyword input and result output Htrees inside bank Energy (nJ): " << (fr->data_array2->power_htree_in_search.searchOp.dynamic + fr->data_array2->power_htree_out_search.searchOp.dynamic) * 1e9 << endl; cout << "\tSearchlines (nJ): " << fr->data_array2->power_searchline.searchOp.dynamic * 1e9 + fr->data_array2->power_searchline_precharge.searchOp.dynamic * 1e9 << endl; cout << "\tMatchlines (nJ): " << fr->data_array2->power_matchlines.searchOp.dynamic * 1e9 + fr->data_array2->power_matchline_precharge.searchOp.dynamic * 1e9 << endl; cout << "\tSub-array output driver (nJ): " << fr->data_array2->power_output_drivers_at_subarray.searchOp.dynamic * 1e9 << endl; cout << endl << " Total dynamic read energy/access (nJ): " << fr->data_array2->power.readOp.dynamic * 1e9 << endl; cout << "\tTotal energy in H-tree (that includes both " "address and data transfer) (nJ): " << (fr->data_array2->power_addr_input_htree.readOp.dynamic + fr->data_array2->power_data_output_htree.readOp.dynamic + fr->data_array2->power_routing_to_bank.readOp.dynamic) * 1e9 << endl; cout << "\tOutput Htree inside bank Energy (nJ): " << fr->data_array2->power_data_output_htree.readOp.dynamic * 1e9 << endl; cout << "\tDecoder (nJ): " << fr->data_array2->power_row_predecoder_drivers.readOp.dynamic * 1e9 + fr->data_array2->power_row_predecoder_blocks.readOp.dynamic * 1e9 << endl; cout << "\tWordline (nJ): " << fr->data_array2->power_row_decoders.readOp.dynamic * 1e9 << endl; cout << "\tBitline mux & associated drivers (nJ): " << fr->data_array2->power_bit_mux_predecoder_drivers.readOp.dynamic * 1e9 + fr->data_array2->power_bit_mux_predecoder_blocks.readOp.dynamic * 1e9 + fr->data_array2->power_bit_mux_decoders.readOp.dynamic * 1e9 << endl; cout << "\tSense amp mux & associated drivers (nJ): " << fr->data_array2->power_senseamp_mux_lev_1_predecoder_drivers.readOp.dynamic * 1e9 + fr->data_array2->power_senseamp_mux_lev_1_predecoder_blocks.readOp.dynamic * 1e9 + fr->data_array2->power_senseamp_mux_lev_1_decoders.readOp.dynamic * 1e9 + fr->data_array2->power_senseamp_mux_lev_2_predecoder_drivers.readOp.dynamic * 1e9 + fr->data_array2->power_senseamp_mux_lev_2_predecoder_blocks.readOp.dynamic * 1e9 + fr->data_array2->power_senseamp_mux_lev_2_decoders.readOp.dynamic * 1e9 << endl; cout << "\tBitlines (nJ): " << fr->data_array2->power_bitlines.readOp.dynamic * 1e9 + fr->data_array2->power_prechg_eq_drivers.readOp.dynamic * 1e9 << endl; cout << "\tSense amplifier energy (nJ): " << fr->data_array2->power_sense_amps.readOp.dynamic * 1e9 << endl; cout << "\tSub-array output driver (nJ): " << fr->data_array2->power_output_drivers_at_subarray.readOp.dynamic * 1e9 << endl; cout << endl << " Total leakage power of a bank (mW): " << fr->data_array2->power.readOp.leakage * 1e3 << endl; } else { cout << " Fully associative array:" << endl; cout << " Total dynamic associative search energy/access (nJ): " << fr->data_array2->power.searchOp.dynamic * 1e9 << endl; cout << "\tTotal energy in H-tree (that includes both " "match key and data transfer) (nJ): " << (fr->data_array2->power_htree_in_search.searchOp.dynamic + fr->data_array2->power_htree_out_search.searchOp.dynamic + fr->data_array2->power_routing_to_bank.searchOp.dynamic) * 1e9 << endl; cout << "\tKeyword input and result output Htrees inside bank Energy (nJ): " << (fr->data_array2->power_htree_in_search.searchOp.dynamic + fr->data_array2->power_htree_out_search.searchOp.dynamic) * 1e9 << endl; cout << "\tSearchlines (nJ): " << fr->data_array2->power_searchline.searchOp.dynamic * 1e9 + fr->data_array2->power_searchline_precharge.searchOp.dynamic * 1e9 << endl; cout << "\tMatchlines (nJ): " << fr->data_array2->power_matchlines.searchOp.dynamic * 1e9 + fr->data_array2->power_matchline_precharge.searchOp.dynamic * 1e9 << endl; cout << "\tData portion wordline (nJ): " << fr->data_array2->power_matchline_to_wordline_drv.searchOp.dynamic * 1e9 << endl; cout << "\tData Bitlines (nJ): " << fr->data_array2->power_bitlines.searchOp.dynamic * 1e9 + fr->data_array2->power_prechg_eq_drivers.searchOp.dynamic * 1e9 << endl; cout << "\tSense amplifier energy (nJ): " << fr->data_array2->power_sense_amps.searchOp.dynamic * 1e9 << endl; cout << "\tSub-array output driver (nJ): " << fr->data_array2->power_output_drivers_at_subarray.searchOp.dynamic * 1e9 << endl; cout << endl << " Total dynamic read energy/access (nJ): " << fr->data_array2->power.readOp.dynamic * 1e9 << endl; cout << "\tTotal energy in H-tree (that includes both " "address and data transfer) (nJ): " << (fr->data_array2->power_addr_input_htree.readOp.dynamic + fr->data_array2->power_data_output_htree.readOp.dynamic + fr->data_array2->power_routing_to_bank.readOp.dynamic) * 1e9 << endl; cout << "\tOutput Htree inside bank Energy (nJ): " << fr->data_array2->power_data_output_htree.readOp.dynamic * 1e9 << endl; cout << "\tDecoder (nJ): " << fr->data_array2->power_row_predecoder_drivers.readOp.dynamic * 1e9 + fr->data_array2->power_row_predecoder_blocks.readOp.dynamic * 1e9 << endl; cout << "\tWordline (nJ): " << fr->data_array2->power_row_decoders.readOp.dynamic * 1e9 << endl; cout << "\tBitline mux & associated drivers (nJ): " << fr->data_array2->power_bit_mux_predecoder_drivers.readOp.dynamic * 1e9 + fr->data_array2->power_bit_mux_predecoder_blocks.readOp.dynamic * 1e9 + fr->data_array2->power_bit_mux_decoders.readOp.dynamic * 1e9 << endl; cout << "\tSense amp mux & associated drivers (nJ): " << fr->data_array2->power_senseamp_mux_lev_1_predecoder_drivers.readOp.dynamic * 1e9 + fr->data_array2->power_senseamp_mux_lev_1_predecoder_blocks.readOp.dynamic * 1e9 + fr->data_array2->power_senseamp_mux_lev_1_decoders.readOp.dynamic * 1e9 + fr->data_array2->power_senseamp_mux_lev_2_predecoder_drivers.readOp.dynamic * 1e9 + fr->data_array2->power_senseamp_mux_lev_2_predecoder_blocks.readOp.dynamic * 1e9 + fr->data_array2->power_senseamp_mux_lev_2_decoders.readOp.dynamic * 1e9 << endl; cout << "\tBitlines (nJ): " << fr->data_array2->power_bitlines.readOp.dynamic * 1e9 + fr->data_array2->power_prechg_eq_drivers.readOp.dynamic * 1e9 << endl; cout << "\tSense amplifier energy (nJ): " << fr->data_array2->power_sense_amps.readOp.dynamic * 1e9 << endl; cout << "\tSub-array output driver (nJ): " << fr->data_array2->power_output_drivers_at_subarray.readOp.dynamic * 1e9 << endl; cout << endl << " Total leakage power of a bank (mW): " << fr->data_array2->power.readOp.leakage * 1e3 << endl; } if ((!(g_ip->pure_ram || g_ip->pure_cam || g_ip->fully_assoc)) && !g_ip->is_main_mem) { cout << endl << " Tag array: Total dynamic read energy/access (nJ): " << fr->tag_array2->power.readOp.dynamic * 1e9 << endl; cout << "\tTotal leakage read/write power of a bank (mW): " << fr->tag_array2->power.readOp.leakage * 1e3 << endl; cout << "\tTotal energy in H-tree (that includes both " "address and data transfer) (nJ): " << (fr->tag_array2->power_addr_input_htree.readOp.dynamic + fr->tag_array2->power_data_output_htree.readOp.dynamic + fr->tag_array2->power_routing_to_bank.readOp.dynamic) * 1e9 << endl; cout << "\tOutput Htree inside a bank Energy (nJ): " << fr->tag_array2->power_data_output_htree.readOp.dynamic * 1e9 << endl; cout << "\tDecoder (nJ): " << fr->tag_array2->power_row_predecoder_drivers.readOp.dynamic * 1e9 + fr->tag_array2->power_row_predecoder_blocks.readOp.dynamic * 1e9 << endl; cout << "\tWordline (nJ): " << fr->tag_array2->power_row_decoders.readOp.dynamic * 1e9 << endl; cout << "\tBitline mux & associated drivers (nJ): " << fr->tag_array2->power_bit_mux_predecoder_drivers.readOp.dynamic * 1e9 + fr->tag_array2->power_bit_mux_predecoder_blocks.readOp.dynamic * 1e9 + fr->tag_array2->power_bit_mux_decoders.readOp.dynamic * 1e9 << endl; cout << "\tSense amp mux & associated drivers (nJ): " << fr->tag_array2->power_senseamp_mux_lev_1_predecoder_drivers.readOp.dynamic * 1e9 + fr->tag_array2->power_senseamp_mux_lev_1_predecoder_blocks.readOp.dynamic * 1e9 + fr->tag_array2->power_senseamp_mux_lev_1_decoders.readOp.dynamic * 1e9 + fr->tag_array2->power_senseamp_mux_lev_2_predecoder_drivers.readOp.dynamic * 1e9 + fr->tag_array2->power_senseamp_mux_lev_2_predecoder_blocks.readOp.dynamic * 1e9 + fr->tag_array2->power_senseamp_mux_lev_2_decoders.readOp.dynamic * 1e9 << endl; cout << "\tBitlines precharge and equalization circuit (nJ): " << fr->tag_array2->power_prechg_eq_drivers.readOp.dynamic * 1e9 << endl; cout << "\tBitlines (nJ): " << fr->tag_array2->power_bitlines.readOp.dynamic * 1e9 << endl; cout << "\tSense amplifier energy (nJ): " << fr->tag_array2->power_sense_amps.readOp.dynamic * 1e9 << endl; cout << "\tSub-array output driver (nJ): " << fr->tag_array2->power_output_drivers_at_subarray.readOp.dynamic * 1e9 << endl; cout << "\tTotal leakage power of a bank (mW): " << fr->tag_array2->power.readOp.leakage * 1e3 << endl; cout << "\tTotal leakage power in H-tree (that includes both " "address and data network) ((mW)): " << (fr->tag_array2->power_addr_input_htree.readOp.leakage + fr->tag_array2->power_data_output_htree.readOp.leakage + fr->tag_array2->power_routing_to_bank.readOp.leakage) * 1e3 << endl; cout << "\tTotal leakage power in cells (mW): " << (fr->tag_array2->array_leakage) * 1e3 << endl; cout << "\tTotal leakage power in row logic(mW): " << (fr->tag_array2->wl_leakage) * 1e3 << endl; cout << "\tTotal leakage power in column logic(mW): " << (fr->tag_array2->cl_leakage) * 1e3 << endl; cout << "\tTotal gate leakage power in H-tree (that includes both " "address and data network) ((mW)): " << (fr->tag_array2->power_addr_input_htree.readOp.gate_leakage + fr->tag_array2->power_data_output_htree.readOp.gate_leakage + fr->tag_array2->power_routing_to_bank.readOp.gate_leakage) * 1e3 << endl; } cout << endl << endl << "Area Components:" << endl << endl; /* Data array area stats */ if (!(g_ip->pure_cam || g_ip->fully_assoc)) cout << " Data array: Area (mm2): " << fr->data_array2->area * 1e-6 << endl; else if (g_ip->pure_cam) cout << " CAM array: Area (mm2): " << fr->data_array2->area * 1e-6 << endl; else cout << " Fully associative cache array: Area (mm2): " << fr->data_array2->area * 1e-6 << endl; cout << "\tHeight (mm): " << fr->data_array2->all_banks_height * 1e-3 << endl; cout << "\tWidth (mm): " << fr->data_array2->all_banks_width * 1e-3 << endl; if (g_ip->print_detail) { cout << "\tArea efficiency (Memory cell area/Total area) - " << fr->data_array2->area_efficiency << " %" << endl; cout << "\t\tBank Height (mm): " << fr->data_array2->bank_height * 1e-3 << endl; cout << "\t\tBank Length (mm): " << fr->data_array2->bank_length * 1e-3 << endl; cout << "\t\tMAT Height (mm): " << fr->data_array2->mat_height * 1e-3 << endl; cout << "\t\tMAT Length (mm): " << fr->data_array2->mat_length * 1e-3 << endl; cout << "\t\tSubarray Height (mm): " << fr->data_array2->subarray_height * 1e-3 << endl; cout << "\t\tSubarray Length (mm): " << fr->data_array2->subarray_length * 1e-3 << endl; } /* Tag array area stats */ if ((!(g_ip->pure_ram || g_ip->pure_cam || g_ip->fully_assoc)) && !g_ip->is_main_mem) { cout << endl << " Tag array: Area (mm2): " << fr->tag_array2->area * 1e-6 << endl; cout << "\tHeight (mm): " << fr->tag_array2->all_banks_height * 1e-3 << endl; cout << "\tWidth (mm): " << fr->tag_array2->all_banks_width * 1e-3 << endl; if (g_ip->print_detail) { cout << "\tArea efficiency (Memory cell area/Total area) - " << fr->tag_array2->area_efficiency << " %" << endl; cout << "\t\tMAT Height (mm): " << fr->tag_array2->mat_height * 1e-3 << endl; cout << "\t\tMAT Length (mm): " << fr->tag_array2->mat_length * 1e-3 << endl; cout << "\t\tSubarray Height (mm): " << fr->tag_array2->subarray_height * 1e-3 << endl; cout << "\t\tSubarray Length (mm): " << fr->tag_array2->subarray_length * 1e-3 << endl; } } } // if (!g_ip->is_3d_mem) Wire wpr; //wpr.print_wire(); // cout << "FO4 = " << g_tp.FO4 << endl; } } void output_data_csv_3dd(const uca_org_t& fin_res) { // TODO: the csv output should remain fstream file("out.csv", ios::in); bool print_index = file.fail(); file.close(); file.open("out.csv", ios::out | ios::app); if (file.fail() == true) { cerr << "File out.csv could not be opened successfully" << endl; } else { // print_index = false; if (print_index == true) { file << "Tech node (nm), "; file << "Number of tiers, "; file << "Capacity (MB) per die, "; file << "Number of banks, "; file << "Page size in bits, "; // file << "Output width (bits), "; file << "Burst depth, "; file << "IO width, "; file << "Ndwl, "; file << "Ndbl, "; file << "N rows in subarray, "; file << "N cols in subarray, "; // file << "Access time (ns), "; // file << "Random cycle time (ns), "; // file << "Multisubbank interleave cycle time (ns), "; // file << "Delay request network (ns), "; // file << "Delay inside mat (ns), "; // file << "Delay reply network (ns), "; // file << "Tag array access time (ns), "; // file << "Data array access time (ns), "; // file << "Refresh period (microsec), "; // file << "DRAM array availability (%), "; // file << "Dynamic search energy (nJ), "; // file << "Dynamic read energy (nJ), "; // file << "Dynamic write energy (nJ), "; // file << "Tag Dynamic read energy (nJ), "; // file << "Data Dynamic read energy (nJ), "; // file << "Dynamic read power (mW), "; // file << "Standby leakage per bank(mW), "; // file << "Leakage per bank with leak power management (mW), "; // file << "Leakage per bank with leak power management (mW), "; // file << "Refresh power as percentage of standby leakage, "; file << "Area (mm2), "; // file << "Nspd, "; // file << "Ndcm, "; // file << "Ndsam_level_1, "; // file << "Ndsam_level_2, "; file << "Data arrary area efficiency %, "; // file << "Ntwl, "; // file << "Ntbl, "; // file << "Ntspd, "; // file << "Ntcm, "; // file << "Ntsam_level_1, "; // file << "Ntsam_level_2, "; // file << "Tag arrary area efficiency %, "; // file << "Resistance per unit micron (ohm-micron), "; // file << "Capacitance per unit micron (fF per micron), "; // file << "Unit-length wire delay (ps), "; // file << "FO4 delay (ps), "; // file << "delay route to bank (including crossb delay) (ps), "; // file << "Crossbar delay (ps), "; // file << "Dyn read energy per access from closed page (nJ), "; // file << "Dyn read energy per access from open page (nJ), "; // file << "Leak power of an subbank with page closed (mW), "; // file << "Leak power of a subbank with page open (mW), "; // file << "Leak power of request and reply networks (mW), "; // file << "Number of subbanks, "; file << "Number of TSVs in total, "; file << "Delay of TSVs (ns) worst case, "; file << "Area of TSVs (mm2) in total, "; file << "Energy of TSVs (nJ) per access, "; file << "t_RCD (ns), "; file << "t_RAS (ns), "; file << "t_RC (ns), "; file << "t_CAS (ns), "; file << "t_RP (ns), "; file << "Activate energy (nJ), "; file << "Read energy (nJ), "; file << "Write energy (nJ), "; file << "Precharge energy (nJ), "; // file << "tRCD, "; // file << "CAS latency, "; // file << "Precharge delay, "; // file << "Perc dyn energy bitlines, "; // file << "perc dyn energy wordlines, "; // file << "perc dyn energy outside mat, "; // file << "Area opt (perc), "; // file << "Delay opt (perc), "; // file << "Repeater opt (perc), "; // file << "Aspect ratio"; file << "t_RRD (ns), "; file << "Number tiers for a row, "; file << "Number tiers for a column, "; file << "delay_row_activate_net, "; file << "delay_row_predecode_driver_and_block, "; file << "delay_row_decoder, "; file << "delay_local_wordline , "; file << "delay_bitlines, "; file << "delay_sense_amp, "; file << "delay_column_access_net, "; file << "delay_column_predecoder, "; file << "delay_column_decoder, "; file << "delay_column_selectline, "; file << "delay_datapath_net, "; file << "delay_global_data, "; file << "delay_local_data_and_drv, "; file << "delay_data_buffer, "; file << "delay_subarray_output_driver, "; file << "energy_row_activate_net, "; file << "energy_row_predecode_driver_and_block, "; file << "energy_row_decoder, "; file << "energy_local_wordline, "; file << "energy_bitlines, "; file << "energy_sense_amp, "; file << "energy_column_access_net, "; file << "energy_column_predecoder, "; file << "energy_column_decoder, "; file << "energy_column_selectline, "; file << "energy_datapath_net, "; file << "energy_global_data, "; file << "energy_local_data_and_drv, "; file << "energy_subarray_output_driver, "; file << "energy_data_buffer, "; file << "area_subarray, "; file << "area_lwl_drv, "; file << "area_row_predec_dec, "; file << "area_col_predec_dec, "; file << "area_bus, "; file << "area_address_bus, "; file << "area_data_bus, "; file << "area_data_drv, "; file << "area_IOSA, "; file << endl; } file << g_ip->F_sz_nm << ", "; file << g_ip->num_die_3d << ", "; file << g_ip->cache_sz * 1024 / g_ip->num_die_3d << ", "; file << g_ip->nbanks << ", "; file << g_ip->page_sz_bits << ", "; // file << g_ip->tag_assoc << ", "; // file << g_ip->out_w << ", "; file << g_ip->burst_depth << ", "; file << g_ip->io_width << ", "; file << fin_res.data_array2->Ndwl << ", "; file << fin_res.data_array2->Ndbl << ", "; file << fin_res.data_array2->num_row_subarray << ", "; file << fin_res.data_array2->num_col_subarray << ", "; // file << fin_res.access_time*1e+9 << ", "; // file << fin_res.cycle_time*1e+9 << ", "; // file << fin_res.data_array2->multisubbank_interleave_cycle_time*1e+9 << ", "; // file << fin_res.data_array2->delay_request_network*1e+9 << ", "; // file << fin_res.data_array2->delay_inside_mat*1e+9 << ", "; // file << fin_res.data_array2.delay_reply_network*1e+9 << ", "; // if (!(g_ip->fully_assoc || g_ip->pure_cam || g_ip->pure_ram)) // { // file << fin_res.tag_array2->access_time*1e+9 << ", "; // } // else // { // file << 0 << ", "; // } // file << fin_res.data_array2->access_time*1e+9 << ", "; // file << fin_res.data_array2->dram_refresh_period*1e+6 << ", "; // file << fin_res.data_array2->dram_array_availability << ", "; /* if (g_ip->fully_assoc || g_ip->pure_cam) { file << fin_res.power.searchOp.dynamic*1e+9 << ", "; } else { file << "N/A" << ", "; } */ // file << fin_res.power.readOp.dynamic*1e+9 << ", "; // file << fin_res.power.writeOp.dynamic*1e+9 << ", "; // if (!(g_ip->fully_assoc || g_ip->pure_cam || g_ip->pure_ram)) // { // file << fin_res.tag_array2->power.readOp.dynamic*1e+9 << ", "; // } // else // { // file << "NA" << ", "; // } // file << fin_res.data_array2->power.readOp.dynamic*1e+9 << ", "; // if (g_ip->fully_assoc || g_ip->pure_cam) // { // file << fin_res.power.searchOp.dynamic*1000/fin_res.cycle_time << ", "; // } // else // { // file << fin_res.power.readOp.dynamic*1000/fin_res.cycle_time << ", "; // } // file <<( fin_res.power.readOp.leakage + fin_res.power.readOp.gate_leakage )*1000 << ", "; // file << fin_res.leak_power_with_sleep_transistors_in_mats*1000 << ", "; // file << fin_res.data_array.refresh_power / fin_res.data_array.total_power.readOp.leakage << ", "; file << fin_res.data_array2->area * 1e-6 << ", "; // file << fin_res.data_array2->Nspd << ", "; // file << fin_res.data_array2->deg_bl_muxing << ", "; // file << fin_res.data_array2->Ndsam_lev_1 << ", "; // file << fin_res.data_array2->Ndsam_lev_2 << ", "; file << fin_res.data_array2->area_efficiency << ", "; /* if (!(g_ip->fully_assoc || g_ip->pure_cam || g_ip->pure_ram)) { file << fin_res.tag_array2->Ndwl << ", "; file << fin_res.tag_array2->Ndbl << ", "; file << fin_res.tag_array2->Nspd << ", "; file << fin_res.tag_array2->deg_bl_muxing << ", "; file << fin_res.tag_array2->Ndsam_lev_1 << ", "; file << fin_res.tag_array2->Ndsam_lev_2 << ", "; file << fin_res.tag_array2->area_efficiency << ", "; } else { file << "N/A" << ", "; file << "N/A"<< ", "; file << "N/A" << ", "; file << "N/A" << ", "; file << "N/A" << ", "; file << "N/A" << ", "; file << "N/A" << ", "; } */ file << fin_res.data_array2->num_TSV_tot << ", "; file << fin_res.data_array2->delay_TSV_tot * 1e9 << ", "; file << fin_res.data_array2->area_TSV_tot * 1e-6 << ", "; file << fin_res.data_array2->dyn_pow_TSV_per_access * 1e9 << ", "; file << fin_res.data_array2->t_RCD * 1e9 << ", "; file << fin_res.data_array2->t_RAS * 1e9 << ", "; file << fin_res.data_array2->t_RC * 1e9 << ", "; file << fin_res.data_array2->t_CAS * 1e9 << ", "; file << fin_res.data_array2->t_RP * 1e9 << ", "; // file << g_tp.wire_inside_mat.R_per_um << ", "; // file << g_tp.wire_inside_mat.C_per_um / 1e-15 << ", "; // file << g_tp.unit_len_wire_del / 1e-12 << ", "; // file << g_tp.FO4 / 1e-12 << ", "; // file << fin_res.data_array.delay_route_to_bank / 1e-9 << ", "; // file << fin_res.data_array.delay_crossbar / 1e-9 << ", "; // file << fin_res.data_array.dyn_read_energy_from_closed_page / 1e-9 << ", "; // file << fin_res.data_array.dyn_read_energy_from_open_page / 1e-9 << ", "; // file << fin_res.data_array.leak_power_subbank_closed_page / 1e-3 << ", "; // file << fin_res.data_array.leak_power_subbank_open_page / 1e-3 << ", "; // file << fin_res.data_array.leak_power_request_and_reply_networks / 1e-3 << ", "; // file << fin_res.data_array.number_subbanks << ", " ; // file << fin_res.data_array.page_size_in_bits << ", " ; file << fin_res.data_array2->activate_energy * 1e9 << ", "; file << fin_res.data_array2->read_energy * 1e9 << ", "; file << fin_res.data_array2->write_energy * 1e9 << ", "; file << fin_res.data_array2->precharge_energy * 1e9 << ", "; // file << fin_res.data_array.trcd * 1e9 << ", " ; // file << fin_res.data_array.cas_latency * 1e9 << ", " ; // file << fin_res.data_array.precharge_delay * 1e9 << ", " ; // file << fin_res.data_array.all_banks_height / fin_res.data_array.all_banks_width; file << fin_res.data_array2->t_RRD * 1e9 << ", "; file << g_ip->num_tier_row_sprd << ", "; file << g_ip->num_tier_col_sprd << ", "; file << fin_res.data_array2->delay_row_activate_net * 1e9 << ", "; file << fin_res.data_array2->delay_row_predecode_driver_and_block * 1e9 << ", "; file << fin_res.data_array2->delay_row_decoder * 1e9 << ", "; file << fin_res.data_array2->delay_local_wordline * 1e9 << ", "; file << fin_res.data_array2->delay_bitlines * 1e9 << ", "; file << fin_res.data_array2->delay_sense_amp * 1e9 << ", "; file << fin_res.data_array2->delay_column_access_net * 1e9 << ", "; file << fin_res.data_array2->delay_column_predecoder * 1e9 << ", "; file << fin_res.data_array2->delay_column_decoder * 1e9 << ", "; file << fin_res.data_array2->delay_column_selectline * 1e9 << ", "; file << fin_res.data_array2->delay_datapath_net * 1e9 << ", "; file << fin_res.data_array2->delay_global_data * 1e9 << ", "; file << fin_res.data_array2->delay_local_data_and_drv * 1e9 << ", "; file << fin_res.data_array2->delay_data_buffer * 1e9 << ", "; file << fin_res.data_array2->delay_subarray_output_driver * 1e9 << ", "; file << fin_res.data_array2->energy_row_activate_net * 1e9 << ", "; file << fin_res.data_array2->energy_row_predecode_driver_and_block * 1e9 << ", "; file << fin_res.data_array2->energy_row_decoder * 1e9 << ", "; file << fin_res.data_array2->energy_local_wordline * 1e9 << ", "; file << fin_res.data_array2->energy_bitlines * 1e9 << ", "; file << fin_res.data_array2->energy_sense_amp * 1e9 << ", "; file << fin_res.data_array2->energy_column_access_net * 1e9 << ", "; file << fin_res.data_array2->energy_column_predecoder * 1e9 << ", "; file << fin_res.data_array2->energy_column_decoder * 1e9 << ", "; file << fin_res.data_array2->energy_column_selectline * 1e9 << ", "; file << fin_res.data_array2->energy_datapath_net * 1e9 << ", "; file << fin_res.data_array2->energy_global_data * 1e9 << ", "; file << fin_res.data_array2->energy_local_data_and_drv * 1e9 << ", "; file << fin_res.data_array2->energy_subarray_output_driver * 1e9 << ", "; file << fin_res.data_array2->energy_data_buffer * 1e9 << ", "; file << fin_res.data_array2->area_subarray / 1e6 << ", "; file << fin_res.data_array2->area_lwl_drv / 1e6 << ", "; file << fin_res.data_array2->area_row_predec_dec / 1e6 << ", "; file << fin_res.data_array2->area_col_predec_dec / 1e6 << ", "; file << fin_res.data_array2->area_bus / 1e6 << ", "; file << fin_res.data_array2->area_address_bus / 1e6 << ", "; file << fin_res.data_array2->area_data_bus / 1e6 << ", "; file << fin_res.data_array2->area_data_drv / 1e6 << ", "; file << fin_res.data_array2->area_IOSA / 1e6 << ", "; file << fin_res.data_array2->area_sense_amp / 1e6 << ", "; file << endl; } file.close(); }
57.182151
160
0.521326
SNU-HPCS
8a264ac95f1ea7e968c72bea81e7155e5b33fa58
1,736
cc
C++
descriptor/tunnel_desc.cc
chris-nada/simutrans-extended
71c0c4f78cb3170b1fa1c68d8baafa9a7269ef6f
[ "Artistic-1.0" ]
38
2017-07-26T14:48:12.000Z
2022-03-24T23:48:55.000Z
descriptor/tunnel_desc.cc
chris-nada/simutrans-extended
71c0c4f78cb3170b1fa1c68d8baafa9a7269ef6f
[ "Artistic-1.0" ]
74
2017-03-15T21:07:34.000Z
2022-03-18T07:53:11.000Z
descriptor/tunnel_desc.cc
chris-nada/simutrans-extended
71c0c4f78cb3170b1fa1c68d8baafa9a7269ef6f
[ "Artistic-1.0" ]
43
2017-03-10T15:27:28.000Z
2022-03-05T10:55:38.000Z
/* * This file is part of the Simutrans-Extended project under the Artistic License. * (see LICENSE.txt) */ #include <stdio.h> #include "../dataobj/ribi.h" #include "tunnel_desc.h" #include "../network/checksum.h" int tunnel_desc_t::slope_indices[81] = { -1, // 0: -1, // 1: -1, // 2: -1, // 3: 1, // 4:north slope -1, // 5: -1, // 6: -1, // 7: 1, // 8:north slope -1, // 9: -1, // 10: -1, // 11: 2, // 12:west slope -1, // 13: -1, // 14: -1, // 15: -1, // 16: -1, // 17: -1, // 18: -1, // 19: -1, // 20: -1, // 21: -1, // 22: -1, // 23: 2, // 24:west slope -1, // 25: -1, // 26: -1, // 27: 3, // 28:east slope -1, // 29: -1, // 30: -1, // 31: -1, // 32: -1, // 33: -1, // 34: -1, // 35: 0, // 36:south slope -1, // 37: -1, // 38: -1, // 39: -1, // 40: -1, // 41: -1, // 42: -1, // 43: -1, // 44: -1, // 45: -1, // 46: -1, // 47: -1, // 48: -1, // 49: -1, // 50: -1, // 51: -1, // 52: -1, // 53: -1, // 54: -1, // 55: 3, // 56:east slope -1, // 57: -1, // 58: -1, // 59: -1, // 60: -1, // 61: -1, // 62: -1, // 63: -1, // 64: -1, // 65: -1, // 66: -1, // 67: -1, // 68: -1, // 69: -1, // 70: -1, // 71: 0, // 72:south slope -1, // 73: -1, // 74: -1, // 75: -1, // 76: -1, // 77: -1, // 78: -1, // 79: -1 // 80: }; void tunnel_desc_t::calc_checksum(checksum_t *chk) const { obj_desc_transport_infrastructure_t::calc_checksum(chk); //Extended settings //chk->input(max_axle_load); chk->input(way_constraints.get_permissive()); chk->input(way_constraints.get_prohibitive()); } waytype_t tunnel_desc_t::get_finance_waytype() const { return ((get_way_desc() && (get_way_desc()->get_styp() == type_tram)) ? tram_wt : get_waytype()) ; }
15.63964
99
0.46947
chris-nada
8a26b9b2b384b4431ec6210bbb1ae9c7a87225ef
2,089
cpp
C++
1304-D.cpp
ankiiitraj/questionsSolved
8452b120935a9c3d808b45f27dcdc05700d902fc
[ "MIT" ]
null
null
null
1304-D.cpp
ankiiitraj/questionsSolved
8452b120935a9c3d808b45f27dcdc05700d902fc
[ "MIT" ]
1
2020-02-24T19:45:57.000Z
2020-02-24T19:45:57.000Z
1304-D.cpp
ankiiitraj/questionsSolved
8452b120935a9c3d808b45f27dcdc05700d902fc
[ "MIT" ]
null
null
null
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Author : Ankit Raj // Problem Name : Cow and Secret Message // Problem Link : https://codeforces.com/contest/1304/problem/D // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * #include <bits/stdc++.h> #define int long long int #define len length #define pb push_back #define F first #define S second #define debug cout << "Debugging . . .\n"; #define faster ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL) using namespace std; vector <int> adj[200005]; vector <int> BFS(int s, int dest, int n) { bool visited[n +1] = {0}; vector <int> dist(n +1, 0); queue <int> q; q.push(s); dist[s] = 0; visited[s] = 1; while(!q.empty()) { int cur = q.front(); q.pop(); for(auto itr: adj[cur]) { if(visited[itr] == 0) { q.push(itr); dist[itr] = dist[cur] +1; visited[itr] = 1; } } } return dist; } int32_t main() { faster; #ifndef ONLINE_JUDGE freopen("ip.txt", "r", stdin); freopen("op.txt", "w", stdout); #endif // int t; cin >> t; while(t--) { int n, m, k, x, y, temp; cin >> n >> m >> k; for (int i = 0; i < n; ++i) adj[i].clear(); int a[k]; for (int i = 0; i < k; ++i) { cin >> a[i]; } for (int i = 0; i < m; ++i) { cin >> x >> y; adj[x].pb(y); adj[y].pb(x); } vector <int> fromOne, fromN; fromOne = BFS(1, n, n); fromN = BFS(n, 1, n); map<int, int> mScore; for(int i = 0; i < k; ++i) { mScore.insert({fromOne[a[i]] - fromN[a[i]], a[i]}); } // sort(mScore.begin(), mScore.end()); int _max = -1000000000000, longestShortestPath = 0; for(auto &itr:mScore) { longestShortestPath = max(longestShortestPath, _max + fromN[itr.second]); _max = max(_max, fromOne[itr.second]); } cout << min(longestShortestPath +1, fromOne[n]) << endl; } return 0; }
23.738636
91
0.471996
ankiiitraj
8a2804ac58cb8794eb53f820c2a1f78af57ae4c9
1,696
cpp
C++
October 2021/October 4, 2021/max_and_min_mileage_of_cars/main.cpp
thismrojek/hard_school_exercises
1108b5e5c67625ad95b04c9390d05c334c601218
[ "MIT" ]
null
null
null
October 2021/October 4, 2021/max_and_min_mileage_of_cars/main.cpp
thismrojek/hard_school_exercises
1108b5e5c67625ad95b04c9390d05c334c601218
[ "MIT" ]
null
null
null
October 2021/October 4, 2021/max_and_min_mileage_of_cars/main.cpp
thismrojek/hard_school_exercises
1108b5e5c67625ad95b04c9390d05c334c601218
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main(int argc, char** argv) { int carsMileage[3][4] = { { 35000, 22145, 45981, 31012 }, { 26771, 34121, 36900, 22096 }, { 45332, 41100, 39498, 44128 } }; int sumaricCarsMileage[3]; int carWithMinMileage, carWithMaxMileage; for (int car = 0; car < 3; car++) { for (int month = 0; month < 4; month++) { sumaricCarsMileage[car] += carsMileage[car][month]; } } for (int car = 0; car < 3; car++) { if (sumaricCarsMileage[car] > sumaricCarsMileage[car + 1]) { carWithMaxMileage = car; } else if (sumaricCarsMileage[car] < sumaricCarsMileage[car + 1]) { carWithMinMileage = car; } } cout << "Auto z najwiekszym przebiegiem: " << (carWithMaxMileage + 1) << endl; cout << "Auto z najmniejszym przebiegiem: " << (carWithMinMileage + 1) << endl; for (int car = 0; car < 3; car++) { cout << "Laczny przebieg auta nr: " << (car + 1) << " wynosi: " << sumaricCarsMileage[car] << ", a sredni przebieg miesieczny: " << (sumaricCarsMileage[car] / 4) << endl; } for (int car = 0; car < 3; car++) { if (carsMileage[car][0] % 2 == 0 && carsMileage[car][1] % 2 == 0 && carsMileage[car][2] % 2 == 0 && carsMileage[car][3] % 2 == 0 ) { cout << "Samochod nr: " << (car + 1) << "posiada wszystkie wartosci przebiegu jako liczbe patrzysta." << endl; } } return 0; }
27.803279
178
0.482311
thismrojek
8a2835f30a01491588b28b84034e9507c3c5dfce
3,559
hpp
C++
src/wrapper/AmxInstanceManager.hpp
eupedroosouza/ShoebillPlugin
49bc98348061f08c8ec6e1ce9919d6736656bee9
[ "Apache-2.0" ]
6
2016-06-18T02:06:02.000Z
2020-10-17T12:25:54.000Z
src/wrapper/AmxInstanceManager.hpp
eupedroosouza/ShoebillPlugin
49bc98348061f08c8ec6e1ce9919d6736656bee9
[ "Apache-2.0" ]
13
2015-11-13T13:00:33.000Z
2021-12-09T13:49:52.000Z
src/wrapper/AmxInstanceManager.hpp
eupedroosouza/ShoebillPlugin
49bc98348061f08c8ec6e1ce9919d6736656bee9
[ "Apache-2.0" ]
7
2017-03-01T15:02:34.000Z
2022-03-13T16:22:21.000Z
/** * Copyright (C) 2014 MK124 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef __AMXINSTANCEMANAGER__ #define __AMXINSTANCEMANAGER__ #include <unordered_set> #include "amx/amx.h" #include <map> #include <vector> class AmxInstanceManager { public: static AmxInstanceManager &GetInstance() { static AmxInstanceManager instance; return instance; } AmxInstanceManager() { } ~AmxInstanceManager() { } void RegisterAmx(AMX *amx) { if (!IsValid(amx)) { amxInstances.insert(amx); registeredFunctions[amx] = std::map<std::string, std::vector<std::string>>(); } } void UnregisterAmx(AMX *amx) { if (IsValid(amx)) { registeredFunctions.erase(registeredFunctions.find(amx)); amxInstances.erase(amx); if (mainAmx == amx) mainAmx = nullptr; } } bool IsValid(AMX *amx) { return amxInstances.find(amx) != amxInstances.end(); } void MarkAsMainAmx(AMX *amx) { if (!IsValid(amx)) return; mainAmx = amx; } bool RegisteredFunctionExists(AMX *amx, std::string functionName) { return registeredFunctions[amx].find(functionName) != registeredFunctions[amx].end(); } bool RegisterFunction(AMX *amx, std::string functionName, std::vector<std::string> types) { if (RegisteredFunctionExists(amx, functionName)) return false; registeredFunctions[amx][functionName] = types; return true; } std::vector<std::string> GetParameterTypes(AMX *amx, std::string functionName) { if (!RegisteredFunctionExists(amx, functionName)) return std::vector<std::string>(); return registeredFunctions[amx][functionName]; } bool UnregisterFunction(AMX *amx, std::string functionName) { if (!RegisteredFunctionExists(amx, functionName)) return false; registeredFunctions[amx].erase(registeredFunctions[amx].find(functionName)); return true; } AMX *GetMainAmx() const { return mainAmx; } AMX *GetAvailableAmx() { if (mainAmx != nullptr) return mainAmx; if (amxInstances.empty()) return nullptr; return *amxInstances.begin(); } std::unordered_set<AMX *> GetInstances() { std::unordered_set<AMX *> copyOfInstances; for (auto it = amxInstances.begin(); it != amxInstances.end(); ++it) { copyOfInstances.insert(*it); } return copyOfInstances; } private: std::unordered_set<AMX *> amxInstances; AMX *mainAmx = nullptr; std::map<AMX *, std::map<std::string, std::vector<std::string>>> registeredFunctions; AmxInstanceManager(const AmxInstanceManager &) = delete; AmxInstanceManager &operator=(const AmxInstanceManager &) = delete; }; #endif
27.589147
94
0.615341
eupedroosouza
8a287d8f521eaecbf9bea96ed2208a01180cdbad
926
cpp
C++
PSME/application/src/rest/http/http_defs.cpp
opencomputeproject/HWMgmt-DeviceMgr-PSME
2a00188aab6f4bef3776987f0842ef8a8ea972ac
[ "Apache-2.0" ]
5
2021-10-07T15:36:37.000Z
2022-03-01T07:21:49.000Z
PSME/application/src/rest/http/http_defs.cpp
opencomputeproject/HWMgmt-DeviceMgr-PSME
2a00188aab6f4bef3776987f0842ef8a8ea972ac
[ "Apache-2.0" ]
null
null
null
PSME/application/src/rest/http/http_defs.cpp
opencomputeproject/HWMgmt-DeviceMgr-PSME
2a00188aab6f4bef3776987f0842ef8a8ea972ac
[ "Apache-2.0" ]
1
2022-03-01T07:21:51.000Z
2022-03-01T07:21:51.000Z
/*! * @section LICENSE * * @copyright * Copyright (c) 2015-2017 Intel Corporation * * @copyright * 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 * * @copyright * http://www.apache.org/licenses/LICENSE-2.0 * * @copyright * 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. * * @section Definition of mime types * * */ #include "psme/rest/http/http_defs.hpp" using psme::rest::http::MimeType; constexpr const char MimeType::JSON[]; constexpr const char MimeType::XML[]; constexpr const char MimeType::TXT[];
28.060606
75
0.725702
opencomputeproject
8a2a9b91a6b38fbe768b27a6744e9f288061e93f
389
cpp
C++
WaveSabreCore/src/AllPassDelay.cpp
LeStahL/WaveSabre
2a603ac1b3e9c30390a977f5bfb71766552e9c62
[ "MIT" ]
228
2019-02-18T19:13:31.000Z
2022-03-30T00:52:55.000Z
WaveSabreCore/src/AllPassDelay.cpp
LeStahL/WaveSabre
2a603ac1b3e9c30390a977f5bfb71766552e9c62
[ "MIT" ]
64
2019-02-20T17:38:47.000Z
2022-01-25T20:21:00.000Z
WaveSabreCore/src/AllPassDelay.cpp
thijskruithof/WaveSabre
d2d0c76432284a86780deda45b35a9aa9377d79e
[ "MIT" ]
31
2019-02-20T14:16:40.000Z
2022-01-05T11:25:52.000Z
#include <WaveSabreCore/AllPassDelay.h> #include <WaveSabreCore/Helpers.h> #include <math.h> namespace WaveSabreCore { AllPassDelay::AllPassDelay() { a1 = 0.0f; zm1 = 0.0f; } void AllPassDelay::Delay(float delay) { a1 = (1.f - delay) / (1.f + delay); } float AllPassDelay::Update(float inSamp) { float y = inSamp * -a1 + zm1; zm1 = y * a1 + inSamp; return y; } }
14.407407
41
0.634961
LeStahL
8a2d1dd3e780e2d41a7f50414caebd18dce6b535
8,701
cc
C++
content/public/browser/arc_tracing_agent.cc
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2021-05-24T13:52:28.000Z
2021-05-24T13:53:10.000Z
content/public/browser/arc_tracing_agent.cc
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
content/public/browser/arc_tracing_agent.cc
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
3
2018-03-12T07:58:10.000Z
2019-08-31T04:53:58.000Z
// Copyright 2017 The Chromium 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 "content/public/browser/arc_tracing_agent.h" #include <memory> #include <string> #include <utility> #include <vector> #include "base/bind.h" #include "base/bind_helpers.h" #include "base/files/file.h" #include "base/files/file_descriptor_watcher_posix.h" #include "base/logging.h" #include "base/memory/ptr_util.h" #include "base/memory/singleton.h" #include "base/memory/weak_ptr.h" #include "base/posix/unix_domain_socket_linux.h" #include "base/threading/sequenced_task_runner_handle.h" #include "base/threading/thread_task_runner_handle.h" #include "base/time/time.h" #include "cc/base/ring_buffer.h" #include "content/public/browser/browser_thread.h" namespace content { namespace { // The maximum size used to store one trace event. The ad hoc trace format for // atrace is 1024 bytes. Here we add additional size as we're using JSON and // have additional data fields. constexpr size_t kArcTraceMessageLength = 1024 + 512; constexpr char kArcTracingAgentName[] = "arc"; constexpr char kArcTraceLabel[] = "ArcTraceEvents"; // Number of events for the ring buffer. constexpr size_t kTraceEventBufferSize = 64000; // A helper class for reading trace data from the client side. We separate this // from |ArcTracingAgentImpl| to isolate the logic that runs on browser's IO // thread. All the functions in this class except for constructor, destructor, // and |GetWeakPtr| are expected to be run on browser's IO thread. class ArcTracingReader { public: using StopTracingCallback = base::Callback<void(const scoped_refptr<base::RefCountedString>&)>; ArcTracingReader() : weak_ptr_factory_(this) {} void StartTracing(base::ScopedFD read_fd) { DCHECK_CURRENTLY_ON(BrowserThread::IO); read_fd_ = std::move(read_fd); // We don't use the weak pointer returned by |GetWeakPtr| to avoid using it // on different task runner. Instead, we use |base::Unretained| here as // |fd_watcher_| is always destroyed before |this| is destroyed. fd_watcher_ = base::FileDescriptorWatcher::WatchReadable( read_fd_.get(), base::Bind(&ArcTracingReader::OnTraceDataAvailable, base::Unretained(this))); } void OnTraceDataAvailable() { DCHECK_CURRENTLY_ON(BrowserThread::IO); char buf[kArcTraceMessageLength]; std::vector<base::ScopedFD> unused_fds; ssize_t n = base::UnixDomainSocket::RecvMsg( read_fd_.get(), buf, kArcTraceMessageLength, &unused_fds); // When EOF, return and do nothing. The clean up is done in StopTracing. if (n == 0) return; if (n < 0) { DPLOG(WARNING) << "Unexpected error while reading trace from client."; // Do nothing here as StopTracing will do the clean up and the existing // trace logs will be returned. return; } if (n > static_cast<ssize_t>(kArcTraceMessageLength)) { DLOG(WARNING) << "Unexpected data size when reading trace from client."; return; } ring_buffer_.SaveToBuffer(std::string(buf, n)); } void StopTracing(const StopTracingCallback& callback) { DCHECK_CURRENTLY_ON(BrowserThread::IO); fd_watcher_.reset(); read_fd_.reset(); bool append_comma = false; std::string data; for (auto it = ring_buffer_.Begin(); it; ++it) { if (append_comma) data.append(","); else append_comma = true; data.append(**it); } ring_buffer_.Clear(); BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::Bind(callback, base::RefCountedString::TakeString(&data))); } base::WeakPtr<ArcTracingReader> GetWeakPtr() { return weak_ptr_factory_.GetWeakPtr(); } private: base::ScopedFD read_fd_; std::unique_ptr<base::FileDescriptorWatcher::Controller> fd_watcher_; cc::RingBuffer<std::string, kTraceEventBufferSize> ring_buffer_; // NOTE: Weak pointers must be invalidated before all other member variables // so it must be the last member. base::WeakPtrFactory<ArcTracingReader> weak_ptr_factory_; DISALLOW_COPY_AND_ASSIGN(ArcTracingReader); }; class ArcTracingAgentImpl : public ArcTracingAgent { public: // base::trace_event::TracingAgent overrides: std::string GetTracingAgentName() override { return kArcTracingAgentName; } std::string GetTraceEventLabel() override { return kArcTraceLabel; } void StartAgentTracing(const base::trace_event::TraceConfig& trace_config, const StartAgentTracingCallback& callback) override { DCHECK_CURRENTLY_ON(BrowserThread::UI); // delegate_ may be nullptr if ARC is not enabled on the system. In such // case, simply do nothing. bool success = (delegate_ != nullptr); base::ScopedFD write_fd, read_fd; success = success && CreateSocketPair(&read_fd, &write_fd); if (!success) { // Use PostTask as the convention of TracingAgent. The caller expects // callback to be called after this function returns. base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(callback, GetTracingAgentName(), false)); return; } BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::Bind(&ArcTracingReader::StartTracing, reader_.GetWeakPtr(), base::Passed(&read_fd))); delegate_->StartTracing(trace_config, std::move(write_fd), base::Bind(callback, GetTracingAgentName())); } void StopAgentTracing(const StopAgentTracingCallback& callback) override { DCHECK_CURRENTLY_ON(BrowserThread::UI); if (is_stopping_) { DLOG(WARNING) << "Already working on stopping ArcTracingAgent."; return; } is_stopping_ = true; if (delegate_) { delegate_->StopTracing( base::Bind(&ArcTracingAgentImpl::OnArcTracingStopped, weak_ptr_factory_.GetWeakPtr(), callback)); } } // ArcTracingAgent overrides: void SetDelegate(Delegate* delegate) override { DCHECK_CURRENTLY_ON(BrowserThread::UI); delegate_ = delegate; } static ArcTracingAgentImpl* GetInstance() { return base::Singleton<ArcTracingAgentImpl>::get(); } private: // This allows constructor and destructor to be private and usable only // by the Singleton class. friend struct base::DefaultSingletonTraits<ArcTracingAgentImpl>; ArcTracingAgentImpl() : weak_ptr_factory_(this) {} ~ArcTracingAgentImpl() override = default; void OnArcTracingStopped(const StopAgentTracingCallback& callback, bool success) { DCHECK_CURRENTLY_ON(BrowserThread::UI); if (!success) { DLOG(WARNING) << "Failed to stop ARC tracing."; callback.Run(GetTracingAgentName(), GetTraceEventLabel(), new base::RefCountedString()); is_stopping_ = false; return; } BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::Bind(&ArcTracingReader::StopTracing, reader_.GetWeakPtr(), base::Bind(&ArcTracingAgentImpl::OnTracingReaderStopped, weak_ptr_factory_.GetWeakPtr(), callback))); } void OnTracingReaderStopped( const StopAgentTracingCallback& callback, const scoped_refptr<base::RefCountedString>& data) { DCHECK_CURRENTLY_ON(BrowserThread::UI); callback.Run(GetTracingAgentName(), GetTraceEventLabel(), data); is_stopping_ = false; } Delegate* delegate_ = nullptr; // Owned by ArcServiceLauncher. // We use |reader_.GetWeakPtr()| when binding callbacks with its functions. // Notes that the weak pointer returned by it can only be deferenced or // invalided in the same task runner to avoid racing condition. The // destruction of |reader_| is also a source of invalidation. However, we're // lucky as we're using |ArcTracingAgentImpl| as a singleton, the // destruction is always performed after all MessageLoops are destroyed, and // thus there are no race conditions in such situation. ArcTracingReader reader_; bool is_stopping_ = false; // NOTE: Weak pointers must be invalidated before all other member variables // so it must be the last member. base::WeakPtrFactory<ArcTracingAgentImpl> weak_ptr_factory_; DISALLOW_COPY_AND_ASSIGN(ArcTracingAgentImpl); }; } // namespace // static ArcTracingAgent* ArcTracingAgent::GetInstance() { return ArcTracingAgentImpl::GetInstance(); } ArcTracingAgent::ArcTracingAgent() = default; ArcTracingAgent::~ArcTracingAgent() = default; ArcTracingAgent::Delegate::~Delegate() = default; } // namespace content
34.943775
79
0.70785
metux
8a2d5f60a15ee8f2c3ceba648e815e7427209038
1,012
cpp
C++
0600/00/602a.cpp
actium/cf
d7be128c3a9adb014a231a399f1c5f19e1ab2a38
[ "Unlicense" ]
1
2020-07-03T15:55:52.000Z
2020-07-03T15:55:52.000Z
0600/00/602a.cpp
actium/cf
d7be128c3a9adb014a231a399f1c5f19e1ab2a38
[ "Unlicense" ]
null
null
null
0600/00/602a.cpp
actium/cf
d7be128c3a9adb014a231a399f1c5f19e1ab2a38
[ "Unlicense" ]
3
2020-10-01T14:55:28.000Z
2021-07-11T11:33:58.000Z
#include <iostream> #include <vector> using integer = unsigned long long; template <typename T> std::istream& operator >>(std::istream& input, std::vector<T>& v) { for (T& a : v) input >> a; return input; } void answer(char v) { std::cout << v << '\n'; } integer convert(const std::vector<unsigned>& x, unsigned b) { integer y = 0; for (const unsigned d : x) { y *= b; y += d; } return y; } void solve(const std::vector<unsigned>& x, unsigned bx, const std::vector<unsigned>& y, unsigned by) { const integer u = convert(x, bx); const integer v = convert(y, by); if (u == v) return answer('='); answer(u < v ? '<' : '>'); } int main() { size_t n; std::cin >> n; unsigned bx; std::cin >> bx; std::vector<unsigned> x(n); std::cin >> x; size_t m; std::cin >> m; unsigned by; std::cin >> by; std::vector<unsigned> y(m); std::cin >> y; solve(x, bx, y, by); return 0; }
15.333333
100
0.527668
actium
8a308f674be5fcc99893e10bec4f21f21e7219f3
3,352
cpp
C++
rom.cpp
PJBoy/Fusion-level-editor
bf2779f5ab634fb6a3d499ee9c220c8d77992478
[ "0BSD" ]
4
2018-09-27T17:31:33.000Z
2021-12-24T12:46:14.000Z
rom.cpp
PJBoy/Metroid-level-editor
bf2779f5ab634fb6a3d499ee9c220c8d77992478
[ "0BSD" ]
null
null
null
rom.cpp
PJBoy/Metroid-level-editor
bf2779f5ab634fb6a3d499ee9c220c8d77992478
[ "0BSD" ]
null
null
null
//#include "sm.h" #include "global.h" import rom; import mf; import mzm; import Sm; Rom::Reader::Reader(std::filesystem::path filepath, index_t address /* = 0*/) try : f(filepath, std::ios::binary) { f.exceptions(std::ios::badbit | std::ios::failbit); seek(address); } LOG_RETHROW Rom::Rom(std::filesystem::path filepath) try : filepath(filepath) {} LOG_RETHROW Rom::Reader Rom::makeReader(index_t address /* = 0*/) const try { return Rom::Reader(filepath, address); } LOG_RETHROW std::ifstream Rom::makeIfstream() const try { std::ifstream f(filepath, std::ios::binary); f.exceptions(std::ios::badbit | std::ios::failbit); return f; } LOG_RETHROW bool Rom::verifyRom(std::filesystem::path filepath) noexcept try { loadRom(filepath); return true; } catch (const std::exception&) { return false; } std::unique_ptr<Rom> Rom::loadRom(std::filesystem::path filepath) try { try { return std::make_unique<Sm>(filepath); } catch (const std::exception&) {} try { return std::make_unique<Mf>(filepath); } catch (const std::exception&) {} try { return std::make_unique<Mzm>(filepath); } catch (const std::exception&) {} throw std::runtime_error("Not a valid ROM"s); } LOG_RETHROW /* void Rom::drawLevelView(Cairo::RefPtr<Cairo::Surface> p_surface, unsigned, unsigned) const try { Cairo::RefPtr<Cairo::ImageSurface> p_tile(Cairo::ImageSurface::create(Cairo::Format::FORMAT_ARGB32, 32, 32)); { Cairo::RefPtr<Cairo::Context> p_context(Cairo::Context::create(p_tile)); p_context->set_source_rgb(0, 1, 0); p_context->rectangle(4, 8, 28, 24); p_context->fill(); } Cairo::RefPtr<Cairo::Context> p_context(Cairo::Context::create(p_surface)); p_context->set_source(p_tile, 32, 64); p_context->paint(); } LOG_RETHROW void Rom::drawSpritemapView(Cairo::RefPtr<Cairo::Surface> p_surface, unsigned, unsigned) const try { Cairo::RefPtr<Cairo::ImageSurface> p_tile(Cairo::ImageSurface::create(Cairo::Format::FORMAT_ARGB32, 32, 32)); { Cairo::RefPtr<Cairo::Context> p_context(Cairo::Context::create(p_tile)); p_context->set_source_rgb(0, 1, 0); p_context->rectangle(4, 8, 28, 24); p_context->fill(); } Cairo::RefPtr<Cairo::Context> p_context(Cairo::Context::create(p_surface)); p_context->set_source(p_tile, 32, 64); p_context->paint(); } LOG_RETHROW void Rom::drawSpritemapTilesView(Cairo::RefPtr<Cairo::Surface> p_surface, unsigned, unsigned) const try { Cairo::RefPtr<Cairo::ImageSurface> p_tile(Cairo::ImageSurface::create(Cairo::Format::FORMAT_ARGB32, 32, 32)); { Cairo::RefPtr<Cairo::Context> p_context(Cairo::Context::create(p_tile)); p_context->set_source_rgb(0, 1, 0); p_context->rectangle(4, 8, 28, 24); p_context->fill(); } Cairo::RefPtr<Cairo::Context> p_context(Cairo::Context::create(p_surface)); p_context->set_source(p_tile, 32, 64); p_context->paint(); } LOG_RETHROW */ auto Rom::getRoomList() const -> std::vector<RoomList> { return {}; } auto Rom::getLevelViewDimensions() const -> Dimensions { return {}; } void Rom::loadLevelData(std::vector<long>) {} void Rom::loadSpritemap(index_t, index_t, index_t, index_t, index_t) {}
22.052632
113
0.660203
PJBoy
8a30a2d5d74959fcd1156be030fb783d27b12973
378
cpp
C++
components/xtl/tests/stl/mkheap1.cpp
untgames/funner
c91614cda55fd00f5631d2bd11c4ab91f53573a3
[ "MIT" ]
7
2016-03-30T17:00:39.000Z
2017-03-27T16:04:04.000Z
components/xtl/tests/stl/mkheap1.cpp
untgames/Funner
c91614cda55fd00f5631d2bd11c4ab91f53573a3
[ "MIT" ]
4
2017-11-21T11:25:49.000Z
2018-09-20T17:59:27.000Z
components/xtl/tests/stl/mkheap1.cpp
untgames/Funner
c91614cda55fd00f5631d2bd11c4ab91f53573a3
[ "MIT" ]
4
2016-11-29T15:18:40.000Z
2017-03-27T16:04:08.000Z
#include <stl/algorithm> #include <stl/functional> #include <stdio.h> using namespace stl; int main () { printf ("Results of mkheap1_test:\n"); int numbers [6] = {5,10,4,13,11,19}; make_heap (numbers,numbers+6,greater<int> ()); for (int i=6;i>=1;i--) { printf ("%d\n",numbers [0]); pop_heap (numbers,numbers+i,greater<int> ()); } return 0; }
16.434783
49
0.597884
untgames
8a321b59d767b2421bed5ffe12cd0fcf4dcae987
7,448
hpp
C++
Tests/TaskTypeTests.hpp
iarebwan/TaskScheduler
f21a7c1823f9dfe1e495596666d072ca08b234b7
[ "MIT" ]
null
null
null
Tests/TaskTypeTests.hpp
iarebwan/TaskScheduler
f21a7c1823f9dfe1e495596666d072ca08b234b7
[ "MIT" ]
null
null
null
Tests/TaskTypeTests.hpp
iarebwan/TaskScheduler
f21a7c1823f9dfe1e495596666d072ca08b234b7
[ "MIT" ]
1
2022-01-27T05:15:36.000Z
2022-01-27T05:15:36.000Z
#ifndef __TASK_TYPE_TESTS_HPP__ #define __TASK_TYPE_TESTS_HPP__ #include "../OrderTasks.hpp" #include "../OrderByTaskType.hpp" #include <vector> #include <iostream> #include "gtest/gtest.h" using namespace std; void printTasks(vector<Task*>& ListOfTasks, OrderTasks* orderType, string classification = "") { orderType->display(ListOfTasks, classification); } void test_printByClassification(vector<Task*>& ListOfTasks, string classification) { OrderTasks* orderTaskType = new OrderByTaskType(); printTasks(ListOfTasks, orderTaskType, classification); } TEST(OrderByTaskTypeTest, OneTask){ vector<Task*> ListOfTasks; Task* task1 = new Task(); task1->setTaskTitle("Task 1"); task1->setTaskType("work"); ListOfTasks.push_back(task1); EXPECT_EQ(test_printByClassification(ListOfTasks, "work"), "1. Title: Task 1, TaskType(classification): work\n"); } TEST(OrderByTaskTypeTest, WorkTest){ vector<Task*> ListOfTasks; Task* task1 = new Task(); task1->setTaskTitle("Task 1"); task1->setTaskType("academic"); ListOfTasks.push_back(task1); Task* task2 = new Task(); task2->setTaskTitle("Task 2"); task2->setTaskType("personal"); ListOfTasks.push_back(task2); Task* task3 = new Task(); task3->setTaskTitle("Task 3"); task3->setTaskType("work"); ListOfTasks.push_back(task3); EXPECT_EQ(test_printByClassification(ListOfTasks, "work"), "1. Title: Task 3, TaskType(classification): work\n2. Title: Task 1, TaskType(classification): academic\n3. Title: Task 2, TaskType(classification): personal\n"); } TEST(OrderByTaskTypeTest, PersonalTest){ vector<Task*> ListOfTasks; Task* task1 = new Task(); task1->setTaskTitle("Task 1"); task1->setTaskType("academic"); ListOfTasks.push_back(task1); Task* task2 = new Task(); task2->setTaskTitle("Task 2"); task2->setTaskType("personal"); ListOfTasks.push_back(task2); Task* task3 = new Task(); task3->setTaskTitle("Task 3"); task3->setTaskType("work"); ListOfTasks.push_back(task3); EXPECT_EQ(test_printByClassification(ListOfTasks, "personal"), "1. Title: Task 2, TaskType(classification): personal\n2. Title: Task 1, TaskType(classification): academic\n3. Title: Task 3, TaskType(classification): work\n"); } TEST(OrderByTaskTypeTest, academicTest){ vector<Task*> ListOfTasks; Task* task1 = new Task(); task1->setTaskTitle("Task 1"); task1->setTaskType("personal"); ListOfTasks.push_back(task1); Task* task2 = new Task(); task2->setTaskTitle("Task 2"); task2->setTaskType("academic"); ListOfTasks.push_back(task2); Task* task3 = new Task(); task3->setTaskTitle("Task 3"); task3->setTaskType("work"); ListOfTasks.push_back(task3); EXPECT_EQ(test_printByClassification(ListOfTasks, "personal"), "1. Title: Task 2, TaskType(classification): academic\n2. Title: Task 1, TaskType(classification): personal\n3. Title: Task 3, TaskType(classification): work\n"); } TEST(OrderByTaskTypeTest, OneTaskTypeEntry){ vector<Task*> ListOfTasks; Task* task1 = new Task(); task1->setTaskTitle("Task 1"); ListOfTasks.push_back(task1); Task* task2 = new Task(); task2->setTaskTitle("Task 2"); task2->setTaskType("work"); ListOfTasks.push_back(task2); EXPECT_EQ(test_printByClassification(ListOfTasks, "work"), "1. Title: Task 2, TaskType(classification): work\n2. Title: Task 1\n"); } TEST(OrderByTaskTypeTest, NoTaskTypeEntry){ vector<Task*> ListOfTasks; Task* task1 = new Task(); task1->setTaskTitle("Task 1"); ListOfTasks.push_back(task1); Task* task2 = new Task(); task2->setTaskTitle("Task 2"); ListOfTasks.push_back(task2); EXPECT_EQ(test_printByClassification(ListOfTasks, ""), "1. Title: Task 1\n2. Title: Task 2\n"); } TEST(OrderByTaskTypeTest, NoTaskTypeEntry2){ vector<Task*> ListOfTasks; Task* task1 = new Task(); task1->setTaskTitle("Task 1"); ListOfTasks.push_back(task1); Task* task2 = new Task(); task2->setTaskTitle("Task 2"); task2->setTaskType("work"); ListOfTasks.push_back(task2); EXPECT_EQ(test_printByClassification(ListOfTasks, ""), "1. Title: Task 1\n2. Title: Task 2, TaskType(classification): work\n"); } TEST(OrderByTaskTypeTest, SameTaskTypeEntry){ vector<Task*> ListOfTasks; Task* task1 = new Task(); task1->setTaskTitle("Task 1"); task1->setTaskType("personal"); ListOfTasks.push_back(task1); Task* task2 = new Task(); task2->setTaskTitle("Task 2"); task2->setTaskType("personal"); ListOfTasks.push_back(task2); EXPECT_EQ(test_printByClassification(ListOfTasks, "personal"), "1. Title: Task 1, TaskType(classification): personal\n2. Title: Task 2, TaskType(classification): personal\n"; } TEST(OrderByTaskTypeTest, SameTaskTypeEntry2){ vector<Task*> ListOfTasks; Task* task1 = new Task(); task1->setTaskTitle("Task 1"); task1->setTaskType("work"); ListOfTasks.push_back(task1); Task* task2 = new Task(); task2->setTaskTitle("Task 2"); task2->setTaskType("work"); ListOfTasks.push_back(task2); Task* task3 = new Task(); task3->setTaskTitle("Task 3"); task3->setTaskType("work"); ListOfTasks.push_back(task3); EXPECT_EQ(test_printByClassification(ListOfTasks, "work"), "1. Title: Task 1, TaskType(classification): work\n2. Title: Task 2, TaskType(classification): work\n3. Title: Task 3, TaskType(classification): work\n"); } TEST(OrderByTaskTypeTest, LotsOfPriorities){ vector<Task*> ListOfTasks; Task* task1 = new Task(); task1->setTaskTitle("Task 1"); task1->setTaskType("work"); ListOfTasks.push_back(task1); Task* task2 = new Task(); task2->setTaskTitle("Task 2"); task2->setTaskType("personal"); ListOfTasks.push_back(task2); Task* task3 = new Task(); task3->setTaskTitle("Task 3"); task3->setTaskType("academic"); ListOfTasks.push_back(task3); Task* task4 = new Task(); task4->setTaskTitle("Task 4"); task4->setTaskType("work"); ListOfTasks.push_back(task4); Task* task5 = new Task(); task5->setTaskTitle("Task 5"); task5->setTaskType("personal"); ListOfTasks.push_back(task5); Task* task6 = new Task(); task6->setTaskTitle("Task 6"); task6->setTaskType("academic"); ListOfTasks.push_back(task6); Task* task7 = new Task(); task7->setTaskTitle("Task 7"); task7->setTaskType("work"); ListOfTasks.push_back(task7); Task* task8 = new Task(); task8->setTaskTitle("Task 8"); task8->setTaskType("personal"); ListOfTasks.push_back(task8); Task* task9 = new Task(); task9->setTaskTitle("Task 9"); task9->setTaskType("academic"); ListOfTasks.push_back(task9); EXPECT_EQ(test_printByClassification(ListOfTasks, "work"), "1. Title: Task 1, TaskType(classification): work\n2. Title: Task 4, TaskType(classification): work\n3. Title: Task 7, TaskType(classification): work\n4. Title: Task 2, TaskType(classification): personal\n5. Title: Task 3, TaskType(classification): academic\n6. Title: Task 5, TaskType(classification): personal\n7. Title: Task 6, TaskType(classification): academic\n8. Title: Task 8, TaskType(classification): personal\n9. Title: Task 9, TaskType(classification): academic\n"); } //int main(int argc, char **argv) { // ::testing::InitGoogleTest(&argc, argv); // return RUN_ALL_TESTS(); //} #endif
32.242424
541
0.692132
iarebwan
8a3582f6d37055f6fdaf63fdced671951853af76
160
hpp
C++
src/libmlog/global.hpp
publiqnet/mesh.pp
a85e393c0de82b5b477b48bf23f0b89f6ac82c26
[ "MIT" ]
1
2020-02-22T16:50:11.000Z
2020-02-22T16:50:11.000Z
src/libmlog/global.hpp
publiqnet/mesh.pp
a85e393c0de82b5b477b48bf23f0b89f6ac82c26
[ "MIT" ]
null
null
null
src/libmlog/global.hpp
publiqnet/mesh.pp
a85e393c0de82b5b477b48bf23f0b89f6ac82c26
[ "MIT" ]
null
null
null
#pragma once #include <mesh.pp/global.hpp> #if defined(LOG_LIBRARY) #define MLOGSHARED_EXPORT MESH_EXPORT #else #define MLOGSHARED_EXPORT MESH_IMPORT #endif
14.545455
37
0.80625
publiqnet
8a379ca1f3921fff31bb6451da7930866a1669a9
1,380
cpp
C++
openGL/ROOT/src/Primitives/Cube.cpp
alissonads/openGL-c-
11cd2c6de5957694aeb866120b9898fee90a55b5
[ "MIT" ]
null
null
null
openGL/ROOT/src/Primitives/Cube.cpp
alissonads/openGL-c-
11cd2c6de5957694aeb866120b9898fee90a55b5
[ "MIT" ]
null
null
null
openGL/ROOT/src/Primitives/Cube.cpp
alissonads/openGL-c-
11cd2c6de5957694aeb866120b9898fee90a55b5
[ "MIT" ]
null
null
null
#include "Cube.h" #include "..\CG\MeshFactory.h" #include "..\Phong\RT_BasicMaterial.h" #include "..\Phong\RT_PhongMaterial.h" #include "..\Mage\RT_Mesh.h" #include "..\Mage\RT_Shader.h" #include "..\System\RT_Camera.h" #include "..\Phong\RT_DirectionalLight.h" #include "..\System\RT_Keyboard.h" #include <RTmath.h> Cube::Cube(RT::Vec3f *position, float _width, float _height, float _depth) : Form(position), width(_width), height(_height), depth(_depth) {} void Cube::Init() { mesh = MeshFactory::createCube(width, height, depth); } void Cube::Update(float secs) { /*if (RT_Keyboard::GetInstance()->IsDown(GLFW_KEY_W)) { position->z += 1.0f * secs; } if (RT_Keyboard::GetInstance()->IsDown(GLFW_KEY_S)) { position->z -= 1.0f * secs; } if (RT_Keyboard::GetInstance()->IsDown(GLFW_KEY_A)) { position->x -= 1.0f * secs; } if (RT_Keyboard::GetInstance()->IsDown(GLFW_KEY_D)) { position->x += 1.0f * secs; }*/ } void Cube::Draw(const RT_Camera *camera, const RT_Light *light) { RT_Shader *shader = material->GetShader(); shader->Bind() .SetUniform("uProjection", &camera->GetProjectionMatrix()) .SetUniform("uView", &camera->GetViewMatrix()) .SetUniform("uCameraPosition", camera->GetPosition()); light->Apply(*shader); shader->Unbind(); mesh->SetUniform("uWorld", &RT::Mat4f().Translate(*position)) .Draw(material); }
24.210526
63
0.671739
alissonads
8a37d15e458aa1e8e9e37c6141d85242a84e8b03
6,530
cpp
C++
Dynamic Programming/576. Out of Boundary Paths.cpp
beckswu/Leetcode
480e8dc276b1f65961166d66efa5497d7ff0bdfd
[ "MIT" ]
138
2020-02-08T05:25:26.000Z
2021-11-04T11:59:28.000Z
Dynamic Programming/576. Out of Boundary Paths.cpp
beckswu/Leetcode
480e8dc276b1f65961166d66efa5497d7ff0bdfd
[ "MIT" ]
null
null
null
Dynamic Programming/576. Out of Boundary Paths.cpp
beckswu/Leetcode
480e8dc276b1f65961166d66efa5497d7ff0bdfd
[ "MIT" ]
24
2021-01-02T07:18:43.000Z
2022-03-20T08:17:54.000Z
class Solution { public: int findPaths(int m, int n, int N, int i, int j) { static const long long M = 1000000007; vector<vector<long long>>table(m, vector<long long>(n,0)); table[i][j] = 1; long long res = 0; for(long long k = 0; k<N; k++){ vector<vector<long long>>newtable(m, vector<long long>(n,0)); for(long long a = 0; a<m; a++){ for(long long b = 0; b<n; b++){ if(table[a][b]) { if(a-1<0){ res = (res+table[a][b])%M; } else{ newtable[a-1][b] += table[a][b]%M; } if(a+1>=m){ res = (res+table[a][b])%M; } else{ newtable[a+1][b] += table[a][b]%M; } if(b-1<0){ res = (res+table[a][b])%M; } else{ newtable[a][b-1] += table[a][b]%M; } if(b+1>=n){ res = (res+table[a][b])%M; } else{ newtable[a][b+1] += table[a][b]%M; } table[a][b] = 0; } } } table = newtable; } return res%M; } }; /* dfs with memoization, dp[i][j][k] 表示到达i,j后还剩k步,可以最多out of boundary 数量 */ class Solution { public: long long dp[51][51][51]; int m, n; long long M; int findPaths(int m, int n, int N, int i, int j) { M = 1000000007; memset(dp, -1, sizeof(dp)); this->m = m; this->n = n; return dfs(i, j, N); } long long dfs(int i, int j, int k){ if(i < 0 || j < 0 || i >= m || j>=n){ return 1; } else if(k==0) return 0; if(dp[i][j][k]>=0) return dp[i][j][k]; dp[i][j][k] = ( dfs(i, j+1, k-1)%M+ dfs(i, j-1, k-1)%M + dfs(i+1, j, k-1)%M + dfs(i-1, j, k-1)%M)%M; return dp[i][j][k]; } }; //Bottom-up DP class Solution { public: int findPaths(int m, int n, int N, int i, int j) { vector<vector<long long>>dp(m, vector<long long>(n)); dp[i][j] = 1; int mod = pow(10,9)+7; vector<vector<int>>move = {{-1,0},{0,-1}, {1,0}, {0,1}}; long long res = 0 ; for(int z = 0; z<N; ++z){ vector<vector<long long>>tmp(m, vector<long long>(n)); for(int ii = 0 ; ii<m; ++ii){ for(int jj = 0; jj<n; ++jj){ if(dp[ii][jj]){ for(auto nxt: move){ int nxt_i = nxt[0] + ii; int nxt_j = nxt[1] + jj; if(nxt_i <0 || nxt_j < 0 || nxt_i >= m || nxt_j >= n) res = (res + dp[ii][jj]) % mod; else tmp[nxt_i][nxt_j] = (tmp[nxt_i][nxt_j] + dp[ii][jj])%mod; } } } } dp = tmp; } return res; } }; //DP class Solution { public: int findPaths(int m, int n, int N, int i, int j) { uint dp[51][50][50] = {}; for (auto Ni = 1; Ni <= N; ++Ni) for (auto mi = 0; mi < m; ++mi) for (auto ni = 0; ni < n; ++ni) dp[Ni][mi][ni] = ((mi == 0 ? 1 : dp[Ni - 1][mi - 1][ni]) + (mi == m - 1? 1 : dp[Ni - 1][mi + 1][ni]) + (ni == 0 ? 1 : dp[Ni - 1][mi][ni - 1]) + (ni == n - 1 ? 1 : dp[Ni - 1][mi][ni + 1])) % 1000000007; return dp[N][i][j]; } }; //reduce the memory usage by using two grids instead of N class Solution { public: int findPaths(int m, int n, int N, int i, int j) { unsigned int g[2][50][50] = {}; while (N-- > 0) for (auto k = 0; k < m; ++k) for (auto l = 0, nc = (N + 1) % 2, np = N % 2; l < n; ++l) g[nc][k][l] = ((k == 0 ? 1 : g[np][k - 1][l]) + (k == m - 1 ? 1 : g[np][k + 1][l]) + (l == 0 ? 1 : g[np][k][l - 1]) + (l == n - 1 ? 1 : g[np][k][l + 1])) % 1000000007; return g[1][i][j]; } }; //DFS class Solution { public: int findPaths(int m, int n, int N, int i, int j) { vector<vector<vector<long>>>dp(m, vector<vector<long>>(n, vector<long>(N+1,-1))); return dfs(dp, m, n, i, j, N); } int dfs(vector<vector<vector<long>>>&dp, int m, int n, int i, int j, int N ){ if(N<0) return 0; if(i < 0 || j<0 || i>=m || j>=n) return 1; if(dp[i][j][N] >= 0) return dp[i][j][N]; vector<vector<int>>move = {{-1,0},{0,-1}, {1,0}, {0,1}}; int mod = pow(10,9)+7; long long res = 0; for(auto nxt: move){ int nxt_i = nxt[0] + i; int nxt_j = nxt[1] + j; res = (res + dfs(dp, m, n, nxt_i, nxt_j, N-1))%mod; } return dp[i][j][N] = res; } }; //BFS class Solution { public: int findPaths(int m, int n, int N, int i, int j) { vector<vector<int>>move = {{-1,0},{0,-1}, {1,0}, {0,1}}; int mod = pow(10,9)+7; vector<vector<long>>dp(m, vector<long>(n)); queue<vector<int>>q; q.push({i,j}); long res = 0; int size = 1; dp[i][j] = 1; while((size = q.size()) && N--){ vector<vector<long>>tmp(m, vector<long>(n)); for(int z = 0; z< size; ++z){ vector<int>cur = q.front(); q.pop(); int ii = cur[0], jj = cur[1]; for(auto nxt: move){ int nxt_i = nxt[0] + ii; int nxt_j = nxt[1] + jj; if(nxt_i <0 || nxt_j < 0 || nxt_i >= m || nxt_j >= n) res = (res + dp[ii][jj]) % mod; else{ if(tmp[nxt_i][nxt_j] == 0) q.push({nxt_i, nxt_j}); tmp[nxt_i][nxt_j] = (tmp[nxt_i][nxt_j] + dp[ii][jj])%mod; } } } dp = tmp; } return res; } };
32.009804
116
0.35758
beckswu
8a39de8558142fa24514679eccdff414ab89311e
2,087
cpp
C++
src/engine/editor_extensions/src/vertex_gizmo.cpp
moonantonio/halley
c4dfc476ab58539ebb503a5fcdb929413674254d
[ "Apache-2.0" ]
3,262
2016-04-10T15:24:10.000Z
2022-03-31T17:47:08.000Z
src/engine/editor_extensions/src/vertex_gizmo.cpp
moonantonio/halley
c4dfc476ab58539ebb503a5fcdb929413674254d
[ "Apache-2.0" ]
53
2016-10-09T16:25:04.000Z
2022-01-10T13:52:37.000Z
src/engine/editor_extensions/src/vertex_gizmo.cpp
moonantonio/halley
c4dfc476ab58539ebb503a5fcdb929413674254d
[ "Apache-2.0" ]
193
2017-10-23T06:08:41.000Z
2022-03-22T12:59:58.000Z
#include "vertex_gizmo.h" #include "halley/core/game/scene_editor_interface.h" #include "halley/core/graphics/painter.h" #define DONT_INCLUDE_HALLEY_HPP #include "halley/entity/components/transform_2d_component.h" using namespace Halley; VertexGizmo::VertexGizmo(SnapRules snapRules, String componentName, String fieldName) : SceneEditorGizmo(snapRules) , componentName(std::move(componentName)) , fieldName(std::move(fieldName)) { handle.setBoundsCheck([=] (Vector2f myPos, Vector2f mousePos) -> bool { return getMainHandle().contains(mousePos); }); handle.setGridSnap(snapRules.grid); } void VertexGizmo::update(Time time, const ISceneEditor& sceneEditor, const SceneEditorInputState& inputState) { handle.update(inputState); const auto transform = getComponent<Transform2DComponent>(); if (transform) { if (handle.isHeld()) { // Write to object updateEntityData(transform->inverseTransformPoint(handle.getPosition())); } else { // Read from object handle.setPosition(transform->transformPoint(readEntityData()), false); } visible = true; } else { visible = false; } } void VertexGizmo::draw(Painter& painter) const { if (visible) { const float zoom = getZoom(); const auto overCol = Colour4f(0.5f, 0.5f, 1); const auto outCol = Colour4f(0.2f, 0.2f, 1.0f); const auto col = handle.isOver() ? overCol : outCol; const auto circle = getMainHandle(); const auto centre = circle.getCentre(); const auto radius = circle.getRadius(); const float lineWidth = 2.0f / zoom; painter.drawCircle(centre, radius, lineWidth, col); } } Circle VertexGizmo::getMainHandle() const { const auto pos = handle.getPosition(); return Circle(pos, 10.0f / getZoom()); } void VertexGizmo::updateEntityData(Vector2f pos) { auto* data = getComponentData(componentName); if (data) { (*data)[fieldName] = pos; } markModified(componentName, fieldName); } Vector2f VertexGizmo::readEntityData() const { auto* data = getComponentData(componentName); if (data) { return (*data)[fieldName].asVector2f(Vector2f()); } return Vector2f(); }
25.45122
109
0.729756
moonantonio
8a406738a4aaae078f2ac1eb3c0b61a583180d8c
742
hpp
C++
src/MainWindow.hpp
ricardobtez/gtkmm-application
6af746c11f6577cfd12d93fa692c2fad548de538
[ "MIT" ]
null
null
null
src/MainWindow.hpp
ricardobtez/gtkmm-application
6af746c11f6577cfd12d93fa692c2fad548de538
[ "MIT" ]
1
2020-10-22T20:37:33.000Z
2020-10-22T20:40:12.000Z
src/MainWindow.hpp
ricardobtez/gtkmm-application
6af746c11f6577cfd12d93fa692c2fad548de538
[ "MIT" ]
null
null
null
#ifndef MAIN_WINDOW_H #define MAIN_WINDOW_H #include <gtkmm/applicationwindow.h> #include <gtkmm/box.h> #include <gtkmm/builder.h> class MainWindow : public Gtk::ApplicationWindow { public: MainWindow(void); virtual ~MainWindow(); protected: // Signal handlers void on_menu_others(void); void on_menu_choices_other(const int parameter); void on_menu_toggle(); // Child widgets Gtk::Box m_box; Glib::RefPtr<Gtk::Builder> m_refBuilder; //Two sets of choices: Glib::RefPtr<Gio::SimpleAction> m_refChoice; Glib::RefPtr<Gio::SimpleAction> m_refChoiceOther; Glib::RefPtr<Gio::SimpleAction> m_refToggle; private: void on_menu_preferences_options(void); }; #endif /* MAIN_WINDOW_H */
20.054054
53
0.715633
ricardobtez
8a48cb5f4d5884417b36cd4e87219976f0ebffa4
30,711
cpp
C++
deps/libgeos/geos/util/geosop/GeomFunction.cpp
khrushjing/node-gdal-async
6546b0c8690f2db677d5385b40b407523503b314
[ "Apache-2.0" ]
42
2021-03-26T17:34:52.000Z
2022-03-18T14:15:31.000Z
deps/libgeos/geos/util/geosop/GeomFunction.cpp
khrushjing/node-gdal-async
6546b0c8690f2db677d5385b40b407523503b314
[ "Apache-2.0" ]
29
2021-06-03T14:24:01.000Z
2022-03-23T15:43:58.000Z
deps/libgeos/geos/util/geosop/GeomFunction.cpp
khrushjing/node-gdal-async
6546b0c8690f2db677d5385b40b407523503b314
[ "Apache-2.0" ]
8
2021-05-14T19:26:37.000Z
2022-03-21T13:44:42.000Z
/********************************************************************** * * GEOS - Geometry Engine Open Source * http://geos.osgeo.org * * Copyright (C) 2020 Martin Davis * * This is free software; you can redistribute and/or modify it under * the terms of the GNU Lesser General Public Licence as published * by the Free Software Foundation. * See the COPYING file for more information. * **********************************************************************/ #include <geos/geom/Geometry.h> #include <geos/geom/Point.h> #include <geos/geom/LineString.h> #include <geos/geom/LinearRing.h> #include <geos/geom/Polygon.h> #include <geos/geom/GeometryCollection.h> #include <geos/geom/IntersectionMatrix.h> #include <geos/geom/Envelope.h> #include <geos/geom/PrecisionModel.h> #include <geos/geom/GeometryFactory.h> #include <geos/geom/prep/PreparedGeometry.h> #include <geos/geom/prep/PreparedGeometryFactory.h> #include <geos/algorithm/construct/LargestEmptyCircle.h> #include <geos/algorithm/construct/MaximumInscribedCircle.h> #include <geos/algorithm/MinimumBoundingCircle.h> #include <geos/algorithm/distance/DiscreteHausdorffDistance.h> #include <geos/algorithm/distance/DiscreteFrechetDistance.h> #include <geos/geom/util/Densifier.h> #include <geos/operation/buffer/BufferBuilder.h> #include <geos/operation/buffer/BufferOp.h> #include <geos/operation/buffer/BufferParameters.h> #include <geos/operation/linemerge/LineMerger.h> #include <geos/operation/distance/DistanceOp.h> #include <geos/operation/intersection/RectangleIntersection.h> #include <geos/operation/intersection/Rectangle.h> #include <geos/operation/relate/RelateOp.h> #include <geos/operation/valid/MakeValid.h> #include <geos/operation/overlayng/OverlayNG.h> #include <geos/operation/polygonize/Polygonizer.h> #include <geos/precision/GeometryPrecisionReducer.h> #include <geos/simplify/DouglasPeuckerSimplifier.h> #include <geos/simplify/TopologyPreservingSimplifier.h> #include <geos/triangulate/DelaunayTriangulationBuilder.h> #include <geos/triangulate/VoronoiDiagramBuilder.h> #include <geos/triangulate/polygon/ConstrainedDelaunayTriangulator.h> #include "GeomFunction.h" #include <sstream> using geos::operation::overlayng::OverlayNG; using geos::algorithm::distance::DiscreteFrechetDistance; /* static private */ std::map<std::string, GeomFunction*> GeomFunction::registry; /* static private */ std::vector<GeomFunction*> GeomFunction::functionList; class PreparedGeometryCache { public: const PreparedGeometry* get(const Geometry* key) { if (m_key != key) { m_pg = PreparedGeometryFactory::prepare(key); m_key = key; } return m_pg.get(); } private: std::unique_ptr<const PreparedGeometry> m_pg; const Geometry* m_key; }; PreparedGeometryCache prepGeomCache; const std::string catMetric = "Metric"; const std::string catConst = "Construction"; const std::string catDist = "Distance"; const std::string catGeom = "Geometry"; const std::string catOverlay = "Overlay"; const std::string catRel = "Spatial Relationship"; const std::string catValid = "Validity"; /* static */ void GeomFunction::init() { add("copy", Result::typeGeometry, catGeom, [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { (void) geomB; (void)d; // prevent unused variable warning return new Result( geom->clone() ); }); add("envelope", Result::typeGeometry, catGeom, [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { (void) geomB; (void)d; // prevent unused variable warning return new Result( geom->getCentroid() ); }); add("isEmpty", 1, 0, Result::typeBool, catGeom, "test if geometry is empty", [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { (void) geomB; (void)d; // prevent unused variable warning return new Result( geom->isEmpty() ); }); add("normalize", 1, 0, Result::typeGeometry, catGeom, "normalize geometry", [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { (void) geomB; (void)d; // prevent unused variable warning auto res = geom->clone(); res->normalize(); return new Result( std::move(res) ); }); add("lineMerge", 1, 0, Result::typeGeometry, catGeom, "merge the lines of geometry", [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { (void) geomB; (void)d; // prevent unused variable warning geos::operation::linemerge::LineMerger lmrgr; lmrgr.add(geom.get()); std::vector<std::unique_ptr<LineString>> lines = lmrgr.getMergedLineStrings(); std::vector<std::unique_ptr<const Geometry>> geoms; for(unsigned int i = 0; i < lines.size(); i++) { geoms.push_back( std::move(lines[i]) ); } return new Result( std::move(geoms) ) ; }); add("reducePrecision", 1, 1, Result::typeGeometry, catGeom, "reduce precision of geometry to a precision scale factor", [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { (void)geomB; // prevent unused variable warning PrecisionModel pm(d); return new Result( geos::precision::GeometryPrecisionReducer::reduce( *geom, pm ) ); }); add("reverse", 1, 0, Result::typeGeometry, catGeom, "reverse geometry", [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { (void) geomB; (void)d; // prevent unused variable warning return new Result( geom->reverse() ); }); //------------------------------------- add("area", Result::typeDouble, catMetric, [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { (void) geomB; (void)d; // prevent unused variable warning return new Result( geom->getArea() ); }); add("length", Result::typeDouble, catMetric, [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { (void) geomB; (void)d; // prevent unused variable warning return new Result( geom->getLength() ); }); //------------------------------------- add("isSimple", 1, 0, Result::typeBool, catValid, "test if geometry is simple", [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { (void) geomB; (void)d; // prevent unused variable warning return new Result( geom->isSimple() ); }); add("isValid", 1, 0, Result::typeBool, catValid, "test if geometry is valid", [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { (void) geomB; (void)d; // prevent unused variable warning return new Result( geom->isValid() ); }); add("makeValid", Result::typeGeometry, catValid, [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { (void) geomB; (void)d; // prevent unused variable warning return new Result( geos::operation::valid::MakeValid().build( geom.get() ) ); }); //------------------------------------- add("boundary", Result::typeGeometry, catConst, [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { (void) geomB; (void)d; // prevent unused variable warning return new Result( geom->getBoundary() ); }); add("buffer", 1, 1, Result::typeGeometry, catConst, "compute the buffer of geometry by a distance", [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { (void) geomB; // prevent unused variable warning return new Result( geom->buffer( d ) ); }); add("offsetCurve", 1, 1, Result::typeGeometry, catConst, "compute the offset curve of geometry by a distance", [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { (void) geomB; // prevent unused variable warning geos::operation::buffer::BufferParameters bp; bool isLeftSide = true; if(d < 0) { isLeftSide = false; d = -d; } geos::operation::buffer::BufferBuilder bufBuilder(bp); return new Result( bufBuilder.bufferLineSingleSided(geom.get(), d, isLeftSide) ); }); add("centroid", Result::typeGeometry, catConst, [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { (void) geomB; (void)d; // prevent unused variable warning return new Result( geom->getCentroid() ); }); add("convexHull", Result::typeGeometry, catConst, [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { (void) geomB; (void)d; // prevent unused variable warning return new Result( geom->convexHull() ); }); add("densify", 1, 1, Result::typeGeometry, catConst, "densify geometry to a distance ", [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { (void)geomB; // prevent unused variable warning geos::geom::util::Densifier densifier( geom.get() ); densifier.setDistanceTolerance( d ); return new Result( densifier.getResultGeometry() ); }); add("interiorPoint", Result::typeGeometry, catConst, [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { (void) geomB; (void)d; // prevent unused variable warning return new Result( geom->getInteriorPoint() ); }); add("largestEmptyCircle", 1, 1, Result::typeGeometry, catConst, "compute radius line of largest empty circle of geometry up to a distance tolerance", [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { (void) geomB; (void)d; // prevent unused variable warning geos::algorithm::construct::LargestEmptyCircle lec( geom.get(), d ); std::unique_ptr<Geometry> res = lec.getRadiusLine(); return new Result( std::move(res) ); }); add("maxInscribedCircle", 1, 1, Result::typeGeometry, catConst, "compute maximum inscribed circle radius of Polygon up to a distance tolerance", [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { (void) geomB; (void)d; // prevent unused variable warning geos::algorithm::construct::MaximumInscribedCircle mc( geom.get(), d ); std::unique_ptr<Geometry> res = mc.getRadiusLine(); return new Result( std::move(res) ); }); add("minBoundingCircle", Result::typeGeometry, catConst, [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { (void) geomB; (void)d; // prevent unused variable warning geos::algorithm::MinimumBoundingCircle mc( geom.get() ); std::unique_ptr<Geometry> res = mc.getCircle(); return new Result( std::move(res) ); }); add("delaunay", 1, 0, Result::typeGeometry, catConst, "compute the Delaunay Triangulation of geometry vertices", [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { (void) geomB; (void)d; // prevent unused variable warning geos::triangulate::DelaunayTriangulationBuilder builder; builder.setTolerance(0); builder.setSites( *geom ); Geometry* out = builder.getTriangles(*(geom->getFactory())).release(); std::vector<std::unique_ptr<const Geometry>> geoms; for(unsigned int i = 0; i < out->getNumGeometries(); i++) { geoms.push_back( std::unique_ptr< const Geometry>( out->getGeometryN(i) ) ); } return new Result( std::move(geoms) ) ; }); add("constrainedDelaunay", 1, 0, Result::typeGeometry, catConst, "constrained Delauanay triangulation of polygonal geometries", [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { (void)geomB; (void)d; // prevent unused variable warning return new Result( geos::triangulate::polygon::ConstrainedDelaunayTriangulator::triangulate(geom.get()) ); }); add("voronoi", 1, 0, Result::typeGeometry, catConst, "Voronoi Diagram of geometry vertices", [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { (void) geomB; (void)d; // prevent unused variable warning geos::triangulate::VoronoiDiagramBuilder builder; builder.setTolerance(0); builder.setSites( *geom ); Geometry* out = builder.getDiagram(*(geom->getFactory())).release(); std::vector<std::unique_ptr<const Geometry>> geoms; for(unsigned int i = 0; i < out->getNumGeometries(); i++) { geoms.push_back( std::unique_ptr< const Geometry>( out->getGeometryN(i) ) ); } return new Result( std::move(geoms) ) ; }); add("polygonize", Result::typeGeometry, catConst, [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { (void) geomB; (void)d; // prevent unused variable warning geos::operation::polygonize::Polygonizer p; p.add(geom.get()); std::vector<std::unique_ptr<Polygon>> polys = p.getPolygons(); std::vector<std::unique_ptr<const Geometry>> geoms; for(unsigned int i = 0; i < polys.size(); i++) { geoms.push_back( std::move(polys[i]) ); } return new Result( std::move(geoms) ) ; }); add("simplifyDP", 1, 1, Result::typeGeometry, catConst, "simplify geometry using Douglas-Peucker with a distance tolerance", [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { (void)geomB; // prevent unused variable warning return new Result( geos::simplify::DouglasPeuckerSimplifier::simplify(geom.get(), d) ); }); add("simplifyTP", 1, 1, Result::typeGeometry, catConst, "simplify geometry using Douglas-Peucker with a distance tolerance, preserving topology", [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { (void)geomB; // prevent unused variable warning return new Result( geos::simplify::TopologyPreservingSimplifier::simplify(geom.get(), d) ); }); //-------------------------------- add("contains", 2, 0, Result::typeBool, catRel, "test if geometry A contains geometry B", [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { (void)d; // prevent unused variable warning return new Result( geom->contains( geomB.get() ) ); }); add("covers", 2, 0, Result::typeBool, catRel, "test if geometry A covers geometry B", [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { (void)d; // prevent unused variable warning return new Result( geom->covers( geomB.get() ) ); }); add("intersects", 2, 0, Result::typeBool, catRel, "test if geometry A and B intersect", [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { (void)d; // prevent unused variable warning return new Result( geom->intersects( geomB.get() ) ); }); add("relate", 2, 0, Result::typeString, catRel, "compute DE-9IM matrix for geometry A and B", [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { (void)d; // prevent unused variable warning std::unique_ptr<geom::IntersectionMatrix> im(geom->relate( geomB.get() )); return new Result( im->toString() ); }); add("containsPrep", 2, 0, Result::typeBool, catRel, "test if geometry A contains geometry B, using PreparedGeometry", [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { (void)d; // prevent unused variable warning return new Result( prepGeomCache.get(geom.get())->contains( geomB.get() ) ); }); add("containsProperlyPrep", 2, 0, Result::typeBool, catRel, "test if geometry A properly contains geometry B using PreparedGeometry", [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { (void)d; // prevent unused variable warning return new Result( prepGeomCache.get(geom.get())->containsProperly( geomB.get() ) ); }); add("coversPrep", 2, 0, Result::typeBool, catRel, "test if geometry A covers geometry B using PreparedGeometry", [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { (void)d; // prevent unused variable warning return new Result( prepGeomCache.get(geom.get())->covers( geomB.get() ) ); }); add("intersectsPrep", 2, 0, Result::typeBool, catRel, "test if geometry A intersects B using PreparedGeometry", [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { (void)d; // prevent unused variable warning return new Result( prepGeomCache.get(geom.get())->intersects( geomB.get() ) ); }); //---------------------------------------- add("distance", 2, 0, Result::typeDouble, catDist, "compute distance between geometry A and B", [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { (void)d; // prevent unused variable warning return new Result( geom->distance( geomB.get() ) ); }); add("nearestPoints", 2, 0, Result::typeGeometry, catDist, "compute a line containing the nearest points of geometry A and B", [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { (void)d; // prevent unused variable warning std::unique_ptr<CoordinateSequence> cs = geos::operation::distance::DistanceOp::nearestPoints(geom.get(), geomB.get()); auto factory = geom->getFactory(); auto res = factory->createLineString( std::move(cs) ); return new Result( std::move(res) ); }); add("frechetDistance", 2, 0, Result::typeDouble, catDist, "compute discrete Frechet distance between geometry A and B", [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { (void)d; // prevent unused variable warning return new Result( geos::algorithm::distance::DiscreteFrechetDistance::distance(*geom, *geomB ) ); }); /* // MD - can't get this to work for now add("frechetDistanceLine", 2, 0, Result::typeGeometry, catDist, "computes a line indicating the discrete Frechet distance between geometry A and B", [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { (void)d; // prevent unused variable warning DiscreteFrechetDistance dist(*geom, *geomB); //--- not supported for now //dist.setDensifyFraction(d); const std::array<geom::Coordinate, 2> ptArray = dist.getCoordinates(); std::unique_ptr<std::vector<Coordinate>> pts(new std::vector<Coordinate>(2)); (*pts)[0] = ptArray[0]; (*pts)[1] = ptArray[1]; //std::cout << ptArray[0] << std::endl; //std::cout << ptArray[1] << std::endl; auto cs = std::unique_ptr<CoordinateSequence>(new CoordinateArraySequence(pts.release())); auto factory = geom->getFactory(); auto res = factory->createLineString( std::move(cs) ); return new Result( std::move(res) ); }); */ add("distancePrep", 2, 0, Result::typeDouble, catDist, "compute distance between geometry A and B using PreparedGeometry", [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { (void)d; // prevent unused variable warning return new Result( prepGeomCache.get(geom.get())->distance( geomB.get() ) ); }); add("nearestPointsPrep", 2, 0, Result::typeGeometry, catDist, "compute a line containing the nearest points of geometry A and B using PreparedGeometry", [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { (void)d; // prevent unused variable warning auto cs = prepGeomCache.get(geom.get())->nearestPoints( geomB.get() ); auto factory = geom->getFactory(); auto res = factory->createLineString( std::move(cs) ); return new Result( std::move(res) ); }); //---------------------------------------- add("difference", 2, 0, Result::typeGeometry, catOverlay, "compute difference of geometry A from B", [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { (void)d; // prevent unused variable warning return new Result( geom->difference( geomB.get() ) ); }); add("intersection", 2, 0, Result::typeGeometry, catOverlay, "compute intersection of geometry A and B", [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { (void)d; // prevent unused variable warning return new Result( geom->intersection( geomB.get() ) ); }); add("symDifference", 2, 0, Result::typeGeometry, catOverlay, "compute symmetric difference of geometry A and B", [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { (void)d; // prevent unused variable warning return new Result( geom->symDifference( geomB.get() ) ); }); add("unaryUnion", Result::typeGeometry, catOverlay, [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { (void)geomB; (void)d; // prevent unused variable warning return new Result( geom->Union() ); }); add("union", 2, 0, Result::typeGeometry, catOverlay, "compute union of geometry A and B", [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { (void)d; // prevent unused variable warning return new Result( geom->Union( geomB.get() ) ); }); add("differenceSR", 2, 1, Result::typeGeometry, catOverlay, "compute difference of geometry A from B, snap-rounding to a precision scale factor", [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { geos::geom::PrecisionModel pm(d); return new Result( OverlayNG::overlay(geom.get(), geomB.get(), OverlayNG::DIFFERENCE, &pm) ); }); add("intersectionSR", 2, 1, Result::typeGeometry, catOverlay, "compute intersection of geometry A and B, snap-rounding to a precision scale factor", [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { geos::geom::PrecisionModel pm(d); return new Result( OverlayNG::overlay(geom.get(), geomB.get(), OverlayNG::INTERSECTION, &pm) ); }); add("symDifferenceSR", 2, 1, Result::typeGeometry, catOverlay, "compute symmetric difference of geometry A and B, snap-rounding to a precision scale factor", [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { geos::geom::PrecisionModel pm(d); return new Result( OverlayNG::overlay(geom.get(), geomB.get(), OverlayNG::SYMDIFFERENCE, &pm) ); }); add("unionSR", 2, 1, Result::typeGeometry, catOverlay, "compute union of geometry A and B, snap-rounding to a precision scale factor", [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { geos::geom::PrecisionModel pm(d); return new Result( OverlayNG::overlay(geom.get(), geomB.get(), OverlayNG::UNION, &pm) ); }); add("clipRect", 2, 0, Result::typeGeometry, catOverlay, "clip geometry A to envelope of B", [](const std::unique_ptr<Geometry>& geom, const std::unique_ptr<Geometry>& geomB, double d)->Result* { (void)d; // prevent unused variable warning using geos::operation::intersection::Rectangle; using geos::operation::intersection::RectangleIntersection; const Envelope* env = geomB->getEnvelopeInternal(); Rectangle rect(env->getMinX(), env->getMinY(), env->getMaxX(), env->getMaxY()); return new Result( RectangleIntersection::clip( *geom, rect) ); }); } /* static */ GeomFunction* GeomFunction::find(std::string name) { if (registry.count(name) == 0) return nullptr; return registry[name]; } /* static */ void GeomFunction::add(std::string name, int resultType, std::string category, geomFunSig geomfun) { add(name, 1, 0, resultType, category, "compute " + name + " of geometry", geomfun); } /* static */ void GeomFunction::add(std::string name, int nGeomParam, int nParam, int typeCode, std::string category, std::string desc, geomFunSig geomfun) { GeomFunction *fun = new GeomFunction(name, nGeomParam, nParam, typeCode, category, desc, geomfun ); registry.insert( std::pair<std::string, GeomFunction *>(name, fun) ); functionList.push_back(fun); } std::string GeomFunction::name() { return funName; } bool GeomFunction::isBinary() { return numGeomParam == 2; } std::string GeomFunction::signature() { std::string sig = " A"; sig += isBinary() ? " B" : " "; sig += " "; sig += funName; if (numParam > 0) sig += " N"; sig += " >"; sig += Result::code(resultType); return sig; } std::vector<std::string> GeomFunction::list() { std::vector<std::string> list; std::string cat = ""; for (auto itr = functionList.begin(); itr != functionList.end(); ++itr) { auto fun = *itr; if (fun->category != cat) { list.push_back( fun->category + " ------------------"); cat = fun->category; } auto desc = fun->signature() + " - " + fun->description; // TODO: add display of function signature list.push_back( desc ); } return list; } Result * GeomFunction::execute( const std::unique_ptr<Geometry>& geomA, const std::unique_ptr<Geometry>& geomB, double d ) { return geomfun( geomA, geomB, d ); } //=============================================== Result::Result(bool val) { valBool = val; typeCode = typeBool; } Result::Result(int val) { valInt = val; typeCode = typeInt; } Result::Result(double val) { valDouble = val; typeCode = typeDouble; } Result::Result(std::string val) { valStr = val; typeCode = typeString; } Result::Result(std::unique_ptr<geom::Geometry> val) { valGeom = std::move(val); typeCode = typeGeometry; } Result::Result(Geometry * val) { valGeom = std::unique_ptr<Geometry>(val); typeCode = typeGeometry; } Result::Result( std::vector<std::unique_ptr<const Geometry>> val ) { valGeomList = std::move(val); typeCode = typeGeomList; } Result::~Result() { } bool Result::isGeometry() { return typeCode == typeGeometry; } bool Result::isGeometryList() { return typeCode == typeGeomList; } std::string Result::toString() { std::stringstream converter; switch (typeCode) { case typeBool: converter << std::boolalpha << valBool; return converter.str(); case typeInt: converter << valInt; return converter.str(); case typeDouble: converter << valDouble; return converter.str(); case typeString: return valStr; case typeGeometry: if (valGeom == nullptr) return "null"; return valGeom->toString(); case typeGeomList: return metadata(); } return "Value for Unknonwn type"; } std::string Result::metadata() { switch (typeCode) { case typeBool: return "bool"; case typeInt: return "int"; case typeDouble: return "double"; case typeString: return "string"; case typeGeometry: if (valGeom == nullptr) return "null"; return valGeom->getGeometryType() + "( " + std::to_string( valGeom->getNumPoints() ) + " )"; case typeGeomList: return "Geometry[" + std::to_string( valGeomList.size()) + "]"; } return "Unknonwn type"; } std::string Result::code(int code) { switch (code) { case typeBool: return "B"; case typeInt: return "I"; case typeDouble: return "D"; case typeString: return "S"; case typeGeometry: return "G"; case typeGeomList: return "[G]"; } return "U"; }
43.377119
131
0.614405
khrushjing
8a4c26eff9fd2b1e02a0c0747fc4142fb7e28350
494
cc
C++
utils/weights_test.cc
agesmundo/FasterCubePruning
f80150140b5273fd1eb0dfb34bdd789c4cbd35e6
[ "BSD-3-Clause-LBNL", "Apache-2.0" ]
1
2019-06-03T00:44:01.000Z
2019-06-03T00:44:01.000Z
utils/weights_test.cc
jhclark/cdec
237ddc67ffa61da310e19710f902d4771dc323c2
[ "BSD-3-Clause-LBNL", "Apache-2.0" ]
null
null
null
utils/weights_test.cc
jhclark/cdec
237ddc67ffa61da310e19710f902d4771dc323c2
[ "BSD-3-Clause-LBNL", "Apache-2.0" ]
1
2021-02-19T12:44:54.000Z
2021-02-19T12:44:54.000Z
#include <cassert> #include <iostream> #include <fstream> #include <vector> #include <gtest/gtest.h> #include "weights.h" #include "tdict.h" using namespace std; class WeightsTest : public testing::Test { protected: virtual void SetUp() { } virtual void TearDown() { } }; TEST_F(WeightsTest,Load) { Weights w; w.InitFromFile("test_data/weights"); w.WriteToFile("-"); } int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
17.642857
42
0.680162
agesmundo
8a51daf50041c469bdb138b5fb747123ebb8bd27
23,611
cc
C++
chrome/services/sharing/nearby/nearby_connections.cc
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
chrome/services/sharing/nearby/nearby_connections.cc
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
86
2015-10-21T13:02:42.000Z
2022-03-14T07:50:50.000Z
chrome/services/sharing/nearby/nearby_connections.cc
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2020 The Chromium 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 "chrome/services/sharing/nearby/nearby_connections.h" #include <algorithm> #include "ash/services/nearby/public/mojom/nearby_connections_types.mojom.h" #include "ash/services/nearby/public/mojom/webrtc.mojom.h" #include "base/files/file_util.h" #include "base/metrics/histogram_functions.h" #include "base/synchronization/waitable_event.h" #include "base/task/post_task.h" #include "base/threading/thread_task_runner_handle.h" #include "base/time/time.h" #include "chrome/browser/nearby_sharing/logging/logging.h" #include "chrome/services/sharing/nearby/nearby_connections_conversions.h" #include "chrome/services/sharing/nearby/platform/input_file.h" #include "services/network/public/mojom/p2p.mojom.h" #include "third_party/nearby/src/cpp/core/core.h" namespace location { namespace nearby { namespace connections { namespace { ConnectionRequestInfo CreateConnectionRequestInfo( const std::vector<uint8_t>& endpoint_info, mojo::PendingRemote<mojom::ConnectionLifecycleListener> listener) { mojo::SharedRemote<mojom::ConnectionLifecycleListener> remote( std::move(listener)); return ConnectionRequestInfo{ .endpoint_info = ByteArrayFromMojom(endpoint_info), .listener = { .initiated_cb = [remote](const std::string& endpoint_id, const ConnectionResponseInfo& info) { if (!remote) return; remote->OnConnectionInitiated( endpoint_id, mojom::ConnectionInfo::New( info.authentication_token, ByteArrayToMojom(info.raw_authentication_token), ByteArrayToMojom(info.remote_endpoint_info), info.is_incoming_connection)); }, .accepted_cb = [remote](const std::string& endpoint_id) { if (!remote) return; remote->OnConnectionAccepted(endpoint_id); }, .rejected_cb = [remote](const std::string& endpoint_id, Status status) { if (!remote) return; remote->OnConnectionRejected(endpoint_id, StatusToMojom(status.value)); }, .disconnected_cb = [remote](const std::string& endpoint_id) { if (!remote) return; remote->OnDisconnected(endpoint_id); }, .bandwidth_changed_cb = [remote](const std::string& endpoint_id, Medium medium) { if (!remote) return; remote->OnBandwidthChanged(endpoint_id, MediumToMojom(medium)); }, }, }; } } // namespace // Should only be accessed by objects within lifetime of NearbyConnections. NearbyConnections* g_instance = nullptr; // static NearbyConnections& NearbyConnections::GetInstance() { DCHECK(g_instance); return *g_instance; } NearbyConnections::NearbyConnections( mojo::PendingReceiver<mojom::NearbyConnections> nearby_connections, mojom::NearbyConnectionsDependenciesPtr dependencies, scoped_refptr<base::SequencedTaskRunner> io_task_runner, base::OnceClosure on_disconnect) : nearby_connections_(this, std::move(nearby_connections)), on_disconnect_(std::move(on_disconnect)), thread_task_runner_(base::ThreadTaskRunnerHandle::Get()) { location::nearby::api::LogMessage::SetMinLogSeverity( dependencies->min_log_severity); nearby_connections_.set_disconnect_handler(base::BindOnce( &NearbyConnections::OnDisconnect, weak_ptr_factory_.GetWeakPtr(), MojoDependencyName::kNearbyConnections)); if (dependencies->bluetooth_adapter) { bluetooth_adapter_.Bind(std::move(dependencies->bluetooth_adapter), io_task_runner); bluetooth_adapter_.set_disconnect_handler( base::BindOnce(&NearbyConnections::OnDisconnect, weak_ptr_factory_.GetWeakPtr(), MojoDependencyName::kBluetoothAdapter), base::SequencedTaskRunnerHandle::Get()); } socket_manager_.Bind( std::move(dependencies->webrtc_dependencies->socket_manager), io_task_runner); socket_manager_.set_disconnect_handler( base::BindOnce(&NearbyConnections::OnDisconnect, weak_ptr_factory_.GetWeakPtr(), MojoDependencyName::kSocketManager), base::SequencedTaskRunnerHandle::Get()); mdns_responder_factory_.Bind( std::move(dependencies->webrtc_dependencies->mdns_responder_factory), io_task_runner); mdns_responder_factory_.set_disconnect_handler( base::BindOnce(&NearbyConnections::OnDisconnect, weak_ptr_factory_.GetWeakPtr(), MojoDependencyName::kMdnsResponder), base::SequencedTaskRunnerHandle::Get()); ice_config_fetcher_.Bind( std::move(dependencies->webrtc_dependencies->ice_config_fetcher), io_task_runner); ice_config_fetcher_.set_disconnect_handler( base::BindOnce(&NearbyConnections::OnDisconnect, weak_ptr_factory_.GetWeakPtr(), MojoDependencyName::kIceConfigFetcher), base::SequencedTaskRunnerHandle::Get()); webrtc_signaling_messenger_.Bind( std::move(dependencies->webrtc_dependencies->messenger), io_task_runner); webrtc_signaling_messenger_.set_disconnect_handler( base::BindOnce(&NearbyConnections::OnDisconnect, weak_ptr_factory_.GetWeakPtr(), MojoDependencyName::kWebRtcSignalingMessenger), base::SequencedTaskRunnerHandle::Get()); // There should only be one instance of NearbyConnections in a process. DCHECK(!g_instance); g_instance = this; } NearbyConnections::~NearbyConnections() { // Note that deleting active Core objects invokes their shutdown flows. This // is required to ensure that Nearby cleans itself up. We must bring down the // Cores before destroying their shared ServiceControllerRouter. VLOG(1) << "Nearby Connections: cleaning up Core objects"; service_id_to_core_map_.clear(); VLOG(1) << "Nearby Connections: shutting down the shared service controller " << "router after taking down Core objects"; service_controller_router_.reset(); g_instance = nullptr; VLOG(1) << "Nearby Connections: shutdown complete"; } std::string NearbyConnections::GetMojoDependencyName( MojoDependencyName dependency_name) { switch (dependency_name) { case MojoDependencyName::kNearbyConnections: return "Nearby Connections"; case MojoDependencyName::kBluetoothAdapter: return "Bluetooth Adapter"; case MojoDependencyName::kSocketManager: return "Socket Manager"; case MojoDependencyName::kMdnsResponder: return "MDNS Responder"; case MojoDependencyName::kIceConfigFetcher: return "ICE Config Fetcher"; case MojoDependencyName::kWebRtcSignalingMessenger: return "WebRTC Signaling Messenger"; } } void NearbyConnections::OnDisconnect(MojoDependencyName dependency_name) { if (!on_disconnect_) { return; } LOG(WARNING) << "The utility process has detected that the browser process " "has disconnected from a mojo pipe: [" << GetMojoDependencyName(dependency_name) << "]"; base::UmaHistogramEnumeration( "Nearby.Connections.UtilityProcessShutdownReason." "DisconnectedMojoDependency", dependency_name); std::move(on_disconnect_).Run(); // Note: |this| might be destroyed here. } void NearbyConnections::StartAdvertising( const std::string& service_id, const std::vector<uint8_t>& endpoint_info, mojom::AdvertisingOptionsPtr options, mojo::PendingRemote<mojom::ConnectionLifecycleListener> listener, StartAdvertisingCallback callback) { ConnectionOptions connection_options{ .strategy = StrategyFromMojom(options->strategy), .allowed = MediumSelectorFromMojom(options->allowed_mediums.get()), .auto_upgrade_bandwidth = options->auto_upgrade_bandwidth, .enforce_topology_constraints = options->enforce_topology_constraints, .enable_bluetooth_listening = options->enable_bluetooth_listening, .enable_webrtc_listening = options->enable_webrtc_listening, .fast_advertisement_service_uuid = options->fast_advertisement_service_uuid.canonical_value()}; GetCore(service_id) ->StartAdvertising( service_id, std::move(connection_options), CreateConnectionRequestInfo(endpoint_info, std::move(listener)), ResultCallbackFromMojom(std::move(callback))); } void NearbyConnections::StopAdvertising(const std::string& service_id, StopAdvertisingCallback callback) { GetCore(service_id) ->StopAdvertising(ResultCallbackFromMojom(std::move(callback))); } void NearbyConnections::StartDiscovery( const std::string& service_id, mojom::DiscoveryOptionsPtr options, mojo::PendingRemote<mojom::EndpointDiscoveryListener> listener, StartDiscoveryCallback callback) { // Left as empty string if no value has been passed in |options|. std::string fast_advertisement_service_uuid; if (options->fast_advertisement_service_uuid) { fast_advertisement_service_uuid = options->fast_advertisement_service_uuid->canonical_value(); } ConnectionOptions connection_options{ .strategy = StrategyFromMojom(options->strategy), .allowed = MediumSelectorFromMojom(options->allowed_mediums.get()), .is_out_of_band_connection = options->is_out_of_band_connection, .fast_advertisement_service_uuid = fast_advertisement_service_uuid}; mojo::SharedRemote<mojom::EndpointDiscoveryListener> remote( std::move(listener), thread_task_runner_); DiscoveryListener discovery_listener{ .endpoint_found_cb = [task_runner = thread_task_runner_, remote]( const std::string& endpoint_id, const ByteArray& endpoint_info, const std::string& service_id) { if (!remote) { return; } // This call must be posted to the same sequence that |remote| was // bound on. task_runner->PostTask( FROM_HERE, base::BindOnce( &mojom::EndpointDiscoveryListener::OnEndpointFound, base::Unretained(remote.get()), endpoint_id, mojom::DiscoveredEndpointInfo::New( ByteArrayToMojom(endpoint_info), service_id))); }, .endpoint_lost_cb = [task_runner = thread_task_runner_, remote](const std::string& endpoint_id) { if (!remote) { return; } // This call must be posted to the same sequence that |remote| was // bound on. task_runner->PostTask( FROM_HERE, base::BindOnce( &mojom::EndpointDiscoveryListener::OnEndpointLost, base::Unretained(remote.get()), endpoint_id)); }, }; ResultCallback result_callback = ResultCallbackFromMojom(std::move(callback)); GetCore(service_id) ->StartDiscovery(service_id, std::move(connection_options), std::move(discovery_listener), std::move(result_callback)); } void NearbyConnections::StopDiscovery(const std::string& service_id, StopDiscoveryCallback callback) { GetCore(service_id) ->StopDiscovery(ResultCallbackFromMojom(std::move(callback))); } void NearbyConnections::InjectBluetoothEndpoint( const std::string& service_id, const std::string& endpoint_id, const std::vector<uint8_t>& endpoint_info, const std::vector<uint8_t>& remote_bluetooth_mac_address, InjectBluetoothEndpointCallback callback) { OutOfBandConnectionMetadata oob_metadata{ .medium = Medium::BLUETOOTH, .endpoint_id = endpoint_id, .endpoint_info = ByteArrayFromMojom(endpoint_info), .remote_bluetooth_mac_address = ByteArrayFromMojom(remote_bluetooth_mac_address)}; GetCore(service_id) ->InjectEndpoint(service_id, oob_metadata, ResultCallbackFromMojom(std::move(callback))); } void NearbyConnections::RequestConnection( const std::string& service_id, const std::vector<uint8_t>& endpoint_info, const std::string& endpoint_id, mojom::ConnectionOptionsPtr options, mojo::PendingRemote<mojom::ConnectionLifecycleListener> listener, RequestConnectionCallback callback) { int keep_alive_interval_millis = options->keep_alive_interval ? options->keep_alive_interval->InMilliseconds() : 0; int keep_alive_timeout_millis = options->keep_alive_timeout ? options->keep_alive_timeout->InMilliseconds() : 0; ConnectionOptions connection_options{ .allowed = MediumSelectorFromMojom(options->allowed_mediums.get()), .keep_alive_interval_millis = std::max(keep_alive_interval_millis, 0), .keep_alive_timeout_millis = std::max(keep_alive_timeout_millis, 0), }; if (options->remote_bluetooth_mac_address) { connection_options.remote_bluetooth_mac_address = ByteArrayFromMojom(*options->remote_bluetooth_mac_address); } GetCore(service_id) ->RequestConnection( endpoint_id, CreateConnectionRequestInfo(endpoint_info, std::move(listener)), std::move(connection_options), ResultCallbackFromMojom(std::move(callback))); } void NearbyConnections::DisconnectFromEndpoint( const std::string& service_id, const std::string& endpoint_id, DisconnectFromEndpointCallback callback) { GetCore(service_id) ->DisconnectFromEndpoint(endpoint_id, ResultCallbackFromMojom(std::move(callback))); } void NearbyConnections::AcceptConnection( const std::string& service_id, const std::string& endpoint_id, mojo::PendingRemote<mojom::PayloadListener> listener, AcceptConnectionCallback callback) { mojo::SharedRemote<mojom::PayloadListener> remote(std::move(listener)); // Capturing Core* is safe as Core owns PayloadListener. PayloadListener payload_listener = { .payload_cb = [&, remote, core = GetCore(service_id)]( const std::string& endpoint_id, Payload payload) { if (!remote) return; switch (payload.GetType()) { case Payload::Type::kBytes: { mojom::BytesPayloadPtr bytes_payload = mojom::BytesPayload::New( ByteArrayToMojom(payload.AsBytes())); remote->OnPayloadReceived( endpoint_id, mojom::Payload::New(payload.GetId(), mojom::PayloadContent::NewBytes( std::move(bytes_payload)))); break; } case Payload::Type::kFile: { DCHECK(payload.AsFile()); // InputFile is created by Chrome, so it's safe to downcast. chrome::InputFile& input_file = static_cast<chrome::InputFile&>( payload.AsFile()->GetInputStream()); base::File file = input_file.ExtractUnderlyingFile(); if (!file.IsValid()) { core->CancelPayload(payload.GetId(), /*callback=*/{}); return; } mojom::FilePayloadPtr file_payload = mojom::FilePayload::New(std::move(file)); remote->OnPayloadReceived( endpoint_id, mojom::Payload::New(payload.GetId(), mojom::PayloadContent::NewFile( std::move(file_payload)))); break; } case Payload::Type::kStream: buffer_manager_.StartTrackingPayload(std::move(payload)); break; case Payload::Type::kUnknown: core->CancelPayload(payload.GetId(), /*callback=*/{}); return; } }, .payload_progress_cb = [&, remote](const std::string& endpoint_id, const PayloadProgressInfo& info) { if (!remote) return; // TODO(crbug.com/1237525): Investigate if OnPayloadTransferUpdate() // should not be called if |info.total_bytes| is negative. DCHECK_GE(info.bytes_transferred, 0); remote->OnPayloadTransferUpdate( endpoint_id, mojom::PayloadTransferUpdate::New( info.payload_id, PayloadStatusToMojom(info.status), info.total_bytes, info.bytes_transferred)); if (!buffer_manager_.IsTrackingPayload(info.payload_id)) return; switch (info.status) { case PayloadProgressInfo::Status::kFailure: FALLTHROUGH; case PayloadProgressInfo::Status::kCanceled: buffer_manager_.StopTrackingFailedPayload(info.payload_id); break; case PayloadProgressInfo::Status::kInProgress: // Note that |info.bytes_transferred| is a cumulative measure of // bytes that have been sent so far in the payload. buffer_manager_.HandleBytesTransferred(info.payload_id, info.bytes_transferred); break; case PayloadProgressInfo::Status::kSuccess: // When kSuccess is passed, we are guaranteed to have received a // previous kInProgress update with the same |bytes_transferred| // value. // Since we have completed fetching the full payload, return the // completed payload as a "bytes" payload. remote->OnPayloadReceived( endpoint_id, mojom::Payload::New( info.payload_id, mojom::PayloadContent::NewBytes( mojom::BytesPayload::New(ByteArrayToMojom( buffer_manager_ .GetCompletePayloadAndStopTracking( info.payload_id)))))); break; } }}; GetCore(service_id) ->AcceptConnection(endpoint_id, std::move(payload_listener), ResultCallbackFromMojom(std::move(callback))); } void NearbyConnections::RejectConnection(const std::string& service_id, const std::string& endpoint_id, RejectConnectionCallback callback) { GetCore(service_id) ->RejectConnection(endpoint_id, ResultCallbackFromMojom(std::move(callback))); } void NearbyConnections::SendPayload( const std::string& service_id, const std::vector<std::string>& endpoint_ids, mojom::PayloadPtr payload, SendPayloadCallback callback) { Payload core_payload; switch (payload->content->which()) { case mojom::PayloadContent::Tag::BYTES: core_payload = Payload(payload->id, ByteArrayFromMojom(payload->content->get_bytes()->bytes)); break; case mojom::PayloadContent::Tag::FILE: int64_t file_size = payload->content->get_file()->file.GetLength(); { base::AutoLock al(input_file_lock_); input_file_map_.insert_or_assign( payload->id, std::move(payload->content->get_file()->file)); } core_payload = Payload(payload->id, InputFile(payload->id, file_size)); break; } GetCore(service_id) ->SendPayload(absl::MakeSpan(endpoint_ids), std::move(core_payload), ResultCallbackFromMojom(std::move(callback))); } void NearbyConnections::CancelPayload(const std::string& service_id, int64_t payload_id, CancelPayloadCallback callback) { GetCore(service_id) ->CancelPayload(payload_id, ResultCallbackFromMojom(std::move(callback))); } void NearbyConnections::StopAllEndpoints(const std::string& service_id, StopAllEndpointsCallback callback) { GetCore(service_id) ->StopAllEndpoints(ResultCallbackFromMojom(std::move(callback))); } void NearbyConnections::InitiateBandwidthUpgrade( const std::string& service_id, const std::string& endpoint_id, InitiateBandwidthUpgradeCallback callback) { GetCore(service_id) ->InitiateBandwidthUpgrade(endpoint_id, ResultCallbackFromMojom(std::move(callback))); } void NearbyConnections::RegisterPayloadFile( const std::string& service_id, int64_t payload_id, base::File input_file, base::File output_file, RegisterPayloadFileCallback callback) { if (!input_file.IsValid() || !output_file.IsValid()) { std::move(callback).Run(mojom::Status::kError); return; } { base::AutoLock al(input_file_lock_); input_file_map_.insert_or_assign(payload_id, std::move(input_file)); } { base::AutoLock al(output_file_lock_); output_file_map_.insert_or_assign(payload_id, std::move(output_file)); } std::move(callback).Run(mojom::Status::kSuccess); } base::File NearbyConnections::ExtractInputFile(int64_t payload_id) { base::AutoLock al(input_file_lock_); auto file_it = input_file_map_.find(payload_id); if (file_it == input_file_map_.end()) return base::File(); base::File file = std::move(file_it->second); input_file_map_.erase(file_it); return file; } base::File NearbyConnections::ExtractOutputFile(int64_t payload_id) { base::AutoLock al(output_file_lock_); auto file_it = output_file_map_.find(payload_id); if (file_it == output_file_map_.end()) return base::File(); base::File file = std::move(file_it->second); output_file_map_.erase(file_it); return file; } scoped_refptr<base::SingleThreadTaskRunner> NearbyConnections::GetThreadTaskRunner() { return thread_task_runner_; } Core* NearbyConnections::GetCore(const std::string& service_id) { std::unique_ptr<Core>& core = service_id_to_core_map_[service_id]; if (!core) { // Note: Some tests will use SetServiceControllerRouterForTesting to set a // |service_controller_router| instance, but this value is expected to be // null for the first GetCore() call during normal operation. if (!service_controller_router_) { service_controller_router_ = std::make_unique<ServiceControllerRouter>(); } core = std::make_unique<Core>(service_controller_router_.get()); } return core.get(); } void NearbyConnections::SetServiceControllerRouterForTesting( std::unique_ptr<ServiceControllerRouter> service_controller_router) { service_controller_router_ = std::move(service_controller_router); } } // namespace connections } // namespace nearby } // namespace location
38.706557
80
0.649951
chromium
8a52281d0d28206e88109bb087e388cbf970c4f5
1,024
cpp
C++
TimeEntry.cpp
ChristianLightServices/ClockifyTrayIcons
568f9635ff1b304773e7fe8f143c1044c7b94ad4
[ "MIT" ]
1
2021-09-17T08:09:32.000Z
2021-09-17T08:09:32.000Z
TimeEntry.cpp
ChristianLightServices/ClockifyTrayIcons
568f9635ff1b304773e7fe8f143c1044c7b94ad4
[ "MIT" ]
null
null
null
TimeEntry.cpp
ChristianLightServices/ClockifyTrayIcons
568f9635ff1b304773e7fe8f143c1044c7b94ad4
[ "MIT" ]
null
null
null
#include "TimeEntry.h" #include "ClockifyManager.h" #include "JsonHelper.h" TimeEntry::TimeEntry(nlohmann::json entry, QObject *parent) : QObject{parent} { try { m_id = entry["id"].get<QString>(); auto projectId = entry["projectId"].get<QString>(); m_project = {projectId, ClockifyManager::instance()->projectName(projectId), entry["description"].get<QString>()}; m_userId = entry["userId"].get<QString>(); m_start = entry["timeInterval"]["start"].get<QDateTime>(); m_end = entry["timeInterval"]["end"].get<QDateTime>(); m_isValid = true; } catch (const std::exception &) { // TODO: do something here? } } TimeEntry::TimeEntry() : QObject{nullptr}, m_isValid{false} { } TimeEntry::TimeEntry(const TimeEntry &that) : QObject{that.parent()} { *this = that; } TimeEntry &TimeEntry::operator=(const TimeEntry &other) { m_id = other.m_id; m_project = other.m_project; m_userId = other.m_userId; m_start = other.m_start; m_end = other.m_end; m_isValid = other.m_isValid; return *this; }
20.897959
116
0.6875
ChristianLightServices
8a524ae537a83365004b3acc5b57c39dd2b3b14e
422
hpp
C++
plugin-sdk/include/piga/daemon/sdk/AppManager.hpp
Pigaco/daemon
df28306a7f8cdd2d263ab8f5663eefc1aabe876f
[ "Apache-2.0" ]
1
2016-11-17T07:13:18.000Z
2016-11-17T07:13:18.000Z
plugin-sdk/include/piga/daemon/sdk/AppManager.hpp
Pigaco/daemon
df28306a7f8cdd2d263ab8f5663eefc1aabe876f
[ "Apache-2.0" ]
null
null
null
plugin-sdk/include/piga/daemon/sdk/AppManager.hpp
Pigaco/daemon
df28306a7f8cdd2d263ab8f5663eefc1aabe876f
[ "Apache-2.0" ]
null
null
null
#pragma once #include <unordered_map> #include <memory> #include <string> #include <piga/daemon/sdk/App.hpp> namespace piga { namespace daemon { namespace sdk { class AppManager { public: typedef std::shared_ptr<App> AppPtr; typedef std::unordered_map<std::string, AppPtr> AppMap; virtual AppPtr operator[](const std::string &name) = 0; virtual AppPtr getApp(const std::string &name) = 0; }; } } }
15.62963
59
0.696682
Pigaco
8a529df2caf2691ea9692c833b11885976700c0d
659
cpp
C++
Clases Virtuales.cpp
monicastle/C_PDC_06
e5447d853ae2702341a33cec1448ac500a356540
[ "MIT" ]
null
null
null
Clases Virtuales.cpp
monicastle/C_PDC_06
e5447d853ae2702341a33cec1448ac500a356540
[ "MIT" ]
null
null
null
Clases Virtuales.cpp
monicastle/C_PDC_06
e5447d853ae2702341a33cec1448ac500a356540
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; class B{ public: void fun1(){ cout << "base-2\n"; } virtual void fun2() { cout << "base-2\n"; } virtual void fun3() { cout << "base-3\n"; } virtual void fun4() { cout << "base-4\n"; } }; class D: public B{ public: void fun1() { cout << "delivered-1\n"; } void fun2() { cout << "delivered-2\n"; } void fun4(int x) { cout << "delivered-4\n"; } }; int main(){ B* p; D obj1; p = &obj1; p->fun1(); p->fun2(); p->fun3(); p->fun4(); p->fun4(); obj1.fun4(5); }
16.475
33
0.427921
monicastle
8a52aa04476e74404cbfb57667d8748fed622fad
1,013
cpp
C++
toki/[Versi Lama] Training Gate TOKI Learning Center/Bab 4. Complete Search/4A. Complete Search I/E.cpp
andraantariksa/code-exercise-answer
69b7dbdc081cdb094cb110a72bc0c9242d3d344d
[ "MIT" ]
1
2019-11-06T15:17:48.000Z
2019-11-06T15:17:48.000Z
toki/[Versi Lama] Training Gate TOKI Learning Center/Bab 4. Complete Search/4A. Complete Search I/E.cpp
andraantariksa/code-exercise-answer
69b7dbdc081cdb094cb110a72bc0c9242d3d344d
[ "MIT" ]
null
null
null
toki/[Versi Lama] Training Gate TOKI Learning Center/Bab 4. Complete Search/4A. Complete Search I/E.cpp
andraantariksa/code-exercise-answer
69b7dbdc081cdb094cb110a72bc0c9242d3d344d
[ "MIT" ]
1
2018-11-13T08:43:26.000Z
2018-11-13T08:43:26.000Z
/*input 3 */ #include <iostream> #include <algorithm> #include <vector> int main(int argc, char const *argv[]){ int n; bool out_; long int num; std::string s = ""; std::vector<std::string> v; std::vector<long int> v2; std::cin>>n; for(int i = 1; i <= n; i++){ s += ('0' + i); } do{ v.push_back(s); }while(std::next_permutation(s.begin(), s.end())); for(std::string i: v){ out_ = true; for(int j = 1; j < i.length()-1; j++){ if(!((i[j] < i[j-1] && i[j] < i[j+1]) || (i[j] > i[j-1] && i[j] > i[j+1]))){ out_ = false; break; } } if(out_){ v2.push_back(stol(i)); } } std::sort(v2.begin(), v2.end()); for(long int i: v2){ std::cout<<i<<std::endl; } return 0; } /* for j in range(1, len(i)-1): #print(">{}".format(i[j])) if not ((i[j] < i[j-1] and i[j] < i[j+1]) or (i[j] > i[j-1] and i[j] > i[j+1])): out_ = False break if out_: num = "" for k in i: num = num + k out.append(int(num)) for i in out: print(i) */
18.759259
82
0.489635
andraantariksa
8a52d1852d32a9c4b1183480131a39d7098ff096
396
cpp
C++
examples/cpp/intro/textfileio.cpp
airgiser/ucb
d03e62a17f35a9183ed36662352f603f0f673194
[ "MIT" ]
1
2022-01-08T14:59:44.000Z
2022-01-08T14:59:44.000Z
examples/cpp/intro/textfileio.cpp
airgiser/just-for-fun
d03e62a17f35a9183ed36662352f603f0f673194
[ "MIT" ]
null
null
null
examples/cpp/intro/textfileio.cpp
airgiser/just-for-fun
d03e62a17f35a9183ed36662352f603f0f673194
[ "MIT" ]
null
null
null
/* * \brief Copy one file to anothre, a line at a time. * \author airfox */ #include <string> #include <fstream> #include <iostream> using namespace std; int main() { ifstream fin("Makefile"); ofstream fout("Makefile.2"); string str; string dest; while(getline(fin, str)) { dest += str + '\n'; fout<<str<<endl; } cout<<dest; return 0; }
14.666667
53
0.570707
airgiser
a435e230263dd38004415e0412b3f4866eea5dfa
2,129
cc
C++
src/lib/common/dump_utils.cc
ghsecuritylab/comanche
a8862eaed59045377874b95b120832a0cba42193
[ "Apache-2.0" ]
19
2017-10-03T16:01:49.000Z
2021-06-07T10:21:46.000Z
src/lib/common/dump_utils.cc
dnbaker/comanche
121cd0fa16e55d461b366e83511d3810ea2b11c9
[ "Apache-2.0" ]
25
2018-02-21T23:43:03.000Z
2020-09-02T08:47:32.000Z
src/lib/common/dump_utils.cc
dnbaker/comanche
121cd0fa16e55d461b366e83511d3810ea2b11c9
[ "Apache-2.0" ]
19
2017-10-24T17:41:40.000Z
2022-02-22T02:17:18.000Z
/* eXokernel Development Kit (XDK) Samsung Research America Copyright (C) 2013 The GNU C 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. The GNU C 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 the GNU C Library; if not, see <http://www.gnu.org/licenses/>. As a special exception, if you link the code in this file with files compiled with a GNU compiler to produce an executable, that does not cause the resulting executable to be covered by the GNU Lesser General Public License. This exception does not however invalidate any other reasons why the executable file might be covered by the GNU Lesser General Public License. This exception applies to code released by its copyright holders in files containing the exception. */ /* Authors: Copyright (C) 2014, Daniel G. Waddington <daniel.waddington@acm.org> */ #include "common/dump_utils.h" #include <assert.h> #include <stdint.h> #include <stdio.h> void hexdump(void *data, unsigned len) { printf("HEXDUMP----------------------------------------------"); assert(len > 0); uint8_t *d = (uint8_t *) data; for (unsigned i = 0; i < len; i++) { if (i % 16 == 0) { printf("\n0x%x:\t", i); } printf("%x%x ", 0xf & (d[i] >> 4), 0xf & d[i]); } printf("\n"); fflush(0); } void asciidump(void *data, unsigned len) { printf("ASCIIDUMP----------------------------------------------"); assert(len > 0); uint8_t *d = (uint8_t *) data; for (unsigned i = 0; i < len; i++) { if (i % 16 == 0) { printf("\n0x%x:\t", i); } printf("%c%c ", 0xf & (d[i] >> 4), 0xf & d[i]); } printf("\n"); }
32.753846
71
0.641616
ghsecuritylab
a43a82d7fb087d35421c8b56b8b3d1f3cff6ccbb
3,229
hpp
C++
Tests/kext/FromEvent/ParamsUnion.hpp
gkb/Karabiner
f47307d4fc89a4c421d10157d059293c508f721a
[ "Unlicense" ]
3,405
2015-01-01T04:57:52.000Z
2022-03-24T06:05:30.000Z
Tests/kext/FromEvent/ParamsUnion.hpp
Hasimir/Karabiner
6181ef9c9a6aeecd4162720884fbbaa2596ee03a
[ "Unlicense" ]
606
2015-01-04T03:21:16.000Z
2020-10-09T23:55:10.000Z
Tests/kext/FromEvent/ParamsUnion.hpp
Hasimir/Karabiner
6181ef9c9a6aeecd4162720884fbbaa2596ee03a
[ "Unlicense" ]
335
2015-01-06T16:43:16.000Z
2022-02-13T11:12:52.000Z
#ifndef PARAMSUNION_HPP #define PARAMSUNION_HPP #include "CallBackWrapper.hpp" namespace org_pqrs_KeyRemap4MacBook { class ParamsUnion { public: explicit ParamsUnion(const Params_KeyboardEventCallBack& p); explicit ParamsUnion(const Params_UpdateEventFlagsCallback& p); explicit ParamsUnion(const Params_KeyboardSpecialEventCallback& p); explicit ParamsUnion(const Params_RelativePointerEventCallback& p); explicit ParamsUnion(const Params_ScrollWheelEventCallback& p); explicit ParamsUnion(const Params_Wait& p); ~ParamsUnion(void); enum Type { KEYBOARD, UPDATE_FLAGS, KEYBOARD_SPECIAL, RELATIVE_POINTER, SCROLL_WHEEL, WAIT, }; const Type type; Params_KeyboardEventCallBack* get_Params_KeyboardEventCallBack(void) const { if (type != KEYBOARD) return NULL; return params_.params_KeyboardEventCallBack; } Params_UpdateEventFlagsCallback* get_Params_UpdateEventFlagsCallback(void) const { if (type != UPDATE_FLAGS) return NULL; return params_.params_UpdateEventFlagsCallback; } Params_KeyboardSpecialEventCallback* get_Params_KeyboardSpecialEventCallback(void) const { if (type != KEYBOARD_SPECIAL) return NULL; return params_.params_KeyboardSpecialEventCallback; } Params_RelativePointerEventCallback* get_Params_RelativePointerEventCallback(void) const { if (type != RELATIVE_POINTER) return NULL; return params_.params_RelativePointerEventCallback; } Params_ScrollWheelEventCallback* get_Params_ScrollWheelEventCallback(void) const { if (type != SCROLL_WHEEL) return NULL; return params_.params_ScrollWheelEventCallback; } Params_Wait* get_Params_Wait(void) const { if (type != WAIT) return NULL; return params_.params_Wait; } bool iskeydown(bool& output) const { output = false; switch (type) { case KEYBOARD: { Params_KeyboardEventCallBack* p = get_Params_KeyboardEventCallBack(); if (p) { output = p->ex_iskeydown; return true; } break; } case KEYBOARD_SPECIAL: { Params_KeyboardSpecialEventCallback* p = get_Params_KeyboardSpecialEventCallback(); if (p) { output = p->ex_iskeydown; return true; } break; } case RELATIVE_POINTER: { Params_RelativePointerEventCallback* p = get_Params_RelativePointerEventCallback(); if (p) { output = p->ex_isbuttondown; return true; } break; } case UPDATE_FLAGS: case SCROLL_WHEEL: case WAIT: break; } return false; } private: union { Params_KeyboardEventCallBack* params_KeyboardEventCallBack; Params_UpdateEventFlagsCallback* params_UpdateEventFlagsCallback; Params_KeyboardSpecialEventCallback* params_KeyboardSpecialEventCallback; Params_RelativePointerEventCallback* params_RelativePointerEventCallback; Params_ScrollWheelEventCallback* params_ScrollWheelEventCallback; Params_Wait* params_Wait; } params_; }; } #endif
30.752381
94
0.690307
gkb
a43c69b1e413f9bd56c76b3af84396d0c9fb1618
10,720
cpp
C++
common/src/utils/IntCodeMachine.cpp
bielskij/AOC-2019
e98d660412037b3fdac4a6b49adcb9230f518c99
[ "MIT" ]
null
null
null
common/src/utils/IntCodeMachine.cpp
bielskij/AOC-2019
e98d660412037b3fdac4a6b49adcb9230f518c99
[ "MIT" ]
null
null
null
common/src/utils/IntCodeMachine.cpp
bielskij/AOC-2019
e98d660412037b3fdac4a6b49adcb9230f518c99
[ "MIT" ]
null
null
null
#include <stdexcept> #include <utils/IntCodeMachine.h> #include <utils/utils.h> #define DEBUG_LEVEL 5 #include "common/debug.h" IntCodeMachine::IntCodeMachine(const std::vector<int64_t> &program) : memory(program), program(program) { this->pc = 0; this->eop = false; this->relativeBase = 0; this->memory.resize(64 * 1024); } IntCodeMachine::~IntCodeMachine() { } bool IntCodeMachine::onOut(int64_t value) { WRN(("%s(): Default implementation!", __func__)); return false; } bool IntCodeMachine::onIn(int64_t &value) { WRN(("%s(): Default implementation!", __func__)); return false; } void IntCodeMachine::onMemoryWrite(int64_t address, int64_t currentValue, int64_t newValue) { WRN(("%s(): Default implementation!", __func__)); } void IntCodeMachine::onMemoryRead(int64_t address, int64_t currentValue) { WRN(("%s(): Default implementation!", __func__)); } #define _I(x) ((int)x) #define _IP PRId64 std::string IntCodeMachine::_addrToAsm(const std::vector<int64_t> &program, int argMode, int64_t arg, bool readPositionParameters) { std::string ret; if (argMode == ADDRESS_IMMEDIATE) { ret = utils::toString(arg); } else { if (readPositionParameters) { ret = "mem[" + utils::toString(program[arg]); } else { ret = "mem[mem[" + utils::toString(arg); } if (argMode == ADDRESS_RELATIVE) { ret += " + _rel"; } if (! readPositionParameters) { ret += "]"; } ret += "]"; } return ret; } std::string IntCodeMachine::_opcodeToAsm(const std::vector<int64_t> &program, int pc, int code, int arg1Mode, int64_t arg1, int arg2Mode, int64_t arg2, int arg3Mode, int64_t arg3, int &codeSize, bool rpp) { std::string _asm = utils::toString(pc); switch (code) { case 1: case 2: { if (code == 1) { _asm += " add "; } else { _asm += " mul "; } _asm += _addrToAsm(program, arg3Mode, arg3, rpp) + " := " + _addrToAsm(program, arg1Mode, arg1, rpp) + ", " + _addrToAsm(program, arg2Mode, arg2, rpp); codeSize = 4; } break; case 3: { _asm += " in " + _addrToAsm(program, arg1Mode, arg1, rpp); codeSize = 2; } break; case 4: { _asm += " out " + _addrToAsm(program, arg1Mode, arg1, rpp); codeSize = 2; } break; case 5: { _asm += " jmp_gtz " + _addrToAsm(program, arg1Mode, arg1, rpp) + ", " + _addrToAsm(program, arg2Mode, arg2, rpp); codeSize = 3; } break; case 6: { _asm += " jmp_eqz " + _addrToAsm(program, arg1Mode, arg1, rpp) + ", " + _addrToAsm(program, arg2Mode, arg2, rpp); codeSize = 3; } break; case 7: { _asm += " cmp_lt " + _addrToAsm(program, arg3Mode, arg3, rpp) + " := " + _addrToAsm(program, arg1Mode, arg1, rpp) + ", " + _addrToAsm(program, arg2Mode, arg2, rpp); codeSize = 4; } break; case 8: { _asm += " cmp_eq " + _addrToAsm(program, arg3Mode, arg3, rpp) + " := " + _addrToAsm(program, arg1Mode, arg1, rpp) + ", " + _addrToAsm(program, arg2Mode, arg2, rpp); codeSize = 4; } break; case 9: { _asm += " rel " + _addrToAsm(program, arg1Mode, arg1, rpp); codeSize = 2; } break; case 99: { _asm += " halt"; codeSize = 1; } break; } return _asm; } void IntCodeMachine::_memWrite(int64_t address, int64_t value) { if (! this->watchedAddresses.empty()) { int64_t currentValue = this->memory[address]; if (this->watchedAddresses.find(address) != this->watchedAddresses.end()) { this->onMemoryWrite(address, currentValue, value); } } this->memory[address] = value; } int64_t IntCodeMachine::_memRead(int64_t address) { int64_t val = this->memory[address]; if (! this->watchedAddresses.empty()) { if (this->watchedAddresses.find(address) != this->watchedAddresses.end()) { this->onMemoryRead(address, val); } } return val; } bool IntCodeMachine::handleOpcode(int code, int64_t arg1, int64_t arg2, int64_t arg3) { switch (code) { case 1: case 2: { int64_t noun = _memRead(arg1); int64_t verb = _memRead(arg2); int64_t result; if (code == 1) { result = noun + verb; } else { result = noun * verb; } DBG(("[%" _IP "] %s m[%" _IP "] (%" _IP ") = m[%" _IP "] (%" _IP ") + m[%" _IP "] (%" _IP ")", this->pc, code == 1 ? "ADD" : "MUL", arg3, result, arg1, noun, arg2, verb)); _memWrite(arg3, result); this->pc += 4; } break; case 3: { int64_t inVal; if (! this->onIn(inVal)) { return false; } else { _memWrite(arg1, inVal); DBG(("[%" _IP "] IN m[%" _IP "] = %" _IP, this->pc, arg1, inVal)); pc += 2; } } break; case 4: { int64_t val = _memRead(arg1); if (! this->onOut(val)) { return false; } else { DBG(("[%" _IP "] OUT m[%" _IP "] = %" _IP, this->pc, arg1, val)); pc += 2; } } break; case 5: { int64_t arg1Val = _memRead(arg1); int64_t arg2Val = _memRead(arg2); DBG(("[%" _IP "] m[%" _IP "] (%" _IP ") JMP_GT 0 PC <- m[%" _IP "] (%" _IP ")", this->pc, arg1, arg1Val, arg2, arg2Val)); if (arg1Val > 0) { pc = arg2Val; } else { pc += 3; } } break; case 6: { int64_t arg1Val = _memRead(arg1); int64_t arg2Val = _memRead(arg2); DBG(("[%" _IP "] m[%" _IP "] (%" _IP ") JMP_EQ 0 PC <- m[%" _IP "] (%" _IP ")", this->pc, arg1, arg1Val, arg2, arg2Val)); if (arg1Val == 0) { pc = arg2Val; } else { pc += 3; } } break; case 7: { int64_t arg1Val = _memRead(arg1); int64_t arg2Val = _memRead(arg2); int64_t outVal = (arg1Val < arg2Val) ? 1 : 0; DBG(("[%" _IP "] m[%" _IP "] (%" _IP ") LT m[%" _IP "] (%" _IP ") m[%" _IP "] = %" _IP, this->pc, arg1, arg1Val, arg2, arg2Val, arg3, outVal )); _memWrite(arg3, outVal); pc += 4; } break; case 8: { int64_t arg1Val = _memRead(arg1); int64_t arg2Val = _memRead(arg2); int64_t outVal = (arg1Val == arg2Val) ? 1 : 0; DBG(("[%" _IP "] m[%" _IP "] (%" _IP ") EQ m[%" _IP "] (%" _IP ") m[%" _IP "] = %" _IP, this->pc, arg1, arg1Val, arg2, arg2Val, arg3, outVal )); _memWrite(arg3, outVal); pc += 4; } break; case 9: { this->relativeBase += _memRead(arg1); this->pc += 2; } break; default: ERR(("Not supported code: %d", code)); throw std::runtime_error("Not supported opcode!"); } return true; } bool IntCodeMachine::step() { if (this->finished()) { return false; } int64_t num = this->memory.at(this->pc); switch (num) { case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 8: case 9: if (! this->handleOpcode(num, memory[this->pc + 1], memory[this->pc + 2], memory[this->pc + 3])) { return false; } break; case 99: this->eop = true; break; default: { if (num > 100) { int64_t opcode = num % 100; int64_t arg1 = this->pc + 1; int64_t arg2 = this->pc + 2; int64_t arg3 = this->pc + 3; switch ((num / 100) % 10) { case 0: arg1 = memory[arg1]; break; case 1: break; case 2: arg1 = memory[arg1] + this->relativeBase; break; } switch ((num / 1000) % 10) { case 0: arg2 = memory[arg2]; break; case 1: break; case 2: arg2 = memory[arg2] + this->relativeBase; break; } switch ((num / 10000) % 10) { case 0: arg3 = memory[arg3]; break; case 1: break; case 2: arg3 = memory[arg3] + this->relativeBase; break; } if (! this->handleOpcode(opcode, arg1, arg2, arg3)) { return false; } } else { ERR(("Not supported code: %" PRId64 ", at: %" PRId64, num, this->pc)); throw std::runtime_error("Not supported opcode!"); } } break; } return true; } bool IntCodeMachine::run() { int64_t num; if (this->finished()) { return false; } do { if (! this->step()) { return false; } } while (! this->finished()); return true; } void IntCodeMachine::reset() { this->pc = 0; this->eop = false; this->relativeBase = 0; std::copy(this->program.begin(), this->program.end(), this->memory.begin()); } bool IntCodeMachine::finished() const { return this->eop; } std::vector<int64_t> &IntCodeMachine::getMemory() { return this->memory; } std::string IntCodeMachine::getAsm(bool readPositionAddresses) { std::string ret; for (int i = 0; i < this->program.size(); i++) { int64_t num = this->program.at(i); int codeSize; switch (num) { case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 8: case 9: case 99: ret += _opcodeToAsm(this->program, i, num, ADDRESS_POSITION, i + 1, ADDRESS_POSITION, i + 2, ADDRESS_POSITION, i + 3, codeSize, readPositionAddresses); break; default: { if (num > 100) { int64_t opcode = num % 100; int64_t arg1 = i + 1; int64_t arg2 = i + 2; int64_t arg3 = i + 3; ret += _opcodeToAsm(this->program, i, opcode, (num / 100) % 10, arg1, (num / 1000) % 10, arg2, (num / 10000) % 10, arg3, codeSize, readPositionAddresses); } else { codeSize = 0; } } break; } if (codeSize > 0) { ret += "\n"; i += (codeSize - 1); } } return ret; } void IntCodeMachine::setPc(int64_t pc) { this->pc = pc; } void IntCodeMachine::addMemoryWatch(int64_t address) { this->watchedAddresses.insert(address); } void IntCodeMachine::save(SaveSlot &slot) { slot.memory = this->memory; slot.pc = this->pc; slot.relativeBase = this->relativeBase; slot.eop = this->eop; } void IntCodeMachine::load(SaveSlot &slot) { this->memory = slot.memory; this->pc = slot.pc; this->relativeBase = slot.relativeBase; this->eop = slot.eop; } void IntCodeMachine::dumpMemory() { int i; int lineLength = 32; int bufferSize = this->memory.size(); int offset = 0; char asciiBuffer[lineLength + 1]; for (i = 0; i < bufferSize; i++) { if (i % lineLength == 0) { if (i != 0) { printf(" %s\n", asciiBuffer); } printf("%04x: ", i + offset); } printf(" %02x", (unsigned char) this->memory.at(i)); if (! isprint((char) this->memory.at(i))) { asciiBuffer[i % lineLength] = '.'; } else { asciiBuffer[i % lineLength] = this->memory.at(i); } asciiBuffer[(i % lineLength) + 1] = '\0'; } while ((i % 16) != 0) { printf(" "); i++; } printf(" %s\n", asciiBuffer); }
20.037383
206
0.553918
bielskij
a43ea8249efb0776cef097e97a339cc3d04f4ff3
2,973
cpp
C++
test/module/irohad/multi_sig_transactions/transport_test.cpp
truongnmt/iroha
e9b969df9a0eb6ce62eae3ab62c5c3f046a5e6e1
[ "Apache-2.0" ]
null
null
null
test/module/irohad/multi_sig_transactions/transport_test.cpp
truongnmt/iroha
e9b969df9a0eb6ce62eae3ab62c5c3f046a5e6e1
[ "Apache-2.0" ]
2
2020-07-07T19:31:15.000Z
2021-06-01T22:29:48.000Z
test/module/irohad/multi_sig_transactions/transport_test.cpp
truongnmt/iroha
e9b969df9a0eb6ce62eae3ab62c5c3f046a5e6e1
[ "Apache-2.0" ]
null
null
null
/** * Copyright Soramitsu Co., Ltd. 2017 All Rights Reserved. * http://soramitsu.co.jp * * 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 <gtest/gtest.h> #include "module/irohad/multi_sig_transactions/mst_mocks.hpp" #include "module/irohad/multi_sig_transactions/mst_test_helpers.hpp" #include "multi_sig_transactions/state/mst_state.hpp" #include "multi_sig_transactions/transport/mst_transport_grpc.hpp" using namespace iroha::network; using namespace iroha::model; using ::testing::_; using ::testing::Invoke; using ::testing::InvokeWithoutArgs; /** * @brief Sends data over MstTransportGrpc (MstState and Peer objects) and * receives them. When received deserializes them end ensures that deserialized * objects equal to objects before sending. * * @given Initialized transport * AND MstState for transfer * @when Send state via transport * @then Assume that received state same as sent */ TEST(TransportTest, SendAndReceive) { auto transport = std::make_shared<MstTransportGrpc>(); auto notifications = std::make_shared<iroha::MockMstTransportNotification>(); transport->subscribe(notifications); std::mutex mtx; std::condition_variable cv; ON_CALL(*notifications, onNewState(_, _)) .WillByDefault( InvokeWithoutArgs(&cv, &std::condition_variable::notify_one)); auto state = iroha::MstState::empty(); state += makeTx(1, iroha::time::now(), makeKey(), 3); state += makeTx(1, iroha::time::now(), makeKey(), 4); state += makeTx(1, iroha::time::now(), makeKey(), 5); state += makeTx(1, iroha::time::now(), makeKey(), 5); std::unique_ptr<grpc::Server> server; grpc::ServerBuilder builder; int port = 0; std::string addr = "localhost:"; builder.AddListeningPort( addr + "0", grpc::InsecureServerCredentials(), &port); builder.RegisterService(transport.get()); server = builder.BuildAndStart(); ASSERT_TRUE(server); ASSERT_NE(port, 0); std::shared_ptr<shared_model::interface::Peer> peer = makePeer(addr + std::to_string(port), "abcdabcdabcdabcdabcdabcdabcdabcd"); // we want to ensure that server side will call onNewState() // with same parameters as on the client side EXPECT_CALL(*notifications, onNewState(_, state)) .WillOnce(Invoke([&peer](auto &p, auto) { EXPECT_EQ(*p, *peer); })); transport->sendState(*peer, state); std::unique_lock<std::mutex> lock(mtx); cv.wait_for(lock, std::chrono::milliseconds(100)); server->Shutdown(); }
35.819277
80
0.723512
truongnmt
a443ffec551c537c2fb926db12254f23c465a34d
4,832
cpp
C++
socketio/client/src/rtsp/ffmpeg/mpegaudiodata.cpp
eagle3dstreaming/webrtc
fef9b3652f7744f722785fc1f4cc6b099f4c7aa7
[ "BSD-3-Clause" ]
null
null
null
socketio/client/src/rtsp/ffmpeg/mpegaudiodata.cpp
eagle3dstreaming/webrtc
fef9b3652f7744f722785fc1f4cc6b099f4c7aa7
[ "BSD-3-Clause" ]
null
null
null
socketio/client/src/rtsp/ffmpeg/mpegaudiodata.cpp
eagle3dstreaming/webrtc
fef9b3652f7744f722785fc1f4cc6b099f4c7aa7
[ "BSD-3-Clause" ]
null
null
null
/* * MPEG Audio common tables * copyright (c) 2002 Fabrice Bellard * * This file is part of FFmpeg. * * FFmpeg 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. * * FFmpeg 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * mpeg audio layer common tables. */ #include <cmath> #include "mpegaudiodata.h" const uint16_t avpriv_mpa_bitrate_tab[2][3][15] = { { {0, 32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448 }, {0, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384 }, {0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320 } }, { {0, 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256}, {0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160}, {0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160} } }; const uint16_t avpriv_mpa_freq_tab[3] = { 44100, 48000, 32000 }; /*******************************************************/ /* layer 2 tables */ const int ff_mpa_sblimit_table[5] = { 27 , 30 , 8, 12 , 30 }; const int ff_mpa_quant_steps[17] = { 3, 5, 7, 9, 15, 31, 63, 127, 255, 511, 1023, 2047, 4095, 8191, 16383, 32767, 65535 }; /* we use a negative value if grouped */ const int ff_mpa_quant_bits[17] = { -5, -7, 3, -10, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 }; /* encoding tables which give the quantization index. Note how it is possible to store them efficiently ! */ static const unsigned char alloc_table_1[] = { 4, 0, 2, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 4, 0, 2, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 4, 0, 2, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 4, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 16, 4, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 16, 4, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 16, 4, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 16, 4, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 16, 4, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 16, 4, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 16, 4, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 16, 3, 0, 1, 2, 3, 4, 5, 16, 3, 0, 1, 2, 3, 4, 5, 16, 3, 0, 1, 2, 3, 4, 5, 16, 3, 0, 1, 2, 3, 4, 5, 16, 3, 0, 1, 2, 3, 4, 5, 16, 3, 0, 1, 2, 3, 4, 5, 16, 3, 0, 1, 2, 3, 4, 5, 16, 3, 0, 1, 2, 3, 4, 5, 16, 3, 0, 1, 2, 3, 4, 5, 16, 3, 0, 1, 2, 3, 4, 5, 16, 3, 0, 1, 2, 3, 4, 5, 16, 3, 0, 1, 2, 3, 4, 5, 16, 2, 0, 1, 16, 2, 0, 1, 16, 2, 0, 1, 16, 2, 0, 1, 16, 2, 0, 1, 16, 2, 0, 1, 16, 2, 0, 1, 16, }; static const unsigned char alloc_table_3[] = { 4, 0, 1, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 4, 0, 1, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 3, 0, 1, 3, 4, 5, 6, 7, 3, 0, 1, 3, 4, 5, 6, 7, 3, 0, 1, 3, 4, 5, 6, 7, 3, 0, 1, 3, 4, 5, 6, 7, 3, 0, 1, 3, 4, 5, 6, 7, 3, 0, 1, 3, 4, 5, 6, 7, 3, 0, 1, 3, 4, 5, 6, 7, 3, 0, 1, 3, 4, 5, 6, 7, 3, 0, 1, 3, 4, 5, 6, 7, 3, 0, 1, 3, 4, 5, 6, 7, }; static const unsigned char alloc_table_4[] = { 4, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 4, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 4, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 4, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 3, 0, 1, 3, 4, 5, 6, 7, 3, 0, 1, 3, 4, 5, 6, 7, 3, 0, 1, 3, 4, 5, 6, 7, 3, 0, 1, 3, 4, 5, 6, 7, 3, 0, 1, 3, 4, 5, 6, 7, 3, 0, 1, 3, 4, 5, 6, 7, 3, 0, 1, 3, 4, 5, 6, 7, 2, 0, 1, 3, 2, 0, 1, 3, 2, 0, 1, 3, 2, 0, 1, 3, 2, 0, 1, 3, 2, 0, 1, 3, 2, 0, 1, 3, 2, 0, 1, 3, 2, 0, 1, 3, 2, 0, 1, 3, 2, 0, 1, 3, 2, 0, 1, 3, 2, 0, 1, 3, 2, 0, 1, 3, 2, 0, 1, 3, 2, 0, 1, 3, 2, 0, 1, 3, 2, 0, 1, 3, 2, 0, 1, 3, }; const unsigned char * const ff_mpa_alloc_tables[5] = { alloc_table_1, alloc_table_1, alloc_table_3, alloc_table_3, alloc_table_4, };
32.42953
80
0.457161
eagle3dstreaming
a448dbe327562ef0827330e5e6811a52a3a6e8eb
5,568
cpp
C++
src/event_base_tests.cpp
Lizb3th/rpt
edd5e3055ee2fbad03c92900aa8e9cec6c0d2ee4
[ "MIT" ]
null
null
null
src/event_base_tests.cpp
Lizb3th/rpt
edd5e3055ee2fbad03c92900aa8e9cec6c0d2ee4
[ "MIT" ]
null
null
null
src/event_base_tests.cpp
Lizb3th/rpt
edd5e3055ee2fbad03c92900aa8e9cec6c0d2ee4
[ "MIT" ]
null
null
null
// This is a part of the RPT (Realy Poor Tech) Framework. // Copyright (C) Elizabeth Williams // All rights reserved. #include "pch.h" #include "detail/event_base.hpp" #include <vector> #include <future> #include <optional> using namespace Microsoft::VisualStudio::CppUnitTestFramework; namespace rpt::event_detail_tests { using rpt::event_detail::event_base; using rpt::event_detail::listener_base; TEST_CLASS(event_base_tests) { public: TEST_METHOD(construct); TEST_METHOD(empty); TEST_METHOD(add_remove_listener); TEST_METHOD(repudiate_delay); TEST_METHOD(clear_delay); TEST_METHOD(clear_one); TEST_METHOD(clear_many); TEST_METHOD(clear_complex); }; void event_base_tests::construct() { auto test = event_base<>{}; } void event_base_tests::empty() { auto test = event_base<>{}; Assert::IsTrue(test.empty()); } void event_base_tests::add_remove_listener() { auto test = event_base<>{}; auto test_litener = listener_base<>{ { [](auto p) {} } }; Assert::IsTrue(test.empty()); test.subscribe(test_litener); Assert::IsFalse(test.empty()); test.repudiate(test_litener); Assert::IsTrue(test.empty()); } struct event_base_test_listener : listener_base<> { event_base_test_listener() : listener_base<>({ [](auto& p) {}, [](auto& p) { static_cast<event_base_test_listener&>(p).attached = false; return true; } }) {} bool attached{ true }; }; void event_base_tests::clear_one() { auto test = event_base<>{}; auto test_litener = event_base_test_listener(); test.subscribe(test_litener); Assert::IsFalse(test.empty()); Assert::IsTrue(test_litener.attached); test.clear(); //Assert::IsTrue(test.empty()); Assert::IsFalse(test_litener.attached); } void event_base_tests::clear_many() { auto test = event_base<>{}; auto test_liteners = std::vector<event_base_test_listener>(10, event_base_test_listener{} ); for(auto& test_litener : test_liteners) test.subscribe(test_litener); Assert::IsFalse(test.empty()); for (auto& test_litener : test_liteners) Assert::IsTrue(test_litener.attached); test.clear(); //Assert::IsTrue(test.empty()); for (auto& test_litener : test_liteners) Assert::IsFalse(test_litener.attached); } void event_base_tests::repudiate_delay() { auto test = event_base<>{}; auto test_litener = event_base_test_listener{}; test.subscribe(test_litener); auto view = test.view_lock(); Assert::AreEqual(1ull, view.size()); std::thread([view = std::move(view)]() { std::this_thread::sleep_for(std::chrono::milliseconds(2)); }).detach(); auto time = std::chrono::system_clock::now(); test.repudiate(test_litener); auto delay = std::chrono::system_clock::now() - time; Assert::IsTrue(delay > std::chrono::milliseconds(1)); } void event_base_tests::clear_delay() { auto test = event_base<>{}; auto test_litener = event_base_test_listener{}; test.subscribe(test_litener); auto view = test.view_lock(); Assert::AreEqual(1ull, view.size()); std::thread([view = std::move(view)]() { std::this_thread::sleep_for(std::chrono::milliseconds(2)); }).detach(); auto time = std::chrono::system_clock::now(); test.repudiate(test_litener); auto delay = std::chrono::system_clock::now() - time; Assert::IsTrue(delay > std::chrono::milliseconds(1)); } void event_base_tests::clear_complex() { auto thread_count = std::thread::hardware_concurrency(); auto test_liteners = std::vector<event_base_test_listener>(thread_count, event_base_test_listener{}); auto times = std::vector<std::chrono::microseconds>(); //auto threads = std::vector<std::thread>{}; //threads.reserve(10); auto futures = std::vector<std::future<void>>(); futures.reserve(thread_count); auto test = event_base<>{}; auto view = std::make_optional(test.view_lock()); try { std::mutex mutex; auto cv_mutex = std::mutex{}; auto cv = std::condition_variable{}; auto counter = std::atomic<int>{ 0 }; for (auto& test_litener : test_liteners) { //threads.push_back(std::thread( futures.push_back(std::async(std::launch::async, [&]() mutable { counter++; { auto lock = std::lock_guard{ cv_mutex }; } cv.notify_all(); auto time = std::chrono::system_clock::now(); test.subscribe(test_litener); auto lock = std::lock_guard(mutex); times.push_back(std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::system_clock::now() - time)); //auto view = test.view_lock(); })); } { auto lock = std::lock_guard(mutex); Assert::IsTrue(times.empty()); } //std::this_thread::sleep_for(std::chrono::milliseconds{ 40 }); { auto waiter = std::unique_lock{ cv_mutex }; cv.wait(waiter, [&] { return counter >= static_cast<std::size_t>(thread_count); }); } while(test.view_lock().size() != thread_count) { std::this_thread::yield(); } Assert::AreEqual<std::size_t>(test.view_lock().size(), thread_count); std::this_thread::sleep_for(std::chrono::milliseconds{ 5 }); view.reset(); //for (auto& thread : threads) // thread.join(); for (auto& future : futures) future.wait(); Assert::IsTrue(times.size() == thread_count); test_liteners.clear(); //auto lock = std::lock_guard(mutex); //threads.clear(); futures.clear(); } catch (const std::exception& e) { auto what = e.what(); assert(0); } for (auto& time : times) Assert::IsTrue(time > std::chrono::milliseconds{ 5 }); } }
22.361446
117
0.668822
Lizb3th
a44bd8fdbd3e5b4ddcb338a00d63eb81b28af541
967
cpp
C++
Engine2D/TestCameraScript.cpp
FroKCreativeTM/FroKEngine
a1e61a0982919efa42bfcbd1e93aacc049966afd
[ "BSD-3-Clause" ]
1
2022-01-10T13:00:27.000Z
2022-01-10T13:00:27.000Z
Engine2D/TestCameraScript.cpp
FroKCreativeTM/FroKEngine
a1e61a0982919efa42bfcbd1e93aacc049966afd
[ "BSD-3-Clause" ]
null
null
null
Engine2D/TestCameraScript.cpp
FroKCreativeTM/FroKEngine
a1e61a0982919efa42bfcbd1e93aacc049966afd
[ "BSD-3-Clause" ]
null
null
null
#include "pch.h" #include "TestCameraScript.h" #include "Transform.h" #include "Camera.h" #include "GameObject.h" #include "Input.h" #include "Timer.h" #include "SceneManager.h" #include "CollisionManager.h" TestCameraScript::TestCameraScript() { } TestCameraScript::~TestCameraScript() { } void TestCameraScript::LateUpdate() { Vec3 pos = GetTransform()->GetLocalPosition(); if (INPUT->GetButton(KEY_TYPE::W)) pos.y += GetTransform()->GetWorldPosition().y * DELTA_TIME; if (INPUT->GetButton(KEY_TYPE::S)) pos.y -= GetTransform()->GetWorldPosition().y * DELTA_TIME; if (INPUT->GetButton(KEY_TYPE::A)) pos.x -= GetTransform()->GetWorldPosition().x * DELTA_TIME; if (INPUT->GetButton(KEY_TYPE::D)) pos.x += GetTransform()->GetWorldPosition().x * DELTA_TIME; if (INPUT->GetButtonDown(KEY_TYPE::LBUTTON)) { const POINT& pos = INPUT->GetMousePos(); GET_SINGLE(CollisionManager)->Pick(pos.x, pos.y); } GetTransform()->SetLocalPosition(pos); }
22.488372
61
0.711479
FroKCreativeTM
a44be3be92826e920fd75ce827b41170f0f8b49a
2,148
cpp
C++
Train/El_Sageer/El_Sageer_Pupil/08 - 14 - [SP]/11 - 12 - [SP] Greedy/12 - [SP] Greedy/onTopic/4.UVa [11157].cpp
mohamedGamalAbuGalala/Practice
2a5fa3bdaf995d0c304f04231e1a69e6960f72c8
[ "MIT" ]
1
2019-12-19T06:51:20.000Z
2019-12-19T06:51:20.000Z
Train/El_Sageer/El_Sageer_Pupil/08 - 14 - [SP]/11 - 12 - [SP] Greedy/12 - [SP] Greedy/onTopic/4.UVa [11157].cpp
mohamedGamalAbuGalala/Practice
2a5fa3bdaf995d0c304f04231e1a69e6960f72c8
[ "MIT" ]
null
null
null
Train/El_Sageer/El_Sageer_Pupil/08 - 14 - [SP]/11 - 12 - [SP] Greedy/12 - [SP] Greedy/onTopic/4.UVa [11157].cpp
mohamedGamalAbuGalala/Practice
2a5fa3bdaf995d0c304f04231e1a69e6960f72c8
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; // input handle #define iln() scanf("\n") //scan new line #define in(n) scanf("%d",&n) //scan int #define ins(n) scanf("%s",n) //scan char[] #define inc(n) scanf("%c ",&n) //scan char #define inf(n) scanf("%lf",&n) //scan double/float #define inl(n) scanf("%lld",&n) //scan long long int #define ot(x) printf("%d", x) //output int #define sp() printf(" ") //output single space #define ots(x) printf("%s", x) //output char[] ( be careful using it may have some issue ) #define otc(x) printf("%c", x) //output char #define ln() printf("\n") //output new line #define otl(x) printf("%lld", x)//output long long int #define otf(x) printf("%.2lf", x)// output double/float with 0.00 // helpers defines #define all(v) v.begin(), v.end() #define sz(v) ((int)((v).size())) // eg... vector<int> v; sz(v) #define ssz(s) ((int)strlen(s)) // eg... char s[10]; ssz(s) #define pb push_back #define mem(a,b) memset(a,b,sizeof(a)) //helpers void file() { #ifndef ONLINE_JUDGE freopen("in.txt", "r", stdin); // freopen("ot.txt", "w", stdout); #else // freopen("jumping.in", "r", stdin); // HERE #endif } // constants #define EPS 1e-9 #define PI acos(-1.0) // important constant; alternative #define PI (2.0 * acos(0.0)) const int MN = 1e6 + 1e2; const int MW = 1e3 + 5; typedef long long int lli; const int OO = 1e9 + 5; typedef pair<int, int> ii; typedef vector<int> vi; typedef vector<vi> vvi; typedef vector<ii> vii; typedef pair<lli, string> lls; int main() { file(); // TODO int n, pp[105], T, l; bool sm[105], v[105]; char type, sep; in(T); for (int t = 1; t <= T; ++t) { in(n), in(l); for (int i = 0; i < n and cin >> type >> sep >> pp[i]; sm[i] = (type == 'S'), v[i] = 0, ++i) ; sm[n] = 0, pp[n] = l, v[n] = 0; int mx = pp[0]; for (int i = 0; i < n; ++i) { v[i] = 1; if (!sm[i + 1]) mx = max(mx, pp[i + 1] - pp[i]); else mx = max(mx, pp[i + 2] - pp[i]), ++i; } for (int i = n; i > 0; --i) if (!v[i - 1] or !sm[i - 1]) mx = max(mx, pp[i] - pp[i - 1]); else mx = max(mx, pp[i] - pp[i - 2]), --i; printf("Case %d: %d\n", t, mx); } return 0; }
29.027027
91
0.562849
mohamedGamalAbuGalala
a44d5554d82ffd1f84b25f42e6e66bff8a1bb379
466
cpp
C++
problemsets/UVA/10339.cpp
juarezpaulino/coderemite
a4649d3f3a89d234457032d14a6646b3af339ac1
[ "Apache-2.0" ]
null
null
null
problemsets/UVA/10339.cpp
juarezpaulino/coderemite
a4649d3f3a89d234457032d14a6646b3af339ac1
[ "Apache-2.0" ]
null
null
null
problemsets/UVA/10339.cpp
juarezpaulino/coderemite
a4649d3f3a89d234457032d14a6646b3af339ac1
[ "Apache-2.0" ]
null
null
null
/** * * Author: Juarez Paulino(coderemite) * Email: juarez.paulino@gmail.com * */ #define _USE_MATH_DEFINES #include <bits/stdc++.h> using namespace std; typedef long long ll; int main() { int k, m; while (cin >> k >> m) { if (k == m) { cout << k << " " << m << " " << "12:00" << endl; continue; } int n = 6 * abs(k-m); int t = (4320 * (86400 - k) + n/2) / n; t %= 60*12; printf("%d %d %02d:%02d\n", k, m, t<60?12:t/60, t%60); } return 0; }
17.259259
76
0.521459
juarezpaulino
a451c93cbdd6822e4ac7ca032953bb3d3d78014f
1,047
cc
C++
src/binding.cc
indutny/uv_link_t-binding
9ad7dfee9d052077a0e67c561ce258436e3278f9
[ "Unlicense", "MIT" ]
1
2020-03-27T05:44:03.000Z
2020-03-27T05:44:03.000Z
src/binding.cc
indutny/uv_link_t-binding
9ad7dfee9d052077a0e67c561ce258436e3278f9
[ "Unlicense", "MIT" ]
null
null
null
src/binding.cc
indutny/uv_link_t-binding
9ad7dfee9d052077a0e67c561ce258436e3278f9
[ "Unlicense", "MIT" ]
null
null
null
#include "nan.h" #include "uv.h" #include "uv_link_t.h" #include "src/observer.h" #include "src/source.h" namespace node { namespace link { using namespace v8; enum AuxType { kChainType, kUnchainType }; template <AuxType type> static NAN_METHOD(AuxMethod) { if (info.Length() != 2 || !info[0]->IsExternal() || !info[1]->IsExternal()) return Nan::ThrowError("Link::Chain expects External as both arguments"); uv_link_t* from = reinterpret_cast<uv_link_t*>(info[0].As<External>()->Value()); uv_link_t* to = reinterpret_cast<uv_link_t*>(info[1].As<External>()->Value()); int err; if (type == kChainType) err = uv_link_chain(from, to); else err = uv_link_unchain(from, to); info.GetReturnValue().Set(err); } static NAN_MODULE_INIT(Init) { Observer::Init(target); LinkSource::Init(target); Nan::SetMethod(target, "chain", AuxMethod<kChainType>); Nan::SetMethod(target, "unchain", AuxMethod<kUnchainType>); } } // namespace link } // namespace node NODE_MODULE(binding, node::link::Init);
21.367347
77
0.679083
indutny
a45797c83e6a8429b39081fcae5a55821ce06a4d
3,325
cpp
C++
test/context.cpp
selfienetworks/COSE-C
97d1805e71b7a6770093c5e6790d46611680d563
[ "BSD-3-Clause" ]
25
2016-07-15T12:11:42.000Z
2021-11-19T20:52:46.000Z
test/context.cpp
selfienetworks/COSE-C
97d1805e71b7a6770093c5e6790d46611680d563
[ "BSD-3-Clause" ]
96
2015-09-04T05:12:01.000Z
2021-12-30T08:39:56.000Z
test/context.cpp
selfienetworks/COSE-C
97d1805e71b7a6770093c5e6790d46611680d563
[ "BSD-3-Clause" ]
21
2015-05-27T03:27:21.000Z
2021-08-10T15:10:10.000Z
#include <stdlib.h> #ifdef _MSC_VER #endif #include <stdio.h> #include <memory.h> #include <assert.h> #include <cn-cbor/cn-cbor.h> #include <cose/cose.h> #ifdef USE_CBOR_CONTEXT #include "context.h" typedef struct { cn_cbor_context context; byte *pFirst; int iFailLeft; int allocCount; } MyContext; typedef struct _MyItem { int allocNumber; struct _MyItem *pNext; size_t size; byte pad[4]; byte data[4]; } MyItem; bool CheckMemory(MyContext *pContext) { MyItem *p = nullptr; // Walk memory and check every block for (p = (MyItem *)pContext->pFirst; p != nullptr; p = p->pNext) { if (p->pad[0] == (byte)0xab) { // Block has been freed for (unsigned i = 0; i < p->size + 8; i++) { if (p->pad[i] != (byte)0xab) { fprintf(stderr, "Freed block is modified"); assert(false); } } } else if (p->pad[0] == (byte)0xef) { for (unsigned i = 0; i < 4; i++) { if ((p->pad[i] != (byte)0xef) || (p->pad[i + 4 + p->size] != (byte)0xef)) { fprintf(stderr, "Current block was overrun"); assert(false); } } } else { fprintf(stderr, "Incorrect pad value"); assert(false); } } return true; } void *MyCalloc(size_t count, size_t size, void *context) { MyItem *pb = nullptr; MyContext *myContext = (MyContext *)context; CheckMemory(myContext); if (myContext->iFailLeft != -1) { if (myContext->iFailLeft == 0) { return nullptr; } myContext->iFailLeft--; } pb = (MyItem *)malloc(sizeof(MyItem) + count * size); memset(pb, 0xef, sizeof(MyItem) + count * size); memset(&pb->data, 0, count * size); pb->pNext = (struct _MyItem *)myContext->pFirst; myContext->pFirst = (byte *)pb; pb->size = count * size; pb->allocNumber = myContext->allocCount++; return &pb->data; } void MyFree(void *ptr, void *context) { MyItem *pb = (MyItem *)((byte *)ptr - sizeof(MyItem) + 4); MyContext *myContext = (MyContext *)context; MyItem *pItem = nullptr; CheckMemory(myContext); if (ptr == nullptr) { return; } for (pItem = (MyItem *)myContext->pFirst; pItem != nullptr; pItem = pItem->pNext) { if (pItem == pb) { break; } } if (pItem == nullptr) { // Not an item we allocated assert(false); return; } if (pItem->pad[0] == (byte)0xab) { // already freed. assert(false); } memset(&pb->pad, 0xab, pb->size + 8); } cn_cbor_context *CreateContext(int iFailPoint) { MyContext *p = (MyContext *)malloc(sizeof(MyContext)); p->context.calloc_func = MyCalloc; p->context.free_func = MyFree; p->context.context = p; p->pFirst = nullptr; p->iFailLeft = iFailPoint; p->allocCount = 0; return &p->context; } void FreeContext(cn_cbor_context *pContext) { MyContext *myContext = (MyContext *)pContext; MyItem *pItem; MyItem *pItem2; CheckMemory(myContext); for (pItem = (MyItem *)myContext->pFirst; pItem != nullptr; pItem = pItem2) { pItem2 = pItem->pNext; free(pItem); } free(myContext); } int IsContextEmpty(cn_cbor_context *pContext) { MyContext *myContext = (MyContext *)pContext; int i = 0; // Walk memory and check every block for (MyItem *p = (MyItem *)myContext->pFirst; p != nullptr; p = p->pNext) { if (p->pad[0] == (byte)0xab) { // Block has been freed } else { // This block has not been freed i += 1; } } return i; } #endif // USE_CBOR_CONTEXT
19.219653
76
0.628271
selfienetworks
a45a5498565e04e84c82759356634ba7a02f1d32
3,074
cpp
C++
NostaleLogin/dllmain.cpp
hatz02/NostaleLogin
3961be0622d4621af7a95a6a8864ca90ab5ba6c8
[ "MIT" ]
null
null
null
NostaleLogin/dllmain.cpp
hatz02/NostaleLogin
3961be0622d4621af7a95a6a8864ca90ab5ba6c8
[ "MIT" ]
null
null
null
NostaleLogin/dllmain.cpp
hatz02/NostaleLogin
3961be0622d4621af7a95a6a8864ca90ab5ba6c8
[ "MIT" ]
null
null
null
#include "NewServerSelectWidget.h" #include <string> int main() { const int BUFFER_SIZE = 2; const char* pipeName = "\\\\.\\pipe\\GflessClient"; int language, server, channel; HANDLE hPipe; DWORD dwMode; BOOL fSuccess; std::string message; char readBuffer[BUFFER_SIZE]; NewServerSelectWidget newServerSelectWidget; // Set up a pipe to communicate with the Gfless Client // and receive the values for the language server, // the server and the channel hPipe = CreateFileA(pipeName, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); if (hPipe == INVALID_HANDLE_VALUE) if (!WaitNamedPipeA(pipeName, 20000)) return EXIT_FAILURE; dwMode = PIPE_READMODE_BYTE | PIPE_WAIT; fSuccess = SetNamedPipeHandleState(hPipe, &dwMode, NULL, NULL); if (!fSuccess) return EXIT_FAILURE; // Send the server language message message = "ServerLanguage"; fSuccess = WriteFile(hPipe, message.c_str(), message.size(), NULL, NULL); if (!fSuccess) return EXIT_FAILURE; ZeroMemory(readBuffer, BUFFER_SIZE); fSuccess = ReadFile(hPipe, readBuffer, BUFFER_SIZE, NULL, NULL); if (!fSuccess) return EXIT_FAILURE; language = readBuffer[0] - 0x30; // Send the server message message = "Server"; fSuccess = WriteFile(hPipe, message.c_str(), message.size(), NULL, NULL); if (!fSuccess) return EXIT_FAILURE; ZeroMemory(readBuffer, BUFFER_SIZE); fSuccess = ReadFile(hPipe, readBuffer, BUFFER_SIZE, NULL, NULL); if (!fSuccess) return EXIT_FAILURE; server = readBuffer[0] - 0x30; // Send the channel message message = "Channel"; fSuccess = WriteFile(hPipe, message.c_str(), message.size(), NULL, NULL); if (!fSuccess) return EXIT_FAILURE; ZeroMemory(readBuffer, BUFFER_SIZE); fSuccess = ReadFile(hPipe, readBuffer, BUFFER_SIZE, NULL, NULL); if (!fSuccess) return EXIT_FAILURE; channel = readBuffer[0] - 0x30; // Wait for the login widget to be visible // and log into the desired server and channel while (!newServerSelectWidget.isVisible()) Sleep(500); newServerSelectWidget.selectLanguage(language); Sleep(3000); while (!newServerSelectWidget.isVisible()) Sleep(500); newServerSelectWidget.selectServer(server); Sleep(1000); newServerSelectWidget.selectChannel(channel);; return EXIT_SUCCESS; } DWORD WINAPI DllStart(LPVOID param) { FreeLibraryAndExitThread((HMODULE)param, main()); } BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) { HANDLE hThread; switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: DisableThreadLibraryCalls(hModule); hThread = CreateThread(NULL, NULL, DllStart, hModule, NULL, NULL); if (hThread != NULL) CloseHandle(hThread); break; case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: break; } return TRUE; }
25.831933
97
0.672414
hatz02
a45b34c3fedf4055b7a309684151c2d22b448015
3,802
cpp
C++
src/lib/texturelib/InputImage.cpp
hexgear-studio/ds_mod_tools
3fe0cad89848c9d0fca8a4139a0491d188497636
[ "MIT" ]
112
2015-01-15T21:36:02.000Z
2021-12-28T19:19:01.000Z
src/lib/texturelib/InputImage.cpp
hexgear-studio/ds_mod_tools
3fe0cad89848c9d0fca8a4139a0491d188497636
[ "MIT" ]
6
2017-03-14T00:42:42.000Z
2022-01-06T23:09:18.000Z
src/lib/texturelib/InputImage.cpp
hexgear-studio/ds_mod_tools
3fe0cad89848c9d0fca8a4139a0491d188497636
[ "MIT" ]
35
2015-01-15T21:34:36.000Z
2022-01-29T07:42:34.000Z
#include "pch.h" #include "InputImage.h" InputImage::InputImage( const std::string& filename ) : mDIB( NULL ) { FREE_IMAGE_FORMAT fif = FIF_UNKNOWN; fif = FreeImage_GetFileType( filename.c_str(), 0 ); if( fif == FIF_UNKNOWN ) fif = FreeImage_GetFIFFromFilename( filename.c_str() ); if( fif == FIF_UNKNOWN ) throw; if(FreeImage_FIFSupportsReading(fif)) { mDIB = FreeImage_Load( fif, filename.c_str() ); FreeImage_FlipVertical( mDIB ); } if( !mDIB ) throw; } InputImage::InputImage( FIBITMAP* dib ) : mDIB( dib ) { } InputImage::InputImage( uint32_t w, uint32_t h, uint32_t bpp ) { mDIB = FreeImage_Allocate( w, h, bpp ); } InputImage::~InputImage() { FreeImage_Unload( mDIB ); } uint32_t InputImage::Width() const { return FreeImage_GetWidth( mDIB ); } uint32_t InputImage::Height() const { return FreeImage_GetHeight( mDIB ); } uint32_t InputImage::BPP() const { return FreeImage_GetBPP( mDIB ); } void* InputImage::RawData() const { return FreeImage_GetBits( mDIB ); } InputImage* InputImage::ConvertTo32Bit() const { FIBITMAP* converted = FreeImage_ConvertTo32Bits( mDIB ); InputImage* result = new InputImage( converted ); return result; } InputImage* InputImage::ConvertTo24Bit() const { FIBITMAP* converted = FreeImage_ConvertTo24Bits( mDIB ); InputImage* result = new InputImage( converted ); return result; } InputImage* InputImage::Clone() const { return new InputImage( FreeImage_Clone( mDIB ) ); } Colour InputImage::GetPixel( uint32_t x, uint32_t y ) const { RGBQUAD rgb_quad; FreeImage_GetPixelColor( mDIB, x, y, &rgb_quad ); Colour result; result.r = rgb_quad.rgbRed; result.g = rgb_quad.rgbGreen; result.b = rgb_quad.rgbBlue; result.a = rgb_quad.rgbReserved; return result; } void InputImage::SetPixel( uint32_t x, uint32_t y, const Colour& c ) { RGBQUAD rgb_quad; rgb_quad.rgbRed = c.r; rgb_quad.rgbGreen = c.g; rgb_quad.rgbBlue = c.b; rgb_quad.rgbReserved = c.a; FreeImage_SetPixelColor( mDIB, x, y, &rgb_quad ); } InputImage* InputImage::Resize( uint32_t w, uint32_t h, FREE_IMAGE_FILTER filter ) { return new InputImage( FreeImage_Rescale( mDIB, w, h, filter ) ); } void InputImage::Save( const char* filename ) const { FreeImage_Save( FIF_TARGA, mDIB, filename ); } void InputImage::FlipVertical() const { FreeImage_FlipVertical( mDIB ); } void InputImage::PremultiplyAlpha() { for( uint32_t y = 0; y < Height(); ++y ) { for( uint32_t x = 0; x < Width(); ++x ) { RGBQUAD rgb_quad; FreeImage_GetPixelColor( mDIB, x, y, &rgb_quad ); float alpha = ( rgb_quad.rgbReserved ) / 255.0f; rgb_quad.rgbRed = static_cast< BYTE > ( alpha * rgb_quad.rgbRed + 0.5 ); rgb_quad.rgbGreen = static_cast< BYTE > ( alpha * rgb_quad.rgbGreen + 0.5 );; rgb_quad.rgbBlue = static_cast< BYTE > ( alpha * rgb_quad.rgbBlue + 0.5 );; FreeImage_SetPixelColor( mDIB, x, y, &rgb_quad ); } } } void InputImage::ApplyHardAlpha() { for( uint32_t y = 0; y < Height(); ++y ) { for( uint32_t x = 0; x < Width(); ++x ) { RGBQUAD rgb_quad; FreeImage_GetPixelColor( mDIB, x, y, &rgb_quad ); float alpha = ( rgb_quad.rgbReserved ) / 255.0f; if( alpha > 0.5f ) { rgb_quad.rgbReserved = 255; } else { rgb_quad.rgbReserved = 0; } FreeImage_SetPixelColor( mDIB, x, y, &rgb_quad ); } } } void InputImage::Clear() { Colour c; c.mVal = 0; for( uint32_t y = 0; y < Height(); ++y ) { for( uint32_t x = 0; x < Width(); ++x ) { SetPixel( x, y, c ); } } } bool InputImage::Paste( const InputImage* src, uint32_t top, uint32_t left, uint32_t alpha ) { return FreeImage_Paste( mDIB, src->mDIB, left, top, alpha ) != 0; }
20.551351
92
0.652814
hexgear-studio
a45b4bd8167be30faf817dce3e354605d37eae5a
285
cpp
C++
TOJ/toj 499.cpp
Xi-Plus/OJ-Code
7ff6d691f34c9553d53dc9cddf90ad7dc7092349
[ "MIT" ]
null
null
null
TOJ/toj 499.cpp
Xi-Plus/OJ-Code
7ff6d691f34c9553d53dc9cddf90ad7dc7092349
[ "MIT" ]
null
null
null
TOJ/toj 499.cpp
Xi-Plus/OJ-Code
7ff6d691f34c9553d53dc9cddf90ad7dc7092349
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define endl '\n' using namespace std; int main() { // ios::sync_with_stdio(false); // cin.tie(0); string a, b; int n; getline(cin, a); cin>>n; cin.ignore(); for(int q=0; q<n; q++){ getline(cin, b); if(a==b){ cout<<q+1<<" "; } } cout<<endl; }
14.25
31
0.550877
Xi-Plus
a4616b5b2ccfbf82f8cc1e6d054758e76a68acf1
358
cpp
C++
my_awesome_application/src/main.cpp
Life4gal/galFormat
98a2ef98944dfc909a9613f4952565d7f521b833
[ "Unlicense" ]
4
2021-03-13T06:48:27.000Z
2021-03-23T12:12:48.000Z
my_awesome_application/src/main.cpp
Life4gal/galFormat
98a2ef98944dfc909a9613f4952565d7f521b833
[ "Unlicense" ]
1
2021-06-21T15:18:17.000Z
2021-09-18T06:01:07.000Z
my_awesome_application/src/main.cpp
Life4gal/galStarterTemplate
98a2ef98944dfc909a9613f4952565d7f521b833
[ "Unlicense" ]
null
null
null
#include <iostream> #include <fmt/format.h> #include <module1/hello1.hpp> #include <module1/hey1.hpp> #include <module2/hello2.hpp> int main() { std::cout << fmt::format( "module1::hello1 -> {}\nmodule2::hello2 -> {}\nmodule1::hey -> {}\n", my::printer1::say_something(), my::printer2::say_something(), my::greeting1::say_something() ); }
19.888889
72
0.645251
Life4gal
a462d6a331c8b201d3b0d59912b8407dfac57231
6,963
cpp
C++
src/hotspot/share/gc/shared/scavengableNMethods.cpp
siweilxy/openjdkstudy
8597674ec1d6809faf55cbee1f45f4e9149d670d
[ "Apache-2.0" ]
1
2020-12-26T04:52:15.000Z
2020-12-26T04:52:15.000Z
src/hotspot/share/gc/shared/scavengableNMethods.cpp
siweilxy/openjdkstudy
8597674ec1d6809faf55cbee1f45f4e9149d670d
[ "Apache-2.0" ]
1
2020-12-26T04:57:19.000Z
2020-12-26T04:57:19.000Z
src/hotspot/share/gc/shared/scavengableNMethods.cpp
siweilxy/openjdkstudy
8597674ec1d6809faf55cbee1f45f4e9149d670d
[ "Apache-2.0" ]
1
2021-12-06T01:13:18.000Z
2021-12-06T01:13:18.000Z
/* * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. * */ #include "precompiled.hpp" #include "code/codeCache.hpp" #include "code/nmethod.hpp" #include "gc/shared/scavengableNMethods.hpp" #include "gc/shared/scavengableNMethodsData.hpp" #include "runtime/mutexLocker.hpp" #include "utilities/debug.hpp" static ScavengableNMethodsData gc_data(nmethod* nm) { return ScavengableNMethodsData(nm); } nmethod* ScavengableNMethods::_head = NULL; BoolObjectClosure* ScavengableNMethods::_is_scavengable = NULL; void ScavengableNMethods::initialize(BoolObjectClosure* is_scavengable) { _is_scavengable = is_scavengable; } // Conditionally adds the nmethod to the list if it is // not already on the list and has a scavengeable root. void ScavengableNMethods::register_nmethod(nmethod* nm) { assert_locked_or_safepoint(CodeCache_lock); ScavengableNMethodsData data = gc_data(nm); if (data.on_list() || !has_scavengable_oops(nm)) { return; } data.set_on_list(); data.set_next(_head); _head = nm; } void ScavengableNMethods::unregister_nmethod(nmethod* nm) { assert_locked_or_safepoint(CodeCache_lock); if (gc_data(nm).on_list()) { nmethod* prev = NULL; for (nmethod* cur = _head; cur != NULL; cur = gc_data(cur).next()) { if (cur == nm) { unlist_nmethod(cur, prev); return; } prev = cur; } } } #ifndef PRODUCT class DebugScavengableOops: public OopClosure { BoolObjectClosure* _is_scavengable; nmethod* _nm; bool _ok; public: DebugScavengableOops(BoolObjectClosure* is_scavengable, nmethod* nm) : _is_scavengable(is_scavengable), _nm(nm), _ok(true) { } bool ok() { return _ok; } virtual void do_oop(oop* p) { if (*p == NULL || !_is_scavengable->do_object_b(*p)) { return; } if (_ok) { _nm->print_nmethod(true); _ok = false; } tty->print_cr("*** scavengable oop " PTR_FORMAT " found at " PTR_FORMAT " (offset %d)", p2i(*p), p2i(p), (int)((intptr_t)p - (intptr_t)_nm)); (*p)->print(); } virtual void do_oop(narrowOop* p) { ShouldNotReachHere(); } }; #endif // PRODUCT void ScavengableNMethods::verify_nmethod(nmethod* nm) { #ifndef PRODUCT if (!gc_data(nm).on_list()) { // Actually look inside, to verify the claim that it's clean. DebugScavengableOops cl(_is_scavengable, nm); nm->oops_do(&cl); if (!cl.ok()) fatal("found an unadvertised bad scavengable oop in the code cache"); } assert(gc_data(nm).not_marked(), ""); #endif // PRODUCT } class HasScavengableOops: public OopClosure { BoolObjectClosure* _is_scavengable; bool _found; public: HasScavengableOops(BoolObjectClosure* is_scavengable, nmethod* nm) : _is_scavengable(is_scavengable), _found(false) {} bool found() { return _found; } virtual void do_oop(oop* p) { if (!_found && *p != NULL && _is_scavengable->do_object_b(*p)) { _found = true; } } virtual void do_oop(narrowOop* p) { ShouldNotReachHere(); } }; bool ScavengableNMethods::has_scavengable_oops(nmethod* nm) { HasScavengableOops cl(_is_scavengable, nm); nm->oops_do(&cl); return cl.found(); } // Walk the list of methods which might contain oops to the java heap. void ScavengableNMethods::nmethods_do_and_prune(CodeBlobToOopClosure* cl) { assert_locked_or_safepoint(CodeCache_lock); debug_only(mark_on_list_nmethods()); nmethod* prev = NULL; nmethod* cur = _head; while (cur != NULL) { assert(cur->is_alive(), "Must be"); ScavengableNMethodsData data = gc_data(cur); debug_only(data.clear_marked()); assert(data.on_list(), "else shouldn't be on this list"); if (cl != NULL) { cl->do_code_blob(cur); } nmethod* const next = data.next(); if (!has_scavengable_oops(cur)) { unlist_nmethod(cur, prev); } else { prev = cur; } cur = next; } // Check for stray marks. debug_only(verify_unlisted_nmethods(NULL)); } void ScavengableNMethods::prune_nmethods() { nmethods_do_and_prune(NULL /* No closure */); } // Walk the list of methods which might contain oops to the java heap. void ScavengableNMethods::nmethods_do(CodeBlobToOopClosure* cl) { nmethods_do_and_prune(cl); } #ifndef PRODUCT void ScavengableNMethods::asserted_non_scavengable_nmethods_do(CodeBlobClosure* cl) { // While we are here, verify the integrity of the list. mark_on_list_nmethods(); for (nmethod* cur = _head; cur != NULL; cur = gc_data(cur).next()) { assert(gc_data(cur).on_list(), "else shouldn't be on this list"); gc_data(cur).clear_marked(); } verify_unlisted_nmethods(cl); } #endif // PRODUCT void ScavengableNMethods::unlist_nmethod(nmethod* nm, nmethod* prev) { assert_locked_or_safepoint(CodeCache_lock); assert((prev == NULL && _head == nm) || (prev != NULL && gc_data(prev).next() == nm), "precondition"); ScavengableNMethodsData data = gc_data(nm); if (prev == NULL) { _head = data.next(); } else { gc_data(prev).set_next(data.next()); } data.set_next(NULL); data.clear_on_list(); } #ifndef PRODUCT // Temporarily mark nmethods that are claimed to be on the scavenge list. void ScavengableNMethods::mark_on_list_nmethods() { NMethodIterator iter(NMethodIterator::only_alive); while(iter.next()) { nmethod* nm = iter.method(); ScavengableNMethodsData data = gc_data(nm); assert(data.not_marked(), "clean state"); if (data.on_list()) data.set_marked(); } } // If the closure is given, run it on the unlisted nmethods. // Also make sure that the effects of mark_on_list_nmethods is gone. void ScavengableNMethods::verify_unlisted_nmethods(CodeBlobClosure* cl) { NMethodIterator iter(NMethodIterator::only_alive); while(iter.next()) { nmethod* nm = iter.method(); verify_nmethod(nm); if (cl != NULL && !gc_data(nm).on_list()) { cl->do_code_blob(nm); } } } #endif //PRODUCT
28.536885
91
0.691656
siweilxy
a4660174e14ca7c4a94663a9aec8beaf6f041c3e
4,477
cxx
C++
Common/DataModel/Testing/Cxx/TestPolygonBoundedTriangulate.cxx
LongerVisionUSA/VTK
1170774b6611c71b95c28bb821d51c2c18ff091f
[ "BSD-3-Clause" ]
1
2019-05-31T14:00:53.000Z
2019-05-31T14:00:53.000Z
Common/DataModel/Testing/Cxx/TestPolygonBoundedTriangulate.cxx
LongerVisionUSA/VTK
1170774b6611c71b95c28bb821d51c2c18ff091f
[ "BSD-3-Clause" ]
null
null
null
Common/DataModel/Testing/Cxx/TestPolygonBoundedTriangulate.cxx
LongerVisionUSA/VTK
1170774b6611c71b95c28bb821d51c2c18ff091f
[ "BSD-3-Clause" ]
null
null
null
/*========================================================================= Program: Visualization Toolkit Module: TestPolygon.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ // .NAME // .SECTION Description // this program tests the BoundedTriangulate method in Polygon #include "vtkIdList.h" #include "vtkNew.h" #include "vtkPoints.h" #include "vtkPolygon.h" // #define VISUAL_DEBUG 1 #ifdef VISUAL_DEBUG #include <vtkActor.h> #include <vtkCellArray.h> #include <vtkPolyData.h> #include <vtkPolyDataMapper.h> #include <vtkProperty.h> #include <vtkRenderWindow.h> #include <vtkRenderWindowInteractor.h> #include <vtkRenderer.h> #endif #include <vector> bool ValidTessellation(vtkPolygon* polygon, vtkIdList* outTris) { // Check that there are enough triangles if (outTris->GetNumberOfIds() / 3 != polygon->GetNumberOfPoints() - 2) { return false; } // Check that all of the edges of the polygon are represented std::vector<bool> edges(polygon->GetNumberOfPoints(), false); for (int i = 0; i < polygon->GetNumberOfPoints(); i++) { vtkIdType edge[2] = { polygon->GetPointId(i), polygon->GetPointId((i + 1) % polygon->GetNumberOfPoints()) }; for (int j = 0; j < outTris->GetNumberOfIds(); j += 3) { for (int k = 0; k < 3; k++) { vtkIdType triedge[2] = { polygon->PointIds->GetId(outTris->GetId(j + k)), polygon->PointIds->GetId(outTris->GetId(j + ((k + 1) % 3))) }; if ((triedge[0] == edge[0] && triedge[1] == edge[1]) || (triedge[0] == edge[1] && triedge[1] == edge[0])) { edges[i] = true; break; } } if (edges[i]) break; } if (!edges[i]) break; } for (std::size_t i = 0; i < edges.size(); i++) { if (!edges[i]) { return false; } } return true; } int TestPolygonBoundedTriangulate(int, char*[]) { vtkNew<vtkPolygon> polygon; polygon->GetPoints()->InsertNextPoint(125.703, 149.84, 45.852); polygon->GetPoints()->InsertNextPoint(126.438, 147.984, 44.3112); polygon->GetPoints()->InsertNextPoint(126.219, 148.174, 44.4463); polygon->GetPoints()->InsertNextPoint(126.196, 148.202, 44.4683); polygon->GetPoints()->InsertNextPoint(126.042, 148.398, 44.6184); polygon->GetPoints()->InsertNextPoint(125.854, 148.635, 44.8); polygon->GetPoints()->InsertNextPoint(125.598, 148.958, 45.0485); polygon->GetPoints()->InsertNextPoint(125.346, 149.24, 45.26); polygon->GetPoints()->InsertNextPoint(125.124, 149.441, 45.4041); polygon->GetPointIds()->SetNumberOfIds(polygon->GetPoints()->GetNumberOfPoints()); for (vtkIdType i = 0; i < polygon->GetPoints()->GetNumberOfPoints(); i++) { polygon->GetPointIds()->SetId(i, i); } vtkNew<vtkIdList> outTris; int success = polygon->BoundedTriangulate(outTris, 1.e-2); if (!success || !ValidTessellation(polygon, outTris)) { cerr << "ERROR: vtkPolygon::BoundedTriangulate should triangulate this polygon" << endl; return EXIT_FAILURE; } #ifdef VISUAL_DEBUG vtkNew<vtkCellArray> triangles; for (vtkIdType i = 0; i < outTris->GetNumberOfIds(); i += 3) { vtkIdType t[3] = { outTris->GetId(i), outTris->GetId(i + 1), outTris->GetId(i + 2) }; triangles->InsertNextCell(3, t); } vtkNew<vtkPolyData> polydata; polydata->SetPoints(polygon->GetPoints()); polydata->SetPolys(triangles); vtkNew<vtkPolyDataMapper> mapper; mapper->SetInputData(polydata); vtkNew<vtkActor> actor; actor->SetMapper(mapper); actor->GetProperty()->SetRepresentationToWireframe(); // Create a renderer, render window, and an interactor vtkNew<vtkRenderer> renderer; vtkNew<vtkRenderWindow> renderWindow; renderWindow->AddRenderer(renderer); vtkNew<vtkRenderWindowInteractor> renderWindowInteractor; renderWindowInteractor->SetRenderWindow(renderWindow); // Add the actors to the scene renderer->AddActor(actor); renderer->SetBackground(.1, .2, .4); // Render and interact renderWindow->Render(); renderWindowInteractor->Start(); #endif return EXIT_SUCCESS; }
29.071429
93
0.651552
LongerVisionUSA
a4676837163ed602733b36b27d3fd29ba3bf4f1d
647
cpp
C++
src/ui/ScrollBar.cpp
alikins/Rack
614c6d09883569563bc8a7c41513390babf2cabb
[ "BSD-2-Clause", "BSD-3-Clause" ]
null
null
null
src/ui/ScrollBar.cpp
alikins/Rack
614c6d09883569563bc8a7c41513390babf2cabb
[ "BSD-2-Clause", "BSD-3-Clause" ]
null
null
null
src/ui/ScrollBar.cpp
alikins/Rack
614c6d09883569563bc8a7c41513390babf2cabb
[ "BSD-2-Clause", "BSD-3-Clause" ]
null
null
null
#include "ui.hpp" #include "window.hpp" namespace rack { void ScrollBar::draw(NVGcontext *vg) { bndScrollBar(vg, 0.0, 0.0, box.size.x, box.size.y, state, offset, size); } void ScrollBar::onDragStart(EventDragStart &e) { state = BND_ACTIVE; windowCursorLock(); } void ScrollBar::onDragMove(EventDragMove &e) { ScrollWidget *scrollWidget = dynamic_cast<ScrollWidget*>(parent); assert(scrollWidget); if (orientation == HORIZONTAL) scrollWidget->offset.x += e.mouseRel.x; else scrollWidget->offset.y += e.mouseRel.y; } void ScrollBar::onDragEnd(EventDragEnd &e) { state = BND_DEFAULT; windowCursorUnlock(); } } // namespace rack
19.606061
73
0.718702
alikins
a46d0c80798e7154762f31345a834ab66e790d40
1,935
cpp
C++
test.cpp
wisd0me/plog-converter
e534fa5873c9036f5193a28be19e1ded9738586a
[ "Apache-2.0" ]
null
null
null
test.cpp
wisd0me/plog-converter
e534fa5873c9036f5193a28be19e1ded9738586a
[ "Apache-2.0" ]
null
null
null
test.cpp
wisd0me/plog-converter
e534fa5873c9036f5193a28be19e1ded9738586a
[ "Apache-2.0" ]
null
null
null
// 2006-2008 (c) Viva64.com Team // 2008-2020 (c) OOO "Program Verification Systems" // 2020 (c) PVS-Studio LLC #define CATCH_CONFIG_MAIN #include <catch.hpp> #include "warning.h" #include "application.h" using namespace PlogConverter; TEST_CASE("Warning::GetErrorCode") { Warning msg; msg.code = "V112"; REQUIRE(msg.GetErrorCode() == 112); msg.code = "V001"; REQUIRE(msg.GetErrorCode() == 1); } TEST_CASE("Warning::GetType") { Warning msg; msg.code = "V112"; REQUIRE(msg.GetType() == AnalyzerType::Viva64); msg.code = "V001"; REQUIRE(msg.GetType() == AnalyzerType::Fail); } TEST_CASE("Warning::GetVivaUrl") { Warning msg; msg.code = "V001"; REQUIRE(msg.GetVivaUrl() == "https://www.viva64.com/en/w/v001/"); msg.code = "V101"; REQUIRE(msg.GetVivaUrl() == "https://www.viva64.com/en/w/v101/"); msg.code = "V1001"; REQUIRE(msg.GetVivaUrl() == "https://www.viva64.com/en/w/v1001/"); msg.code = "Renew"; REQUIRE(msg.GetVivaUrl() == "https://www.viva64.com/en/renewal/"); } TEST_CASE("plog-converter -a") { std::vector<Analyzer> analyzers; ParseEnabledAnalyzers("all", analyzers); REQUIRE(analyzers.empty()); ParseEnabledAnalyzers("ALL", analyzers); REQUIRE(analyzers.empty()); ParseEnabledAnalyzers("GA:1,2;64:1;OP:1,2,3;CS:1;MISRA:1,2", analyzers); REQUIRE(analyzers.size() == 5); REQUIRE(analyzers[0].type == AnalyzerType::General); REQUIRE(analyzers[0].levels == (std::vector<int>{1, 2})); REQUIRE(analyzers[1].type == AnalyzerType::Viva64); REQUIRE(analyzers[1].levels == (std::vector<int>{1})); REQUIRE(analyzers[2].type == AnalyzerType::Optimization); REQUIRE(analyzers[2].levels == (std::vector<int>{1, 2, 3})); REQUIRE(analyzers[3].type == AnalyzerType::CustomerSpecific); REQUIRE(analyzers[3].levels == (std::vector<int>{1})); REQUIRE(analyzers[4].type == AnalyzerType::Misra); REQUIRE(analyzers[4].levels == (std::vector<int>{1, 2})); }
26.148649
74
0.668217
wisd0me
a46d47446e8c45c95d951bd91a24368a7ba08853
415
cpp
C++
trabalhos/trab1/paises.cpp
senapk/fup_2014_2
5fc2986724f2e5fb912524b6208744b7295c6347
[ "Apache-2.0" ]
null
null
null
trabalhos/trab1/paises.cpp
senapk/fup_2014_2
5fc2986724f2e5fb912524b6208744b7295c6347
[ "Apache-2.0" ]
null
null
null
trabalhos/trab1/paises.cpp
senapk/fup_2014_2
5fc2986724f2e5fb912524b6208744b7295c6347
[ "Apache-2.0" ]
null
null
null
/* Faça um código que receba um dos países abaixo e retorne o continente em que ele se encontra. Use o comando switch. */ #include <iostream> using namespace std; enum Pais { Brasil, Italia, EUA, Japao, Australia}; enum Continente { AmericaSul, AmericaNorte, Europa, Asia, Australia }; Continente acharLocalizacao( Pais pais){ //faça seu código aqui } int main () { //faça seu teste aqui return 0; }
20.75
70
0.715663
senapk
a46d61d25bc2c1095e446b7f126ebead1ef2832d
4,924
cpp
C++
firmware/ventilator-controller-stm32/Core/Src/Pufferfish/Driver/Serial/Nonin/FrameReceiver.cpp
raavilagoo/Test
e2de25cc4b6fcbffe3f98f4a7ce1644fa8b6bb16
[ "Apache-2.0" ]
null
null
null
firmware/ventilator-controller-stm32/Core/Src/Pufferfish/Driver/Serial/Nonin/FrameReceiver.cpp
raavilagoo/Test
e2de25cc4b6fcbffe3f98f4a7ce1644fa8b6bb16
[ "Apache-2.0" ]
null
null
null
firmware/ventilator-controller-stm32/Core/Src/Pufferfish/Driver/Serial/Nonin/FrameReceiver.cpp
raavilagoo/Test
e2de25cc4b6fcbffe3f98f4a7ce1644fa8b6bb16
[ "Apache-2.0" ]
null
null
null
/// FrameReceiver.cpp /// This file has methods to take input from FrameBuffer and output the /// frame on availability. // Copyright (c) 2020 Pez-Globo and the Pufferfish project contributors // SPDX-License-Identifier: Apache-2.0 // // 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 "Pufferfish/Driver/Serial/Nonin/FrameReceiver.h" namespace Pufferfish::Driver::Serial::Nonin { /** * validateStartOfFrame function is called on beginning to get the first frame * and on there is a loss of bytes or noise in the bytes of frame received. * Called based on start_of_frame_status_ private variable */ bool validate_start_of_frame(const Frame &new_frame) { /* Check for the byte 1 is 01 and 1st bit of byte 2 is 0x81 for the start of * frame */ static const uint8_t mask_start_of_packet = 0x81; if (new_frame[0] == 0x01 && (new_frame[1] & mask_start_of_packet) == mask_start_of_packet) { /* Checksum validation */ if (((new_frame[0] + new_frame[1] + new_frame[2] + new_frame[3]) % (UINT8_MAX + 1)) == new_frame[4]) { return true; } } return false; } /** * validateFrame function is called to validated the every frame for Status byte * and Checksum. */ FrameReceiver::FrameInputStatus validate_frame(const Frame &new_frame) { static const uint8_t mask_start_of_frame = 0x80; /* Check for the byte 1 is 01 and 1st bit of byte 2 is 0x80 for status byte */ if (new_frame[0] == 0x01 && (new_frame[1] & mask_start_of_frame) == mask_start_of_frame) { /* Checksum validation */ if (((new_frame[0] + new_frame[1] + new_frame[2] + new_frame[3]) % (UINT8_MAX + 1)) == new_frame[4]) { /* Return the start of packet status as available */ return FrameReceiver::FrameInputStatus::available; } } /* return the frame status as not available */ return FrameReceiver::FrameInputStatus::framing_error; } FrameReceiver::FrameInputStatus FrameReceiver::update_frame_buffer(uint8_t new_byte) { Frame frame_buffer; /* Input the new byte received and check for frame availability */ if (frame_buf_.input(new_byte) == BufferStatus::partial) { /* return false on frame is not available */ return FrameInputStatus::waiting; } /* On frame buffer input status is available update the frameBuffer with new frame */ if (frame_buf_.output(frame_buffer) != BufferStatus::ok) { /* return false on frame is not available */ return FrameInputStatus::waiting; } /* On start_of_frame_status_ false Validate the start of frame */ if (!start_of_frame_status_) { /* Validate the start of frame in the beginning of reading sensor data and on there is loss of bytes in a frame or noise occurred in recived frame due to which the validation of start of frame is called */ if (validate_start_of_frame(frame_buffer)) { /* On start of frame available update the start frame status as true */ start_of_frame_status_ = true; /* On Start frame is available return status as available */ return FrameInputStatus::available; } /* On non available of start frame left shift the frame buffer */ frame_buf_.shift_left(); /* On Start frame is not available return status as waiting */ return FrameInputStatus::waiting; } /* Validate the frame received and return the status */ input_status_ = validate_frame(frame_buffer); if (input_status_ == FrameInputStatus::framing_error) { /* On checksum error update the start frame status as false */ start_of_frame_status_ = false; } return input_status_; } FrameReceiver::FrameInputStatus FrameReceiver::input(const uint8_t new_byte) { /* Update the frame buffer with new byte received */ input_status_ = this->update_frame_buffer(new_byte); /* Return the input status */ return input_status_; } FrameReceiver::FrameOutputStatus FrameReceiver::output(Frame &frame) { /* Check for the frame availability in the buffer */ if (input_status_ != FrameInputStatus::available) { return FrameOutputStatus::waiting; } /* On frame available update the frameBuffer with new frame available */ if (frame_buf_.output(frame) != BufferStatus::ok) { /* return false on frame is not available */ return FrameOutputStatus::waiting; } frame_buf_.reset(); /* Return frame is available */ return FrameOutputStatus::available; } } // namespace Pufferfish::Driver::Serial::Nonin
37.022556
94
0.718928
raavilagoo
a46fb1e2117cae5873e3a18f93694220ac78f257
1,782
cpp
C++
src/ScreenCaptureLib/ScreenCapture.cpp
Postrediori/OceanSimulation
ff836f9c92f43e62a3e5c2befc065784d3c36ce0
[ "MIT" ]
14
2017-12-18T08:22:12.000Z
2021-04-12T13:05:42.000Z
src/ScreenCaptureLib/ScreenCapture.cpp
Postrediori/OceanSimulation
ff836f9c92f43e62a3e5c2befc065784d3c36ce0
[ "MIT" ]
4
2017-12-20T09:41:15.000Z
2020-06-26T10:56:48.000Z
src/ScreenCaptureLib/ScreenCapture.cpp
Postrediori/OceanSimulation
ff836f9c92f43e62a3e5c2befc065784d3c36ce0
[ "MIT" ]
2
2018-01-31T13:11:28.000Z
2019-05-20T04:04:28.000Z
#define STB_IMAGE_WRITE_IMPLEMENTATION #include <stb_image_write.h> #include "stdafx.h" #include "ScreenCapture.h" std::string ScreenCapture::GetNextFileName(ScreenCaptureFormat format) { static int counter = 0; std::stringstream s; s << "capture" << (counter++); if (format == ScreenCaptureFormat::Png) { s << ".png"; } else if (format == ScreenCaptureFormat::Jpg) { s << ".jpg"; } return s.str(); } bool ScreenCapture::SaveToFile(ScreenCaptureFormat format, int width, int height) { static const size_t ScreenCaptureBpp = 3; static const GLenum ScreenCaptureFormat = GL_RGB; std::vector<uint8_t> pixelBuffer(width * height * ScreenCaptureBpp); glReadPixels(0, 0, width, height, ScreenCaptureFormat, GL_UNSIGNED_BYTE, pixelBuffer.data()); stbi_flip_vertically_on_write(1); // flag is non-zero to flip data vertically std::string fileName = ScreenCapture::GetNextFileName(format); static const int ScreenCaptureComp = ScreenCaptureBpp; // 1=Y, 2=YA, 3=RGB, 4=RGBA int result = 0; if (format == ScreenCaptureFormat::Png) { int screenCaptureStride = width * ScreenCaptureBpp; result = stbi_write_png(fileName.c_str(), width, height, ScreenCaptureComp, pixelBuffer.data(), screenCaptureStride); } else if (format == ScreenCaptureFormat::Jpg) { static const int ScreenCaptureQuality = 90; result = stbi_write_jpg(fileName.c_str(), width, height, ScreenCaptureComp, pixelBuffer.data(), ScreenCaptureQuality); } if (!result) { LOGE << "Unable to capture screen to file " << fileName; return false; } LOGI << "Saved screen capture to file " << fileName << " (" << width << "x" << height << " pixels)"; return true; }
33.622642
126
0.673962
Postrediori
a4707414405f82069bd4a6783a2f0f6b0c55b20a
252
hpp
C++
Examples/ViewFactor/ViewFactorProcessData.hpp
FilipovicLado/ViennaLS
39d97c2fc0d36f250bebaaa6879747eb9a7ed23a
[ "MIT" ]
null
null
null
Examples/ViewFactor/ViewFactorProcessData.hpp
FilipovicLado/ViennaLS
39d97c2fc0d36f250bebaaa6879747eb9a7ed23a
[ "MIT" ]
null
null
null
Examples/ViewFactor/ViewFactorProcessData.hpp
FilipovicLado/ViennaLS
39d97c2fc0d36f250bebaaa6879747eb9a7ed23a
[ "MIT" ]
null
null
null
#pragma once #include <array> #include <limits> template <class T> struct ViewFactorProcessDataType { double gridDelta = 0.; T trenchDiameter; T trenchDepth; T topRate; T processTime; T timeStep; hrleVectorType<double, 2> taperAngle; };
18
53
0.72619
FilipovicLado
a473e478510c918fea8e75918c2a79a40882615b
5,900
cpp
C++
src/clients/data/arcmkdir.cpp
maikenp/arc
994ec850c73affb75e81ab9056cb8146ba75fa9f
[ "Apache-2.0" ]
null
null
null
src/clients/data/arcmkdir.cpp
maikenp/arc
994ec850c73affb75e81ab9056cb8146ba75fa9f
[ "Apache-2.0" ]
null
null
null
src/clients/data/arcmkdir.cpp
maikenp/arc
994ec850c73affb75e81ab9056cb8146ba75fa9f
[ "Apache-2.0" ]
null
null
null
// -*- indent-tabs-mode: nil -*- #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <string> #include <list> #include <unistd.h> #include <arc/ArcLocation.h> #include <arc/Logger.h> #include <arc/StringConv.h> #include <arc/URL.h> #include <arc/UserConfig.h> #include <arc/credential/Credential.h> #include <arc/data/DataHandle.h> #include <arc/loader/FinderLoader.h> #include <arc/OptionParser.h> static Arc::Logger logger(Arc::Logger::getRootLogger(), "arcmkdir"); bool arcmkdir(const Arc::URL& file_url, Arc::UserConfig& usercfg, bool with_parents) { if (!file_url) { logger.msg(Arc::ERROR, "Invalid URL: %s", file_url.str()); return false; } if (file_url.Protocol() == "urllist") { std::list<Arc::URL> files = Arc::ReadURLList(file_url); if (files.empty()) { logger.msg(Arc::ERROR, "Can't read list of locations from file %s", file_url.Path()); return false; } bool r = true; for (std::list<Arc::URL>::iterator file = files.begin(); file != files.end(); ++file) { if (!arcmkdir(*file, usercfg, with_parents)) r = false; } return r; } Arc::DataHandle url(file_url, usercfg); if (!url) { logger.msg(Arc::ERROR, "Unsupported URL given"); return false; } if (url->RequiresCredentials()) { if (!usercfg.InitializeCredentials(Arc::initializeCredentialsType::RequireCredentials)) { logger.msg(Arc::ERROR, "Unable to create directory %s", file_url.str()); logger.msg(Arc::ERROR, "Invalid credentials, please check proxy and/or CA certificates"); return false; } Arc::Credential holder(usercfg); if (!holder.IsValid()) { if (holder.GetEndTime() < Arc::Time()) { logger.msg(Arc::ERROR, "Proxy expired"); } logger.msg(Arc::ERROR, "Unable to create directory %s", file_url.str()); logger.msg(Arc::ERROR, "Invalid credentials, please check proxy and/or CA certificates"); return false; } } url->SetSecure(false); Arc::DataStatus res = url->CreateDirectory(with_parents); if (!res.Passed()) { logger.msg(Arc::ERROR, std::string(res)); if (res.Retryable()) logger.msg(Arc::ERROR, "This seems like a temporary error, please try again later"); return false; } return true; } static int runmain(int argc, char **argv) { setlocale(LC_ALL, ""); static Arc::LogStream logcerr(std::cerr); logcerr.setFormat(Arc::ShortFormat); Arc::Logger::getRootLogger().addDestination(logcerr); Arc::Logger::getRootLogger().setThreshold(Arc::WARNING); Arc::ArcLocation::Init(argv[0]); Arc::OptionParser options(istring("url"), istring("The arcmkdir command creates directories " "on grid storage elements and catalogs.")); bool with_parents = false; options.AddOption('p', "parents", istring("make parent directories as needed"), with_parents); bool show_plugins = false; options.AddOption('P', "listplugins", istring("list the available plugins (protocols supported)"), show_plugins); int timeout = 20; options.AddOption('t', "timeout", istring("timeout in seconds (default 20)"), istring("seconds"), timeout); std::string conffile; options.AddOption('z', "conffile", istring("configuration file (default ~/.arc/client.conf)"), istring("filename"), conffile); std::string debug; options.AddOption('d', "debug", istring("FATAL, ERROR, WARNING, INFO, VERBOSE or DEBUG"), istring("debuglevel"), debug); bool version = false; options.AddOption('v', "version", istring("print version information"), version); std::list<std::string> params = options.Parse(argc, argv); if (version) { std::cout << Arc::IString("%s version %s", "arcrm", VERSION) << std::endl; return 0; } // If debug is specified as argument, it should be set before loading the configuration. if (!debug.empty()) Arc::Logger::getRootLogger().setThreshold(Arc::istring_to_level(debug)); logger.msg(Arc::VERBOSE, "Running command: %s", options.GetCommandWithArguments()); if (show_plugins) { std::list<Arc::ModuleDesc> modules; Arc::PluginsFactory pf(Arc::BaseConfig().MakeConfig(Arc::Config()).Parent()); pf.scan(Arc::FinderLoader::GetLibrariesList(), modules); Arc::PluginsFactory::FilterByKind("HED:DMC", modules); std::cout << Arc::IString("Protocol plugins available:") << std::endl; for (std::list<Arc::ModuleDesc>::iterator itMod = modules.begin(); itMod != modules.end(); ++itMod) { for (std::list<Arc::PluginDesc>::iterator itPlug = itMod->plugins.begin(); itPlug != itMod->plugins.end(); ++itPlug) { std::cout << " " << itPlug->name << " - " << itPlug->description << std::endl; } } return 0; } // credentials will be initialised later if necessary Arc::UserConfig usercfg(conffile, Arc::initializeCredentialsType::TryCredentials); if (!usercfg) { logger.msg(Arc::ERROR, "Failed configuration initialization"); return 1; } usercfg.UtilsDirPath(Arc::UserConfig::ARCUSERDIRECTORY()); usercfg.Timeout(timeout); if (debug.empty() && !usercfg.Verbosity().empty()) Arc::Logger::getRootLogger().setThreshold(Arc::istring_to_level(usercfg.Verbosity())); if (params.size() != 1) { logger.msg(Arc::ERROR, "Wrong number of parameters specified"); return 1; } // add a slash to the end if not present std::string url = params.front(); if (url[url.length()-1] != '/') url += '/'; if (!arcmkdir(url, usercfg, with_parents)) return 1; return 0; } int main(int argc, char **argv) { int xr = runmain(argc,argv); _exit(xr); return 0; }
31.891892
95
0.628305
maikenp
a475881ea7a61bde038340060a7786eb7384cbd2
318
cc
C++
tests/ManufacturerTest.cc
martind1111/wifi_pi_survey
9a28f47a6096df2f596b9e62bb984a0922712cf8
[ "MIT" ]
null
null
null
tests/ManufacturerTest.cc
martind1111/wifi_pi_survey
9a28f47a6096df2f596b9e62bb984a0922712cf8
[ "MIT" ]
null
null
null
tests/ManufacturerTest.cc
martind1111/wifi_pi_survey
9a28f47a6096df2f596b9e62bb984a0922712cf8
[ "MIT" ]
null
null
null
#include <gtest/gtest.h> #include <netinet/ether.h> #include "HardwareHelper.h" // Test the manufacturer API. TEST(ManufacturerTest, GetManufacturer) { ether_addr addr = { 0x00, 0x03, 0x93, 0x01, 0x02, 0x03 }; const char* manuf = HardwareHelper::GetManufacturer(&addr); EXPECT_STREQ(manuf, "Apple"); }
22.714286
63
0.704403
martind1111
a47c12d22aa31b210439a83ff6bcd30e874fa813
11,968
cpp
C++
lib/src/calibration/calibrationUtils.cpp
tlalexander/stitchEm
cdff821ad2c500703e6cb237ec61139fce7bf11c
[ "MIT" ]
182
2019-04-19T12:38:30.000Z
2022-03-20T16:48:20.000Z
lib/src/calibration/calibrationUtils.cpp
doymcc/stitchEm
20693a55fa522d7a196b92635e7a82df9917c2e2
[ "MIT" ]
107
2019-04-23T10:49:35.000Z
2022-03-02T18:12:28.000Z
lib/src/calibration/calibrationUtils.cpp
doymcc/stitchEm
20693a55fa522d7a196b92635e7a82df9917c2e2
[ "MIT" ]
59
2019-06-04T11:27:25.000Z
2022-03-17T23:49:49.000Z
// Copyright (c) 2012-2017 VideoStitch SAS // Copyright (c) 2018 stitchEm #include "calibrationUtils.hpp" #include <util/pngutil.hpp> #include <opencv2/imgproc.hpp> namespace VideoStitch { namespace Calibration { void drawMatches(const RigCvImages& rigInputImages, int idinput, videoreaderid_t idcam1, videoreaderid_t idcam2, const KPList& kplist1, const KPList& kplist2, const Core::ControlPointList& input, const int step /* used for the ordering of output files */, const std::string& description) { if (idinput < 0) { // call this function for all rig pictures for (int i = 0; i < (int)rigInputImages[idcam1].size(); i++) { drawMatches(rigInputImages, i, idcam1, idcam2, kplist1, kplist2, input, step, description); } } else { cv::Mat outimage; // set up match vector std::vector<cv::DMatch> matches1to2; std::vector<cv::KeyPoint> keypoints0, keypoints1; unsigned int counter = 0; for (auto& it : input) { matches1to2.push_back(cv::DMatch(counter, counter, (float)it.score)); keypoints0.push_back(cv::KeyPoint(float(it.x0), float(it.y0), 0.f)); keypoints1.push_back(cv::KeyPoint(float(it.x1), float(it.y1), 0.f)); ++counter; } // draw the matches cv::drawMatches(cv::Mat(*rigInputImages[idcam1][idinput].get()), keypoints0, cv::Mat(*rigInputImages[idcam2][idinput].get()), keypoints1, matches1to2, outimage); // overlay all keypoints cv::drawMatches(cv::Mat(*rigInputImages[idcam1][idinput].get()), kplist1, cv::Mat(*rigInputImages[idcam2][idinput].get()), kplist2, std::vector<cv::DMatch>(), outimage, cv::Scalar::all(-1), cv::Scalar::all(-1), std::vector<char>(), cv::DrawMatchesFlags::DRAW_OVER_OUTIMG); std::ostringstream imagefilename; imagefilename << "rig" << idinput << "matches" << idcam1 << "to" << idcam2 << "step" << step << description << ".png"; Util::PngReader writer; writer.writeBGRToFile(imagefilename.str().c_str(), outimage.cols, outimage.rows, outimage.data); Logger::get(Logger::Info) << "Writing " << imagefilename.str() << std::endl; } } void drawReprojectionErrors(const RigCvImages& rigInputImages, int idinput, videoreaderid_t idcam1, videoreaderid_t idcam2, const KPList& kplist1, const KPList& kplist2, const Core::ControlPointList& input, const int step, const std::string& description) { if (idinput < 0) { // call this function for all rig pictures for (size_t i = 0; i < rigInputImages[idcam1].size(); i++) { drawReprojectionErrors(rigInputImages, int(i), idcam1, idcam2, kplist1, kplist2, input, step, description); } } else { cv::Mat outimage; // draw all keypoints cv::drawMatches(cv::Mat(*rigInputImages[idcam1][idinput].get()), kplist1, cv::Mat(*rigInputImages[idcam2][idinput].get()), kplist2, std::vector<cv::DMatch>(), outimage, cv::Scalar::all(-1), cv::Scalar::all(-1), std::vector<char>()); // overlay the reprojections int cam1width = rigInputImages[idcam1][idinput]->cols; for (auto& it : input) { cv::Point p0(cvRound(it.x0), cvRound(it.y0 + .5)); cv::Point p1(cvRound(cam1width + it.x1 + .5), cvRound(it.y1 + .5)); cv::Point rp0(cvRound(cam1width + it.rx0 + .5), cvRound(it.ry0 + .5)); cv::Point rp1(cvRound(it.rx1 + .5), cvRound(it.ry1 + .5)); // use a different color for synthetic control points const cv::Scalar color0 = (it.artificial) ? cv::Scalar(255, 255, 0) : cv::Scalar(0, 0, 255); const cv::Scalar color1 = (it.artificial) ? cv::Scalar(255, 255, 0) : cv::Scalar(0, 255, 0); cv::circle(outimage, p0, 3, color0); cv::circle(outimage, p1, 3, color1); cv::line(outimage, p0, rp1, color0); cv::line(outimage, p1, rp0, color1); } std::ostringstream imagefilename; imagefilename << "rig" << idinput << "matches" << idcam1 << "to" << idcam2 << "step" << step << description << ".png"; Util::PngReader writer; writer.writeBGRToFile(imagefilename.str().c_str(), outimage.cols, outimage.rows, outimage.data); Logger::get(Logger::Info) << "Writing " << imagefilename.str() << std::endl; } } void reportProjectionStats(Core::ControlPointList& list, videoreaderid_t idcam1, videoreaderid_t idcam2, const std::string& description) { double mean0 = 0, meansq0 = 0, mean1 = 0, meansq1 = 0; size_t nkeypoints = list.size(); std::vector<double> distances0, distances1; for (auto& cp : list) { double distance0, distance1; double distancesq0, distancesq1; distancesq0 = (cp.x0 - cp.rx1) * (cp.x0 - cp.rx1) + (cp.y0 - cp.ry1) * (cp.y0 - cp.ry1); distancesq1 = (cp.x1 - cp.rx0) * (cp.x1 - cp.rx0) + (cp.y1 - cp.ry0) * (cp.y1 - cp.ry0); distance0 = std::sqrt(distancesq0); distance1 = std::sqrt(distancesq1); mean0 += distance0; meansq0 += distancesq0; mean1 += distance1; meansq1 += distancesq1; distances0.push_back(distance0); distances1.push_back(distance1); } if (nkeypoints) { mean0 /= double(nkeypoints); mean1 /= double(nkeypoints); meansq0 /= double(nkeypoints); meansq1 /= double(nkeypoints); // get median values std::nth_element(distances0.begin(), distances0.begin() + nkeypoints / 2, distances0.end()); std::nth_element(distances1.begin(), distances1.begin() + nkeypoints / 2, distances1.end()); Logger::get(Logger::Verbose) << description << ", camera " << idcam1 << " to " << idcam2 << ", " << nkeypoints << " points: " << mean1 << " (+/-" << ((nkeypoints > 1) ? std::sqrt((meansq1 - mean1 * mean1)) : 0.) << "), median " << *(distances0.begin() + nkeypoints / 2) << std::endl; Logger::get(Logger::Verbose) << description << ", camera " << idcam2 << " to " << idcam1 << ", " << nkeypoints << " points: " << mean0 << " (+/-" << ((nkeypoints > 1) ? std::sqrt((meansq0 - mean0 * mean0)) : 0.) << "), median " << *(distances1.begin() + nkeypoints / 2) << std::endl; } } void reportControlPointsStats(const Core::ControlPointList& list) { // find the number of pairs per frame, the number of points per input and the number of matched pairs per input pair std::map<videoreaderid_t, int> matched_per_frame; std::map<videoreaderid_t, int> matched_per_input; std::map<videoreaderid_t, std::map<videoreaderid_t, int>> matched_to_per_input; std::map<std::pair<videoreaderid_t, videoreaderid_t>, int> matched_per_pairs; for (auto& cp : list) { matched_per_frame[cp.frameNumber]++; matched_per_input[cp.index0]++; matched_per_input[cp.index1]++; matched_to_per_input[cp.index0][cp.index1]++; matched_to_per_input[cp.index1][cp.index0]++; matched_per_pairs[{cp.index0, cp.index1}]++; } Logger::get(Logger::Verbose) << "Calibration control points statistics:" << std::endl; // report the number of pairs per frame Logger::get(Logger::Verbose) << "Number of matched pairs per frame" << std::endl; for (auto& it : matched_per_frame) { Logger::get(Logger::Verbose) << " frame_number " << it.first << ": " << it.second << std::endl; } // report the number of control points and connections to other inputs per input Logger::get(Logger::Verbose) << "Number of control points to other inputs" << std::endl; for (auto& it : matched_per_input) { Logger::get(Logger::Verbose) << " input_index " << it.first << ": " << it.second << std::endl; for (auto& itto : matched_to_per_input[it.first]) { Logger::get(Logger::Verbose) << " matched_to_input_index " << itto.first << ": " << itto.second << std::endl; } } // report the number of matched pairs per input pair Logger::get(Logger::Verbose) << "Number of matched pairs per input pair" << std::endl; for (auto& it : matched_per_pairs) { Logger::get(Logger::Verbose) << " input pair (" << it.first.first << ',' << it.first.second << "): " << it.second << std::endl; } } void decimateSortedControlPoints(Core::ControlPointList& decimatedList, const Core::ControlPointList& sortedList, const int64_t inputWidth, const int64_t inputHeight, const double cellFactor) { double w = (double)inputWidth; double h = (double)inputHeight; double cellsize = cellFactor * std::sqrt(w * w + h * h); int gwidth = (int)std::ceil(w / cellsize); int gheight = (int)std::ceil(h / cellsize); std::vector<bool> occupancy(gwidth * gheight, false); decimatedList.clear(); int indexCurrentPoint = 0; for (const auto& it : sortedList) { Logger::get(Logger::Debug) << " currentPoint(" << indexCurrentPoint++ << "): "; Logger::get(Logger::Debug) << " " << it.x0 << "," << it.y0 << " " << it.x1 << "," << it.y1 << " score: " << it.score << " error: " << it.error << " frame: " << it.frameNumber << " indexes: " << it.index0 << "," << it.index1 << std::endl; double x = it.x0 / cellsize; double y = it.y0 / cellsize; int ix = (int)x; int iy = (int)y; Logger::get(Logger::Debug) << " x,y: " << x << "," << y << " ix,iy: " << ix << "," << iy << std::endl; if (occupancy[iy * gwidth + ix] == false) { Logger::get(Logger::Debug) << " Point added" << std::endl; occupancy[iy * gwidth + ix] = true; decimatedList.push_back(it); } else { Logger::get(Logger::Debug) << " Point NOT added" << std::endl; } } Logger::get(Logger::Debug) << "Decimated from " << sortedList.size() << " to " << decimatedList.size() << std::endl; } double getMeanReprojectionDistance(const Core::ControlPointList& list) { double sum = 0.; for (const auto& it : list) { sum += std::sqrt((it.x0 - it.rx1) * (it.x0 - it.rx1) + (it.y0 - it.ry1) * (it.y0 - it.ry1)) + std::sqrt((it.x1 - it.rx0) * (it.x1 - it.rx0) + (it.y1 - it.ry0) * (it.y1 - it.ry0)); } if (list.size()) { sum /= (2 * list.size()); } return sum; } Status fillPano(Core::PanoDefinition& pano, const std::vector<std::shared_ptr<Camera>>& cameras) { if (pano.numVideoInputs() != (int)cameras.size()) { return {Origin::CalibrationAlgorithm, ErrType::InvalidConfiguration, "Cannot fill in PanoDefinition, inconsistent number of video inputs and cameras"}; } auto videoInputs = pano.getVideoInputs(); for (size_t cameraid = 0; cameraid < cameras.size(); ++cameraid) { Core::InputDefinition& idef = videoInputs[cameraid]; if (idef.getWidth() != (int64_t)cameras[cameraid]->getWidth() || idef.getHeight() != (int64_t)cameras[cameraid]->getHeight()) { return {Origin::CalibrationAlgorithm, ErrType::InvalidConfiguration, "Cannot fill in PanoDefinition, at least one input and camera have different sizes"}; } idef.setUseMeterDistortion(true); idef.setFormat(cameras[cameraid]->getFormat()); size_t width, height; // handle the cropped area to fill in the geometry, for PTGui compatibility reasons if (idef.hasCroppedArea()) { width = idef.getCroppedWidth() + 2 * idef.getCropLeft(); height = idef.getCroppedHeight() + 2 * idef.getCropTop(); } else { width = idef.getWidth(); height = idef.getHeight(); } Core::GeometryDefinition g = idef.getGeometries().getConstantValue(); cameras[cameraid]->fillGeometry(g, (int)width, (int)height); Core::GeometryDefinitionCurve* gc = new Core::GeometryDefinitionCurve(g); idef.replaceGeometries(gc); } return Status::OK(); } } // namespace Calibration } // namespace VideoStitch
44.325926
120
0.611965
tlalexander
a47db8823f364cce2e1c8d336cf5ff156ff800bd
7,083
cpp
C++
src/sage/symbolic/ginac/fderivative.cpp
UCD4IDS/sage
43474c96d533fd396fe29fe0782d44dc7f5164f7
[ "BSL-1.0" ]
1,742
2015-01-04T07:06:13.000Z
2022-03-30T11:32:52.000Z
src/sage/symbolic/ginac/fderivative.cpp
UCD4IDS/sage
43474c96d533fd396fe29fe0782d44dc7f5164f7
[ "BSL-1.0" ]
66
2015-03-19T19:17:24.000Z
2022-03-16T11:59:30.000Z
src/sage/symbolic/ginac/fderivative.cpp
UCD4IDS/sage
43474c96d533fd396fe29fe0782d44dc7f5164f7
[ "BSL-1.0" ]
495
2015-01-10T10:23:18.000Z
2022-03-24T22:06:11.000Z
/** @file fderivative.cpp * * Implementation of abstract derivatives of functions. */ /* * GiNaC Copyright (C) 1999-2008 Johannes Gutenberg University Mainz, Germany * * 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 */ #define register #include <Python.h> #include "py_funcs.h" #include "fderivative.h" #include "operators.h" #include "archive.h" #include "utils.h" #include <iostream> namespace GiNaC { GINAC_IMPLEMENT_REGISTERED_CLASS_OPT(fderivative, function, print_func<print_context>(&fderivative::do_print). print_func<print_tree>(&fderivative::do_print_tree)) ////////// // default constructor ////////// fderivative::fderivative() { tinfo_key = &fderivative::tinfo_static; } ////////// // other constructors ////////// fderivative::fderivative(unsigned ser, unsigned param, const exvector & args) : function(ser, args) { parameter_set.insert(param); tinfo_key = &fderivative::tinfo_static; } fderivative::fderivative(unsigned ser, paramset params, const exvector & args) : function(ser, args), parameter_set(std::move(params)) { tinfo_key = &fderivative::tinfo_static; } fderivative::fderivative(unsigned ser, paramset params, std::unique_ptr<exvector> vp) : function(ser, std::move(vp)), parameter_set(std::move(params)) { tinfo_key = &fderivative::tinfo_static; } ////////// // archiving ////////// fderivative::fderivative(const archive_node &n, lst &sym_lst) : inherited(n, sym_lst) { unsigned i = 0; while (true) { unsigned u; if (n.find_unsigned("param", u, i)) parameter_set.insert(u); else break; ++i; } } void fderivative::archive(archive_node &n) const { inherited::archive(n); for (const auto & elem : parameter_set) n.add_unsigned("param", elem); } ////////// // functions overriding virtual functions from base classes ////////// void fderivative::print(const print_context & c, unsigned level) const { // class function overrides print(), but we don't want that basic::print(c, level); } void fderivative::do_print(const print_context & c, unsigned /*unused*/) const { //convert paramset to a python list PyObject* params = py_funcs.paramset_to_PyTuple(parameter_set); //convert arguments to a PyTuple of Expressions PyObject* args = py_funcs.exvector_to_PyTuple(seq); //check if latex mode //call python function std::string *sout; if (is_a<print_latex>(c)) { sout = py_funcs.py_latex_fderivative(serial, params, args); } else { sout = py_funcs.py_print_fderivative(serial, params, args); } if (sout == nullptr) { throw(std::runtime_error("fderivative::do_print(): python print function raised exception")); } c.s<<*sout; delete sout; Py_DECREF(params); Py_DECREF(args); /* c.s << "D["; paramset::const_iterator i = parameter_set.begin(), end = parameter_set.end(); --end; while (i != end) { c.s << *i++ << ","; } c.s << *i << "](" << registered_functions()[serial].name << ")"; printseq(c, "(", ',', ")", exprseq::precedence(), function::precedence()); */ } void fderivative::do_print_tree(const print_tree & c, unsigned level) const { c.s << std::string(level, ' ') << class_name() << " " << registered_functions()[serial].name << " @" << this << std::hex << ", hash=0x" << hashvalue << ", flags=0x" << flags << std::dec << ", nops=" << nops() << ", params="; auto i = parameter_set.begin(), iend = parameter_set.end(); --iend; while (i != iend) c.s << *i++ << ","; c.s << *i << std::endl; for (auto & elem : seq) elem.print(c, level + c.delta_indent); c.s << std::string(level + c.delta_indent, ' ') << "=====" << std::endl; } ex fderivative::eval(int level) const { if (level > 1) { // first evaluate children, then we will end up here again return fderivative(serial, parameter_set, evalchildren(level)); } // No parameters specified? Then return the function itself if (parameter_set.empty()) return function(serial, seq); // If the function in question actually has a derivative, return it if (registered_functions()[serial].has_derivative() && parameter_set.size() == 1) return pderivative(*(parameter_set.begin())); return this->hold(); } /** Numeric evaluation falls back to evaluation of arguments. * @see basic::evalf */ ex fderivative::evalf(int level, PyObject* parent) const { return basic::evalf(level, parent); } /** The series expansion of derivatives falls back to Taylor expansion. * @see basic::series */ ex fderivative::series(const relational & r, int order, unsigned options) const { return basic::series(r, order, options); } ex fderivative::thiscontainer(const exvector & v) const { return fderivative(serial, parameter_set, v); } ex fderivative::thiscontainer(std::unique_ptr<exvector> vp) const { return fderivative(serial, parameter_set, std::move(vp)); } /** Implementation of ex::diff() for derivatives. It applies the chain rule. * @see ex::diff */ ex fderivative::derivative(const symbol & s) const { ex result; for (size_t i=0; i<seq.size(); i++) { ex arg_diff = seq[i].diff(s); if (!arg_diff.is_zero()) { paramset ps = parameter_set; ps.insert(i); result += arg_diff * fderivative(serial, ps, seq); } } return result; } int fderivative::compare_same_type(const basic & other) const { GINAC_ASSERT(is_a<fderivative>(other)); const fderivative & o = static_cast<const fderivative &>(other); if (parameter_set != o.parameter_set) return parameter_set < o.parameter_set ? -1 : 1; return inherited::compare_same_type(o); } bool fderivative::is_equal_same_type(const basic & other) const { GINAC_ASSERT(is_a<fderivative>(other)); const fderivative & o = static_cast<const fderivative &>(other); if (parameter_set != o.parameter_set) return false; return inherited::is_equal_same_type(o); } bool fderivative::match_same_type(const basic & other) const { GINAC_ASSERT(is_a<fderivative>(other)); const fderivative & o = static_cast<const fderivative &>(other); return parameter_set == o.parameter_set && inherited::match_same_type(other); } long fderivative::calchash() const { long res = inherited::calchash(); long prev=0; // FNV hash with custom prime and initial value long h = 2166136285L; for (const auto & elem : parameter_set) { h = ( h * 2097287 ) ^ (elem-prev); prev = elem; } res=h^res; if (is_evaluated()) { setflag(status_flags::hash_calculated); hashvalue = res; } return res; } } // namespace GiNaC
27.034351
151
0.690527
UCD4IDS
a47f0a07dd3e298d314efa97b9c94980000b7248
10,653
cpp
C++
src/physics/bullet/bullet_physics_system.cpp
irisengine/iris
0deb12f5d00c67bf0dde1a702344a2cf73925db6
[ "BSL-1.0" ]
85
2021-10-16T14:58:23.000Z
2022-03-26T11:05:37.000Z
src/physics/bullet/bullet_physics_system.cpp
MaximumProgrammer/iris
cbc2f571bd8d485cdd04f903dcb867e699314682
[ "BSL-1.0" ]
null
null
null
src/physics/bullet/bullet_physics_system.cpp
MaximumProgrammer/iris
cbc2f571bd8d485cdd04f903dcb867e699314682
[ "BSL-1.0" ]
2
2021-10-17T16:57:13.000Z
2021-11-14T19:11:30.000Z
//////////////////////////////////////////////////////////////////////////////// // Distributed under the Boost Software License, Version 1.0. // // (See accompanying file LICENSE or copy at // // https://www.boost.org/LICENSE_1_0.txt) // //////////////////////////////////////////////////////////////////////////////// #include "physics/bullet/bullet_physics_system.h" #include <chrono> #include <map> #include <memory> #include <optional> #include <set> #include <vector> #include <BulletCollision/CollisionDispatch/btGhostObject.h> #include <BulletDynamics/Dynamics/btRigidBody.h> #include <LinearMath/btMotionState.h> #include <LinearMath/btQuaternion.h> #include <LinearMath/btTransform.h> #include <LinearMath/btVector3.h> #include <btBulletDynamicsCommon.h> #include "core/error_handling.h" #include "core/quaternion.h" #include "core/vector3.h" #include "graphics/render_entity.h" #include "log/log.h" #include "physics/basic_character_controller.h" #include "physics/bullet/bullet_box_collision_shape.h" #include "physics/bullet/bullet_capsule_collision_shape.h" #include "physics/bullet/bullet_collision_shape.h" #include "physics/bullet/bullet_rigid_body.h" #include "physics/bullet/debug_draw.h" #include "physics/character_controller.h" #include "physics/rigid_body.h" namespace { /** * Helper function to remove a rigid body from a bullet dynamics world. * * @param body * Body to remove. * * @param world * World to remove from. */ void remove_body_from_world(iris::RigidBody *body, btDynamicsWorld *world) { auto *bullet_body = static_cast<iris::BulletRigidBody *>(body); if (body->type() == iris::RigidBodyType::GHOST) { auto *bullet_ghost = static_cast<::btGhostObject *>(bullet_body->handle()); world->removeCollisionObject(bullet_ghost); } else { auto *bullet_rigid = static_cast<::btRigidBody *>(bullet_body->handle()); world->removeRigidBody(bullet_rigid); } } } namespace iris { /** * Saved information about a rigid body. Used in PhysicsState. */ struct RigidBodyState { RigidBodyState(const btTransform &transform, const btVector3 &linear_velocity, const btVector3 &angular_velocity) : transform(transform) , linear_velocity(linear_velocity) , angular_velocity(angular_velocity) { } btTransform transform; btVector3 linear_velocity; btVector3 angular_velocity; }; /** * Struct for saving the state of the physics simulation. It simply stores * RigidBodyState for all rigid bodies. Note that collision information is * *not* saved. */ struct BulletPhysicsState : public PhysicsState { ~BulletPhysicsState() override = default; std::map<btRigidBody *, RigidBodyState> bodies; }; BulletPhysicsSystem::BulletPhysicsSystem() : PhysicsSystem() , broadphase_(nullptr) , ghost_pair_callback_(nullptr) , collision_config_(nullptr) , collision_dispatcher_(nullptr) , solver_(nullptr) , world_(nullptr) , bodies_() , ignore_() , character_controllers_() , debug_draw_(nullptr) , collision_shapes_() { collision_config_ = std::make_unique<::btDefaultCollisionConfiguration>(); collision_dispatcher_ = std::make_unique<::btCollisionDispatcher>(collision_config_.get()); broadphase_ = std::make_unique<::btDbvtBroadphase>(); solver_ = std::make_unique<::btSequentialImpulseConstraintSolver>(); world_ = std::make_unique<::btDiscreteDynamicsWorld>( collision_dispatcher_.get(), broadphase_.get(), solver_.get(), collision_config_.get()); ghost_pair_callback_ = std::make_unique<::btGhostPairCallback>(); broadphase_->getOverlappingPairCache()->setInternalGhostPairCallback(ghost_pair_callback_.get()); world_->setGravity({0.0f, -10.0f, 0.0f}); debug_draw_ = nullptr; } BulletPhysicsSystem::~BulletPhysicsSystem() { try { for (const auto &body : bodies_) { remove_body_from_world(body.get(), world_.get()); } for (const auto &controller : character_controllers_) { remove_body_from_world(controller->rigid_body(), world_.get()); } } catch (...) { LOG_ERROR("physics_system", "exception caught during dtor"); } } void BulletPhysicsSystem::step(std::chrono::milliseconds time_step) { const auto ticks = static_cast<float>(time_step.count()); world_->stepSimulation(ticks / 1000.0f, 1); if (debug_draw_) { // tell bullet to draw debug world world_->debugDrawWorld(); // now we pass bullet debug information to our render system debug_draw_->render(); } } RigidBody *BulletPhysicsSystem::create_rigid_body( const Vector3 &position, CollisionShape *collision_shape, RigidBodyType type) { bodies_.emplace_back( std::make_unique<BulletRigidBody>(position, static_cast<BulletCollisionShape *>(collision_shape), type)); auto *body = static_cast<BulletRigidBody *>(bodies_.back().get()); if (body->type() == RigidBodyType::GHOST) { auto *bullet_ghost = static_cast<btGhostObject *>(body->handle()); world_->addCollisionObject(bullet_ghost); } else { auto *bullet_rigid = static_cast<btRigidBody *>(body->handle()); world_->addRigidBody(bullet_rigid); } return body; } CharacterController *BulletPhysicsSystem::create_character_controller() { character_controllers_.emplace_back(std::make_unique<BasicCharacterController>(this)); return character_controllers_.back().get(); } CollisionShape *BulletPhysicsSystem::create_box_collision_shape(const Vector3 &half_size) { collision_shapes_.emplace_back(std::make_unique<BulletBoxCollisionShape>(half_size)); return collision_shapes_.back().get(); } CollisionShape *BulletPhysicsSystem::create_capsule_collision_shape(float width, float height) { collision_shapes_.emplace_back(std::make_unique<BulletCapsuleCollisionShape>(width, height)); return collision_shapes_.back().get(); } void BulletPhysicsSystem::remove(RigidBody *body) { remove_body_from_world(body, world_.get()); bodies_.erase( std::remove_if( std::begin(bodies_), std::end(bodies_), [body](const auto &element) { return element.get() == body; }), std::end(bodies_)); } void BulletPhysicsSystem::remove(CharacterController *character) { remove_body_from_world(character->rigid_body(), world_.get()); character_controllers_.erase( std::remove_if( std::begin(character_controllers_), std::end(character_controllers_), [character](const auto &element) { return element.get() == character; }), std::end(character_controllers_)); } std::optional<std::tuple<RigidBody *, Vector3>> BulletPhysicsSystem::ray_cast( const Vector3 &origin, const Vector3 &direction) const { std::optional<std::tuple<RigidBody *, Vector3>> hit; // bullet does ray tracing between two vectors, so we create an end vector // some great distance away btVector3 from{origin.x, origin.y, origin.z}; const auto far_away = origin + (direction * 10000.0f); btVector3 to{far_away.x, far_away.y, far_away.z}; btCollisionWorld::AllHitsRayResultCallback callback{from, to}; world_->rayTest(from, to, callback); if (callback.hasHit()) { auto min = std::numeric_limits<float>::max(); btVector3 hit_position{}; const btRigidBody *body = nullptr; // find the closest hit object excluding any ignored objects for (auto i = 0; i < callback.m_collisionObjects.size(); ++i) { const auto distance = from.distance(callback.m_hitPointWorld[i]); if ((distance < min) && (ignore_.count(callback.m_collisionObjects[i]) == 0)) { min = distance; hit_position = callback.m_hitPointWorld[i]; body = static_cast<const btRigidBody *>(callback.m_collisionObjects[i]); } } if (body != nullptr) { hit = { static_cast<RigidBody *>(body->getUserPointer()), {hit_position.x(), hit_position.y(), hit_position.z()}}; } } return hit; } void BulletPhysicsSystem::ignore_in_raycast(RigidBody *body) { auto *bullet_body = static_cast<iris::BulletRigidBody *>(body); ignore_.emplace(bullet_body->handle()); } std::unique_ptr<PhysicsState> BulletPhysicsSystem::save() { auto state = std::make_unique<BulletPhysicsState>(); // save data for all rigid bodies for (const auto &body : bodies_) { auto *bullet_body = static_cast<iris::BulletRigidBody *>(body.get()); auto *bullet_rigid = static_cast<btRigidBody *>(bullet_body->handle()); state->bodies.try_emplace( bullet_rigid, bullet_rigid->getWorldTransform(), bullet_rigid->getLinearVelocity(), bullet_rigid->getAngularVelocity()); } // save data for all character controllers for (const auto &character : character_controllers_) { auto *bullet_body = static_cast<iris::BulletRigidBody *>(character->rigid_body()); auto *bullet_rigid = static_cast<btRigidBody *>(bullet_body->handle()); state->bodies.try_emplace( bullet_rigid, bullet_rigid->getWorldTransform(), bullet_rigid->getLinearVelocity(), bullet_rigid->getAngularVelocity()); } return state; } void BulletPhysicsSystem::load(const PhysicsState *state) { const auto *bullet_state = static_cast<const BulletPhysicsState *>(state); // restore state for each rigid body for (const auto &[bullet_body, body_state] : bullet_state->bodies) { bullet_body->clearForces(); bullet_body->setWorldTransform(body_state.transform); bullet_body->setCenterOfMassTransform(body_state.transform); bullet_body->setLinearVelocity(body_state.linear_velocity); bullet_body->setAngularVelocity(body_state.angular_velocity); } } void BulletPhysicsSystem::enable_debug_draw(RenderEntity *entity) { expect(!debug_draw_, "debug draw already enabled"); // create debug drawer, only draw wireframe as that's what we support debug_draw_ = std::make_unique<DebugDraw>(entity); debug_draw_->setDebugMode( btIDebugDraw::DBG_DrawWireframe | btIDebugDraw::DBG_DrawConstraints | btIDebugDraw::DBG_DrawConstraintLimits); world_->setDebugDrawer(debug_draw_.get()); } }
31.705357
118
0.673989
irisengine
a480d41967019f6eef6707899c47245c784ebc20
9,007
cc
C++
src/QuadraticCurvatureConstraint.cc
jcupitt/Deformable
e12c08bd744efb8c701dfdee2c363820b9562c81
[ "Apache-2.0" ]
5
2017-06-09T14:39:01.000Z
2021-04-28T00:35:39.000Z
src/QuadraticCurvatureConstraint.cc
jcupitt/Deformable
e12c08bd744efb8c701dfdee2c363820b9562c81
[ "Apache-2.0" ]
13
2016-01-11T17:25:26.000Z
2021-12-19T23:17:42.000Z
src/QuadraticCurvatureConstraint.cc
jcupitt/Deformable
e12c08bd744efb8c701dfdee2c363820b9562c81
[ "Apache-2.0" ]
7
2016-03-17T03:48:02.000Z
2020-10-09T10:15:45.000Z
/* * Medical Image Registration ToolKit (MIRTK) * * Copyright 2013-2015 Imperial College London * Copyright 2013-2015 Andreas Schuh * * 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 "mirtk/QuadraticCurvatureConstraint.h" #include "mirtk/Array.h" #include "mirtk/Memory.h" #include "mirtk/Vector.h" #include "mirtk/Matrix.h" #include "mirtk/Parallel.h" #include "mirtk/Profiling.h" #include "mirtk/VtkMath.h" #include "vtkPoints.h" #include "vtkDataArray.h" namespace mirtk { // Register energy term with object factory during static initialization mirtkAutoRegisterEnergyTermMacro(QuadraticCurvatureConstraint); // ============================================================================= // Auxiliaries // ============================================================================= namespace QuadraticCurvatureConstraintUtils { // ----------------------------------------------------------------------------- /// Evaluate error of quadratic fit in normal direction struct ComputeErrorOfQuadraticFit { typedef RegisteredPointSet::NodeNeighbors NodeNeighbors; vtkPoints *_Points; vtkDataArray *_Normals; const NodeNeighbors *_Neighbors; vtkDataArray *_ExternalMagnitude; vtkDataArray *_Residuals; void operator ()(const blocked_range<int> &ptIds) const { const double delta_sigma2 = .25 * .25; int numNbrPts; const int *nbrPtIds; double c[3], p[3], n[3], e[3], b, m, delta, w, wsum; Vector h; // Distances of neighbors to tangent plane Matrix r; // Squared radial distances of neighbors to central node for (int ptId = ptIds.begin(); ptId != ptIds.end(); ++ptId) { b = 0.; _Neighbors->GetConnectedPoints(ptId, numNbrPts, nbrPtIds); if (numNbrPts > 0) { _Points ->GetPoint(ptId, c); _Normals ->GetTuple(ptId, n); h.Initialize(numNbrPts); r.Initialize(numNbrPts, 2); for (int i = 0; i < numNbrPts; ++i) { _Points->GetPoint(nbrPtIds[i], p); vtkMath::Subtract(p, c, e); h(i) = vtkMath::Dot(e, n); r(i, 0) = vtkMath::Dot(e, e) - h(i) * h(i); r(i, 1) = 1.; } r.PseudoInvert(); if (_ExternalMagnitude) { wsum = 0.; m = abs(_ExternalMagnitude->GetComponent(ptId, 0)); for (int i = 0; i < numNbrPts; ++i) { delta = (abs(_ExternalMagnitude->GetComponent(nbrPtIds[i], 0)) - m) / (m + 1e-6); wsum += (w = exp(-.5 * delta * delta / delta_sigma2)); b += w * r(1, i) * h(i); } if (wsum > 0.) b /= wsum; } else { for (int i = 0; i < numNbrPts; ++i) { b += r(1, i) * h(i); } } } _Residuals->SetComponent(ptId, 0, b); } } }; // ----------------------------------------------------------------------------- /// Evaluate energy of quadratic curvature term struct Evaluate { vtkDataArray *_Residuals; double _Sum; Evaluate() : _Sum(.0) {} Evaluate(const Evaluate &other, split) : _Residuals(other._Residuals), _Sum(.0) {} void join(const Evaluate &other) { _Sum += other._Sum; } void operator ()(const blocked_range<int> &ptIds) { double b; for (int ptId = ptIds.begin(); ptId != ptIds.end(); ++ptId) { b = _Residuals->GetComponent(ptId, 0); _Sum += b * b; } } }; // ----------------------------------------------------------------------------- /// Evaluate gradient of quadratic curvature term (i.e., negative force) struct EvaluateGradient { typedef QuadraticCurvatureConstraint::GradientType GradientType; vtkDataArray *_Status; vtkDataArray *_Normals; vtkDataArray *_Residuals; GradientType *_Gradient; void operator ()(const blocked_range<int> &ptIds) const { double b, n[3]; for (int ptId = ptIds.begin(); ptId != ptIds.end(); ++ptId) { if (_Status && _Status->GetComponent(ptId, 0) == .0) continue; _Normals->GetTuple(ptId, n); b = _Residuals->GetComponent(ptId, 0); _Gradient[ptId] = -b * GradientType(n); } } }; } // namespace QuadraticCurvatureConstraintUtils using namespace QuadraticCurvatureConstraintUtils; // ============================================================================= // Construction/Destruction // ============================================================================= // ----------------------------------------------------------------------------- QuadraticCurvatureConstraint ::QuadraticCurvatureConstraint(const char *name, double weight) : SurfaceConstraint(name, weight) { // QuadraticCurvatureConstraint specific prefixes _ParameterPrefix.push_back("Quadratic surface curvature "); _ParameterPrefix.push_back("Quadratic surface mesh curvature "); _ParameterPrefix.push_back("Quadratic mesh curvature "); // Alternative CurvatureConstraint prefixes _ParameterPrefix.push_back("Surface curvature "); _ParameterPrefix.push_back("Surface bending "); _ParameterPrefix.push_back("Mesh curvature "); _ParameterPrefix.push_back("Mesh bending "); _ParameterPrefix.push_back("Surface mesh curvature "); _ParameterPrefix.push_back("Surface mesh bending "); } // ----------------------------------------------------------------------------- void QuadraticCurvatureConstraint ::CopyAttributes(const QuadraticCurvatureConstraint &other) { } // ----------------------------------------------------------------------------- QuadraticCurvatureConstraint ::QuadraticCurvatureConstraint(const QuadraticCurvatureConstraint &other) : SurfaceConstraint(other) { CopyAttributes(other); } // ----------------------------------------------------------------------------- QuadraticCurvatureConstraint &QuadraticCurvatureConstraint ::operator =(const QuadraticCurvatureConstraint &other) { if (this != &other) { SurfaceConstraint::operator =(other); CopyAttributes(other); } return *this; } // ----------------------------------------------------------------------------- QuadraticCurvatureConstraint::~QuadraticCurvatureConstraint() { } // ============================================================================= // Evaluation // ============================================================================= // ----------------------------------------------------------------------------- void QuadraticCurvatureConstraint::Initialize() { // Initialize base class SurfaceConstraint::Initialize(); // Add point data array for residuals of quadratic fit AddPointData("Residuals", 1, VTK_FLOAT); } // ----------------------------------------------------------------------------- void QuadraticCurvatureConstraint::Update(bool gradient) { if (_NumberOfPoints == 0) return; // Update base class SurfaceConstraint::Update(gradient); // Compute normal coefficients of quadratic fit MIRTK_START_TIMING(); ComputeErrorOfQuadraticFit fit; fit._Points = Points(); fit._Normals = Normals(); fit._Neighbors = Neighbors(); fit._ExternalMagnitude = ExternalMagnitude(); fit._Residuals = PointData("Residuals"); parallel_for(blocked_range<int>(0, _NumberOfPoints), fit); MIRTK_DEBUG_TIMING(3, "quadratic curvature fitting"); } // ----------------------------------------------------------------------------- double QuadraticCurvatureConstraint::Evaluate() { if (_NumberOfPoints == 0) return .0; MIRTK_START_TIMING(); QuadraticCurvatureConstraintUtils::Evaluate eval; eval._Residuals = PointData("Residuals"); parallel_reduce(blocked_range<int>(0, _NumberOfPoints), eval); MIRTK_DEBUG_TIMING(3, "evaluation of quadratic curvature penalty"); return eval._Sum / _NumberOfPoints; } // ----------------------------------------------------------------------------- void QuadraticCurvatureConstraint ::EvaluateGradient(double *gradient, double step, double weight) { if (_NumberOfPoints == 0) return; MIRTK_START_TIMING(); memset(_Gradient, 0, _NumberOfPoints * sizeof(GradientType)); QuadraticCurvatureConstraintUtils::EvaluateGradient eval; eval._Status = Status(); eval._Normals = Normals(); eval._Residuals = PointData("Residuals"); eval._Gradient = _Gradient; parallel_for(blocked_range<int>(0, _NumberOfPoints), eval); SurfaceConstraint::EvaluateGradient(gradient, step, 2. * weight / _NumberOfPoints); MIRTK_DEBUG_TIMING(3, "evaluation of quadratic curvature force"); } } // namespace mirtk
31.493007
93
0.57633
jcupitt
a4812e6719f610059b1bc6ebf19ab882044db088
8,095
cpp
C++
src/add-ons/input_server/filters/shortcut_catcher/KeyCommandMap.cpp
Kirishikesan/haiku
835565c55830f2dab01e6e332cc7e2d9c015b51e
[ "MIT" ]
1,338
2015-01-03T20:06:56.000Z
2022-03-26T13:49:54.000Z
src/add-ons/input_server/filters/shortcut_catcher/KeyCommandMap.cpp
Kirishikesan/haiku
835565c55830f2dab01e6e332cc7e2d9c015b51e
[ "MIT" ]
15
2015-01-17T22:19:32.000Z
2021-12-20T12:35:00.000Z
src/add-ons/input_server/filters/shortcut_catcher/KeyCommandMap.cpp
Kirishikesan/haiku
835565c55830f2dab01e6e332cc7e2d9c015b51e
[ "MIT" ]
350
2015-01-08T14:15:27.000Z
2022-03-21T18:14:35.000Z
/* * Copyright 1999-2014 Haiku, Inc. All rights reserved. * Distributed under the terms of the MIT License. * * Authors: * Jeremy Friesner * Jessica Hamilton, jessica.l.hamilton@gmail.com * John Scipione, jscipione@gmail.com */ #include "KeyCommandMap.h" #include <stdio.h> #include <Beep.h> #include <Entry.h> #include <File.h> #include <FindDirectory.h> #include <MessageFilter.h> #include <NodeMonitor.h> #include <OS.h> #include <Path.h> #include <PathFinder.h> #include <PathMonitor.h> #include <StringList.h> #include <WindowScreen.h> #include "BitFieldTesters.h" #include "CommandActuators.h" #include "ShortcutsFilterConstants.h" #define FILE_UPDATED 'fiUp' // #pragma mark - hks class hks { public: hks(int32 key, BitFieldTester* tester, CommandActuator* actuator, const BMessage& actuatorMessage) : fKey(key), fTester(tester), fActuator(actuator), fActuatorMessage(actuatorMessage) { } ~hks() { delete fActuator; delete fTester; } int32 GetKey() const { return fKey; } bool DoModifiersMatch(uint32 bits) const { return fTester->IsMatching(bits); } const BMessage& GetActuatorMessage() const { return fActuatorMessage; } CommandActuator* GetActuator() { return fActuator; } private: int32 fKey; BitFieldTester* fTester; CommandActuator* fActuator; const BMessage fActuatorMessage; }; // #pragma mark - KeyCommandMap KeyCommandMap::KeyCommandMap(const char* file) : BLooper("Shortcuts map watcher"), fSpecs(NULL) { fFileName = new char[strlen(file) + 1]; strcpy(fFileName, file); BEntry fileEntry(fFileName); BPrivate::BPathMonitor::StartWatching(fFileName, B_WATCH_STAT | B_WATCH_FILES_ONLY, this); if (fileEntry.InitCheck() == B_OK) { BMessage message(FILE_UPDATED); PostMessage(&message); } fPort = create_port(1, SHORTCUTS_CATCHER_PORT_NAME); _PutMessageToPort(); // advertise our BMessenger to the world } KeyCommandMap::~KeyCommandMap() { if (fPort >= 0) close_port(fPort); for (int32 i = fInjects.CountItems() - 1; i >= 0; i--) delete (BMessage*)fInjects.ItemAt(i); BPrivate::BPathMonitor::StopWatching(BMessenger(this, this)); // don't know if this is necessary, but it can't hurt _DeleteHKSList(fSpecs); delete[] fFileName; } void KeyCommandMap::MouseMessageReceived(const BMessage* message) { // Save the mouse state for later... fLastMouseMessage = *message; } filter_result KeyCommandMap::KeyEvent(const BMessage* keyMessage, BList* outList, const BMessenger& sendTo) { filter_result result = B_DISPATCH_MESSAGE; uint32 modifiers; int32 key; if (keyMessage->FindInt32("modifiers", (int32*)&modifiers) == B_OK && keyMessage->FindInt32("key", &key) == B_OK && fSpecs != NULL && fSyncSpecs.Lock()) { int32 count = fSpecs->CountItems(); for (int32 i = 0; i < count; i++) { hks* next = (hks*)fSpecs->ItemAt(i); if (key == next->GetKey() && next->DoModifiersMatch(modifiers)) { void* asyncData = NULL; result = next->GetActuator()->KeyEvent(keyMessage, outList, &asyncData, &fLastMouseMessage); if (asyncData != NULL) { BMessage newMessage(*keyMessage); newMessage.AddMessage("act", &next->GetActuatorMessage()); newMessage.AddPointer("adata", asyncData); sendTo.SendMessage(&newMessage); } } } fSyncSpecs.Unlock(); } return result; } void KeyCommandMap::DrainInjectedEvents(const BMessage* keyMessage, BList* outList, const BMessenger& sendTo) { BList temp; if (fSyncSpecs.Lock()) { temp = fInjects; fInjects.MakeEmpty(); fSyncSpecs.Unlock(); } int32 count = temp.CountItems(); for (int32 i = 0; i < count; i++) { BMessage* message = (BMessage*)temp.ItemAt(i); BArchivable* archive = instantiate_object(message); if (archive != NULL) { CommandActuator* actuator = dynamic_cast<CommandActuator*>(archive); if (actuator != NULL) { BMessage newMessage(*keyMessage); newMessage.what = B_KEY_DOWN; void* asyncData = NULL; actuator->KeyEvent(&newMessage, outList, &asyncData, &fLastMouseMessage); if (asyncData != NULL) { newMessage.AddMessage("act", message); newMessage.AddPointer("adata", asyncData); sendTo.SendMessage(&newMessage); } } delete archive; } delete message; } } void KeyCommandMap::MessageReceived(BMessage* message) { switch (message->what) { case EXECUTE_COMMAND: { BMessage actuatorMessage; if (message->FindMessage("act", &actuatorMessage) == B_OK) { if (fSyncSpecs.Lock()) { fInjects.AddItem(new BMessage(actuatorMessage)); fSyncSpecs.Unlock(); // This evil hack forces input_server to call Filter() on // us so we can process the injected event. BPoint where; status_t err = fLastMouseMessage.FindPoint("where", &where); if (err == B_OK) set_mouse_position((int32)where.x, (int32)where.y); } } break; } case REPLENISH_MESSENGER: _PutMessageToPort(); break; case B_PATH_MONITOR: { const char* path = ""; // only fall through for appropriate file if (!(message->FindString("path", &path) == B_OK && strcmp(path, fFileName) == 0)) { dev_t device; ino_t node; if (message->FindInt32("device", &device) != B_OK || message->FindInt64("node", &node) != B_OK || device != fNodeRef.device || node != fNodeRef.node) { break; } } } // fall-through case FILE_UPDATED: { BMessage fileMessage; BFile file(fFileName, B_READ_ONLY); BList* newList = new BList; BList* oldList = NULL; if (file.InitCheck() == B_OK && fileMessage.Unflatten(&file) == B_OK) { file.GetNodeRef(&fNodeRef); int32 i = 0; BMessage message; while (fileMessage.FindMessage("spec", i++, &message) == B_OK) { uint32 key; BMessage testerMessage; BMessage actuatorMessage; if (message.FindInt32("key", (int32*)&key) == B_OK && message.FindMessage("act", &actuatorMessage) == B_OK && message.FindMessage("modtester", &testerMessage) == B_OK) { // Leave handling of add-ons shortcuts to Tracker BString command; if (message.FindString("command", &command) == B_OK) { BStringList paths; BPathFinder::FindPaths( B_FIND_PATH_ADD_ONS_DIRECTORY, "Tracker", paths); bool foundAddOn = false; int32 count = paths.CountStrings(); for (int32 i = 0; i < count; i++) { if (command.StartsWith(paths.StringAt(i))) { foundAddOn = true; break; } } if (foundAddOn) continue; } BArchivable* archive = instantiate_object(&testerMessage); if (BitFieldTester* tester = dynamic_cast<BitFieldTester*>(archive)) { archive = instantiate_object(&actuatorMessage); CommandActuator* actuator = dynamic_cast<CommandActuator*>(archive); if (actuator != NULL) { newList->AddItem(new hks(key, tester, actuator, actuatorMessage)); } else { delete archive; delete tester; } } else delete archive; } } } else { fNodeRef.device = -1; fNodeRef.node = -1; } if (fSyncSpecs.Lock()) { // swap in the new list oldList = fSpecs; fSpecs = newList; fSyncSpecs.Unlock(); } else { // This should never happen... but clean up if it does. oldList = newList; } _DeleteHKSList(oldList); break; } } } // #pragma mark - KeyCommandMap private methods //! Deletes an HKS-filled BList and its contents. void KeyCommandMap::_DeleteHKSList(BList* list) { if (list == NULL) return; int32 count = list->CountItems(); for (int32 i = 0; i < count; i++) delete (hks*)list->ItemAt(i); delete list; } void KeyCommandMap::_PutMessageToPort() { if (fPort >= 0) { BMessage message; message.AddMessenger("target", this); char buffer[2048]; ssize_t size = message.FlattenedSize(); if (size <= (ssize_t)sizeof(buffer) && message.Flatten(buffer, size) == B_OK) { write_port_etc(fPort, 0, buffer, size, B_TIMEOUT, 250000); } } }
22.611732
78
0.657319
Kirishikesan
a48173204e89a9dc161c13550ce8b842efe3ae8c
2,821
hpp
C++
android-31/java/io/PrintStream.hpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
12
2020-03-26T02:38:56.000Z
2022-03-14T08:17:26.000Z
android-31/java/io/PrintStream.hpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
1
2021-01-27T06:07:45.000Z
2021-11-13T19:19:43.000Z
android-29/java/io/PrintStream.hpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
3
2021-02-02T12:34:55.000Z
2022-03-08T07:45:57.000Z
#pragma once #include "./FilterOutputStream.hpp" class JByteArray; class JCharArray; class JObjectArray; namespace java::io { class BufferedWriter; } namespace java::io { class File; } namespace java::io { class OutputStream; } namespace java::io { class OutputStreamWriter; } class JString; class JObject; class JString; namespace java::nio::charset { class Charset; } namespace java::util { class Formatter; } namespace java::util { class Locale; } namespace java::io { class PrintStream : public java::io::FilterOutputStream { public: // Fields // QJniObject forward template<typename ...Ts> explicit PrintStream(const char *className, const char *sig, Ts...agv) : java::io::FilterOutputStream(className, sig, std::forward<Ts>(agv)...) {} PrintStream(QJniObject obj); // Constructors PrintStream(java::io::File arg0); PrintStream(java::io::OutputStream arg0); PrintStream(JString arg0); PrintStream(java::io::File arg0, JString arg1); PrintStream(java::io::File arg0, java::nio::charset::Charset arg1); PrintStream(java::io::OutputStream arg0, jboolean arg1); PrintStream(JString arg0, JString arg1); PrintStream(JString arg0, java::nio::charset::Charset arg1); PrintStream(java::io::OutputStream arg0, jboolean arg1, JString arg2); PrintStream(java::io::OutputStream arg0, jboolean arg1, java::nio::charset::Charset arg2); // Methods java::io::PrintStream append(jchar arg0) const; java::io::PrintStream append(JString arg0) const; java::io::PrintStream append(JString arg0, jint arg1, jint arg2) const; jboolean checkError() const; void close() const; void flush() const; java::io::PrintStream format(JString arg0, JObjectArray arg1) const; java::io::PrintStream format(java::util::Locale arg0, JString arg1, JObjectArray arg2) const; void print(JCharArray arg0) const; void print(jboolean arg0) const; void print(jchar arg0) const; void print(jdouble arg0) const; void print(jfloat arg0) const; void print(jint arg0) const; void print(JObject arg0) const; void print(JString arg0) const; void print(jlong arg0) const; java::io::PrintStream printf(JString arg0, JObjectArray arg1) const; java::io::PrintStream printf(java::util::Locale arg0, JString arg1, JObjectArray arg2) const; void println() const; void println(JCharArray arg0) const; void println(jboolean arg0) const; void println(jchar arg0) const; void println(jdouble arg0) const; void println(jfloat arg0) const; void println(jint arg0) const; void println(JObject arg0) const; void println(JString arg0) const; void println(jlong arg0) const; void write(JByteArray arg0) const; void write(jint arg0) const; void write(JByteArray arg0, jint arg1, jint arg2) const; void writeBytes(JByteArray arg0) const; }; } // namespace java::io
28.21
173
0.734491
YJBeetle
a482833e6c7c6f5ca5abb6619aef6deb3578a372
7,794
cpp
C++
tsf/src/v20180326/model/MonitorOverview.cpp
sinjoywong/tencentcloud-sdk-cpp
1b931d20956a90b15a6720f924e5c69f8786f9f4
[ "Apache-2.0" ]
null
null
null
tsf/src/v20180326/model/MonitorOverview.cpp
sinjoywong/tencentcloud-sdk-cpp
1b931d20956a90b15a6720f924e5c69f8786f9f4
[ "Apache-2.0" ]
null
null
null
tsf/src/v20180326/model/MonitorOverview.cpp
sinjoywong/tencentcloud-sdk-cpp
1b931d20956a90b15a6720f924e5c69f8786f9f4
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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 <tencentcloud/tsf/v20180326/model/MonitorOverview.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Tsf::V20180326::Model; using namespace std; MonitorOverview::MonitorOverview() : m_invocationCountOfDayHasBeenSet(false), m_invocationCountHasBeenSet(false), m_errorCountOfDayHasBeenSet(false), m_errorCountHasBeenSet(false), m_successRatioOfDayHasBeenSet(false), m_successRatioHasBeenSet(false) { } CoreInternalOutcome MonitorOverview::Deserialize(const rapidjson::Value &value) { string requestId = ""; if (value.HasMember("InvocationCountOfDay") && !value["InvocationCountOfDay"].IsNull()) { if (!value["InvocationCountOfDay"].IsString()) { return CoreInternalOutcome(Error("response `MonitorOverview.InvocationCountOfDay` IsString=false incorrectly").SetRequestId(requestId)); } m_invocationCountOfDay = string(value["InvocationCountOfDay"].GetString()); m_invocationCountOfDayHasBeenSet = true; } if (value.HasMember("InvocationCount") && !value["InvocationCount"].IsNull()) { if (!value["InvocationCount"].IsString()) { return CoreInternalOutcome(Error("response `MonitorOverview.InvocationCount` IsString=false incorrectly").SetRequestId(requestId)); } m_invocationCount = string(value["InvocationCount"].GetString()); m_invocationCountHasBeenSet = true; } if (value.HasMember("ErrorCountOfDay") && !value["ErrorCountOfDay"].IsNull()) { if (!value["ErrorCountOfDay"].IsString()) { return CoreInternalOutcome(Error("response `MonitorOverview.ErrorCountOfDay` IsString=false incorrectly").SetRequestId(requestId)); } m_errorCountOfDay = string(value["ErrorCountOfDay"].GetString()); m_errorCountOfDayHasBeenSet = true; } if (value.HasMember("ErrorCount") && !value["ErrorCount"].IsNull()) { if (!value["ErrorCount"].IsString()) { return CoreInternalOutcome(Error("response `MonitorOverview.ErrorCount` IsString=false incorrectly").SetRequestId(requestId)); } m_errorCount = string(value["ErrorCount"].GetString()); m_errorCountHasBeenSet = true; } if (value.HasMember("SuccessRatioOfDay") && !value["SuccessRatioOfDay"].IsNull()) { if (!value["SuccessRatioOfDay"].IsString()) { return CoreInternalOutcome(Error("response `MonitorOverview.SuccessRatioOfDay` IsString=false incorrectly").SetRequestId(requestId)); } m_successRatioOfDay = string(value["SuccessRatioOfDay"].GetString()); m_successRatioOfDayHasBeenSet = true; } if (value.HasMember("SuccessRatio") && !value["SuccessRatio"].IsNull()) { if (!value["SuccessRatio"].IsString()) { return CoreInternalOutcome(Error("response `MonitorOverview.SuccessRatio` IsString=false incorrectly").SetRequestId(requestId)); } m_successRatio = string(value["SuccessRatio"].GetString()); m_successRatioHasBeenSet = true; } return CoreInternalOutcome(true); } void MonitorOverview::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const { if (m_invocationCountOfDayHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "InvocationCountOfDay"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_invocationCountOfDay.c_str(), allocator).Move(), allocator); } if (m_invocationCountHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "InvocationCount"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_invocationCount.c_str(), allocator).Move(), allocator); } if (m_errorCountOfDayHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "ErrorCountOfDay"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_errorCountOfDay.c_str(), allocator).Move(), allocator); } if (m_errorCountHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "ErrorCount"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_errorCount.c_str(), allocator).Move(), allocator); } if (m_successRatioOfDayHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "SuccessRatioOfDay"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_successRatioOfDay.c_str(), allocator).Move(), allocator); } if (m_successRatioHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "SuccessRatio"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_successRatio.c_str(), allocator).Move(), allocator); } } string MonitorOverview::GetInvocationCountOfDay() const { return m_invocationCountOfDay; } void MonitorOverview::SetInvocationCountOfDay(const string& _invocationCountOfDay) { m_invocationCountOfDay = _invocationCountOfDay; m_invocationCountOfDayHasBeenSet = true; } bool MonitorOverview::InvocationCountOfDayHasBeenSet() const { return m_invocationCountOfDayHasBeenSet; } string MonitorOverview::GetInvocationCount() const { return m_invocationCount; } void MonitorOverview::SetInvocationCount(const string& _invocationCount) { m_invocationCount = _invocationCount; m_invocationCountHasBeenSet = true; } bool MonitorOverview::InvocationCountHasBeenSet() const { return m_invocationCountHasBeenSet; } string MonitorOverview::GetErrorCountOfDay() const { return m_errorCountOfDay; } void MonitorOverview::SetErrorCountOfDay(const string& _errorCountOfDay) { m_errorCountOfDay = _errorCountOfDay; m_errorCountOfDayHasBeenSet = true; } bool MonitorOverview::ErrorCountOfDayHasBeenSet() const { return m_errorCountOfDayHasBeenSet; } string MonitorOverview::GetErrorCount() const { return m_errorCount; } void MonitorOverview::SetErrorCount(const string& _errorCount) { m_errorCount = _errorCount; m_errorCountHasBeenSet = true; } bool MonitorOverview::ErrorCountHasBeenSet() const { return m_errorCountHasBeenSet; } string MonitorOverview::GetSuccessRatioOfDay() const { return m_successRatioOfDay; } void MonitorOverview::SetSuccessRatioOfDay(const string& _successRatioOfDay) { m_successRatioOfDay = _successRatioOfDay; m_successRatioOfDayHasBeenSet = true; } bool MonitorOverview::SuccessRatioOfDayHasBeenSet() const { return m_successRatioOfDayHasBeenSet; } string MonitorOverview::GetSuccessRatio() const { return m_successRatio; } void MonitorOverview::SetSuccessRatio(const string& _successRatio) { m_successRatio = _successRatio; m_successRatioHasBeenSet = true; } bool MonitorOverview::SuccessRatioHasBeenSet() const { return m_successRatioHasBeenSet; }
30.928571
148
0.715679
sinjoywong
a4830eed7cacc0372727720736166d2bb897188c
13,846
cpp
C++
PlatformIO/esp32-r4ge-pro-prong/src/main.cpp
DigiTorus86/ESP32-R4ge-Pro
786127b87491dcdd2bbc928b1a68968a97038aac
[ "MIT" ]
1
2021-01-08T23:09:58.000Z
2021-01-08T23:09:58.000Z
PlatformIO/esp32-r4ge-pro-prong/src/main.cpp
DigiTorus86/ESP32-R4ge-Pro
786127b87491dcdd2bbc928b1a68968a97038aac
[ "MIT" ]
null
null
null
PlatformIO/esp32-r4ge-pro-prong/src/main.cpp
DigiTorus86/ESP32-R4ge-Pro
786127b87491dcdd2bbc928b1a68968a97038aac
[ "MIT" ]
2
2021-06-28T06:27:04.000Z
2022-01-11T12:57:55.000Z
/*************************************************** ESP32 R4ge Prong Requires: - ESP32 R4ge Pro Copyright (c) 2020 Paul Pagel This is free software; see the license.txt file for more information. There is no warranty; not even for merchantability or fitness for a particular purpose. *****************************************************/ #include "esp32_r4ge_pro.h" #include "driver/i2s.h" #include "freertos/queue.h" #include "Ball.h" #include "Player.h" #include "Title.h" #include "Bounce_wav.h" #include "Score_wav.h" #define LINE_COLOR ILI9341_GREEN #define BALL_COLOR ILI9341_WHITE #define PADDLE_COLOR ILI9341_YELLOW #define SCORE_COLOR ILI9341_WHITE #define TOP_LINE 20 #define NET_LINE 160 #define SCORE_DELAY_MS 1000 enum game_state_type { STATE_TITLE, STATE_START, STATE_PLAY, STATE_SCORE, STATE_PAUSE, STATE_GAME_OVER }; enum game_state_type game_state, prev_game_state; bool btn_pressed[8], btn_released[8]; bool btnA_pressed, btnB_pressed, btnX_pressed, btnY_pressed; bool btnUp_pressed, btnDown_pressed, btnLeft_pressed, btnRight_pressed; bool spkrLeft_on, spkrRight_on; bool btnTouch_pressed, btnTouch_released; int16_t joy_x_left, joy_y_left, joy_x_right, joy_y_right; uint32_t state_start_time; const uint8_t *audio_wav; bool audio_playing, audio_right, audio_left; uint16_t wav_length, sample_pos; int16_t ball_x, ball_y; double ball_x_dir, ball_y_dir; uint8_t num_players = 1; Player player[2]; Ball ball; // i2s configuration // See https://github.com/espressif/arduino-esp32/blob/master/tools/sdk/include/driver/driver/i2s.h int i2s_port_num = 0; i2s_config_t i2s_config = { .mode = (i2s_mode_t)(I2S_MODE_MASTER | I2S_MODE_TX), .sample_rate = 11025, .bits_per_sample = I2S_BITS_PER_SAMPLE_16BIT, // (i2s_bits_per_sample_t) 8 .channel_format = I2S_CHANNEL_FMT_RIGHT_LEFT, //I2S_CHANNEL_FMT_ONLY_RIGHT, I2S_CHANNEL_FMT_RIGHT_LEFT .communication_format = (i2s_comm_format_t)(I2S_COMM_FORMAT_I2S | I2S_COMM_FORMAT_I2S_MSB), // | I2S_COMM_FORMAT_PCM .intr_alloc_flags = ESP_INTR_FLAG_LEVEL1, // high interrupt priority. See esp_intr_alloc.h for more .dma_buf_count = 6, .dma_buf_len = 60, .use_apll = false, // I2S using APLL as main I2S clock, enable it to get accurate clock .tx_desc_auto_clear = 0, // helps in avoiding noise in case of data unavailability .fixed_mclk = 0 }; i2s_pin_config_t pin_config = { .bck_io_num = I2S_BCLK, // bit clock pin - to BCK pin on I2S DAC/PCM5102 .ws_io_num = I2S_LRCK, // left right select - to LCK pin on I2S DAC .data_out_num = I2S_DOUT, // DATA output pin - to DIN pin on I2S DAC .data_in_num = -1 // Not used }; #define BUFFER_SIZE 1024 #define SAMPLES_PER_BUFFER 512 // 2 bytes per sample (16bit x 2 channels for stereo) uint8_t audio_buffer[BUFFER_SIZE]; Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC, TFT_RST); void setup(); bool initAudioI2S(); void playAudio(const uint8_t *wav, uint16_t length, bool play_right, bool play_left); void updateAudio(); void playBounceWall(); void playBouncePaddle(bool play_right, bool play_left); void playScore(bool play_right, bool play_left); void drawTitle(); void startGame(int players); void drawScore(); void drawPause(); void erasePause(); void drawGameOver(); void checkButtonPresses(); void checkJoysticks(); void loop(void) ; void handleTitle(); void handleStart(); void handlePlay(); void handlePause(); void handleGameOver(); void handleScore(); /* * Set up the board */ void setup() { Serial.begin(115200); Serial.println("ESP32 R4ge Prong"); delay(100); // Set up shift register pins pinMode(SR_PL, OUTPUT); pinMode(SR_CP, OUTPUT); pinMode(SR_Q7, INPUT); // Set up the joysticks pinMode(JOYX_L, INPUT); pinMode(JOYY_L, INPUT); pinMode(JOYX_R, INPUT); pinMode(JOYY_R, INPUT); // Set up the TFT backlight brightness control pinMode(TFT_LED, OUTPUT); digitalWrite(TFT_LED, LOW); delay(100); // Set up the TFT tft.begin(); tft.setRotation(SCREEN_ROT); tft.fillScreen(ILI9341_BLACK); tft.setTextColor(ILI9341_WHITE); drawTitle(); game_state = STATE_TITLE; } /* * Initialize the I2S audio output */ bool initAudioI2S() { esp_err_t err; err = i2s_driver_install((i2s_port_t)i2s_port_num, &i2s_config, 0, NULL); if (err != ESP_OK) { Serial.print("I2S driver install fail: "); Serial.println(err); return false; } i2s_set_pin((i2s_port_t)i2s_port_num, &pin_config); i2s_set_clk((i2s_port_t)i2s_port_num, 11025, I2S_BITS_PER_SAMPLE_16BIT, I2S_CHANNEL_STEREO); return true; } /* * Plays the audio sample through either or both speaker channels. * Does not return until sample is done playing. */ void playAudio(const uint8_t *wav, uint16_t length, bool play_right, bool play_left) { if (!play_right && !play_left) return; // not playing anything, so bail audio_playing = initAudioI2S(); audio_wav = wav; wav_length = length; audio_right = play_right; audio_left = play_left; sample_pos = 40; // skip RIFF header, could detect & skip(?) updateAudio(); } void updateAudio() { int16_t buff_pos; uint8_t temp, temp_msb; size_t bytes_out; if (!audio_playing) return; // Fill I2S transfer audio buffer from sample buffer for (int i = 0; i < SAMPLES_PER_BUFFER - 1; i+= 2) { if (sample_pos + i < wav_length - 1) { temp = audio_wav[sample_pos + i]; temp_msb = audio_wav[sample_pos + i + 1]; } else { temp = 0; temp_msb = 0; } buff_pos = i * 2; // right + left channel samples // If using I2S_CHANNEL_FMT_ONLY_RIGHT //audio_buffer[buff_pos] = temp; //audio_buffer[buff_pos + 1] = (uint8_t)temp_msb; if (audio_left) // put sound data into right channel { audio_buffer[buff_pos] = temp; audio_buffer[buff_pos + 1] = (uint8_t)temp_msb; } else { audio_buffer[buff_pos] = 0; audio_buffer[buff_pos + 1] = 0; } if (audio_right) // put sound data into left channel { audio_buffer[buff_pos + 2] = (uint8_t)temp & 0xff; audio_buffer[buff_pos + 3] = (uint8_t)temp_msb; } else { audio_buffer[buff_pos + 2] = 0; audio_buffer[buff_pos + 3] = 0; } } // Write data to I2S DMA buffer. Blocking call, last parameter = ticks to wait or portMAX_DELAY for no timeout i2s_write((i2s_port_t)i2s_port_num, (const char *)&audio_buffer, sizeof(audio_buffer), &bytes_out, 100); if (bytes_out != sizeof(audio_buffer)) Serial.println("I2S write timeout"); sample_pos += SAMPLES_PER_BUFFER; if (sample_pos >= wav_length - 1) { // Stop audio playback i2s_driver_uninstall((i2s_port_t)i2s_port_num); audio_playing = false; } } void playBounceWall() { playAudio(bounce3_wav, BOUNCE_LENGTH, true, true); } void playBouncePaddle(bool play_right, bool play_left) { playAudio(bounce1_wav, BOUNCE_LENGTH, play_right, play_left); } void playScore(bool play_right, bool play_left) { playAudio(score_wav, BOUNCE_LENGTH, play_right, play_left); } /* * Draws the game title/splash screen */ void drawTitle() { tft.fillScreen(ILI9341_BLACK); tft.drawRGBBitmap(40, 60, (uint16_t *)prong_title, 240, 78); tft.setTextSize(2); tft.setTextColor(ILI9341_DARKGREY); tft.setCursor(80, 180); tft.print("[X] 1 Player"); tft.setCursor(80, 200); tft.print("[Y] 2 Player"); } /* * Initializes the game variables and draws the main gameplay screen */ void startGame(int players) { tft.fillScreen(ILI9341_BLACK); tft.drawLine(0, TOP_LINE, SCREEN_WD, TOP_LINE, LINE_COLOR); for (int i = TOP_LINE; i < SCREEN_HT; i+= 8) { tft.drawLine(NET_LINE, i, NET_LINE, i+3, LINE_COLOR); } ball.setLimits(TOP_LINE + 1, SCREEN_HT - 1); player[0].setLimits(TOP_LINE + 1, SCREEN_HT - 1); player[1].setLimits(TOP_LINE + 1, SCREEN_HT - 1); player[0].begin(1, PADDLE_COLOR, (bool)(players > 0)); player[1].begin(2, PADDLE_COLOR, (bool)(players > 1)); drawScore(); } /* * Draw the score for both players */ void drawScore() { uint16_t score = player[0].getScore(); tft.setTextSize(2); tft.setTextColor(ILI9341_WHITE, ILI9341_BLACK); tft.setCursor(60, 0); tft.print(score); score = player[1].getScore(); tft.setCursor(230, 0); tft.print(score); } /* * Draws a Paused message on the screen */ void drawPause() { //tft.fillRect(124, 0, 112, 20, ILI9341_BLACK); tft.setTextSize(2); tft.setTextColor(ILI9341_RED); tft.setCursor(124, 0); tft.print("PAUSED"); delay(200); game_state = STATE_PAUSE; } /* * Erases the Paused message */ void erasePause() { tft.fillRect(124, 0, 112, 20, ILI9341_BLACK); delay(200); game_state = STATE_PLAY; } /* * Draws the Game Over screen */ void drawGameOver() { tft.fillRect (80, 70, 160, 55, ILI9341_BLACK); // clear msg area tft.drawRect (80, 70, 160, 55, ILI9341_YELLOW); // border tft.setTextSize(2); tft.setTextColor(ILI9341_WHITE); tft.setCursor(105, 80); tft.print("GAME OVER"); tft.setTextSize(1); tft.setTextColor(ILI9341_WHITE); tft.setCursor(105, 110); tft.print("PRESS [Y] TO START"); } /* * Check button presses connected to the shift register */ void checkButtonPresses() { bool pressed = false; digitalWrite(SR_CP, LOW); digitalWrite(SR_PL, LOW); delay(5); digitalWrite(SR_PL, HIGH); for(uint8_t i = 0; i < 8; i++) { pressed = (digitalRead(SR_Q7) == LOW ? 1: 0);// read the state of the SO: btn_released[i] = !pressed && btn_pressed[i]; btn_pressed[i] = pressed; // Shift the next button pin value into the serial data out digitalWrite(SR_CP, LOW); delay(1); digitalWrite(SR_CP, HIGH); delay(1); //Serial.print(i); Serial.print(": "); Serial.println(btn_pressed[i]); } } /* * Check the analog joystick values */ void checkJoysticks() { // Joystick result value will be between -15 and +15 //joy_x_left = (analogRead(JOYX_L) >> 7) - JOY_5BIT_CTR; if (btn_pressed[BTN_UP]) { joy_y_left = 6; } else if (btn_pressed[BTN_DOWN]) { joy_y_left = -6; } else { joy_y_left = (analogRead(JOYY_L) >> 7) - JOY_5BIT_CTR; } if (btn_pressed[BTN_Y]) { joy_y_right = 6; } else if (btn_pressed[BTN_A]) { joy_y_right = -6; } else { joy_y_right = (analogRead(JOYY_R) >> 7) - JOY_5BIT_CTR; } } /* * Main program loop. Called continuously after setup. */ void loop(void) { checkButtonPresses(); checkJoysticks(); if (prev_game_state != game_state) { state_start_time = millis(); // track when the state change started // Do initial screen drawing for new game state switch(game_state) { case STATE_TITLE: drawTitle(); break; case STATE_START: startGame(num_players); break; case STATE_PLAY: if (ball.isDead()) ball.begin(BALL_COLOR); break; case STATE_SCORE: drawScore(); ball.erase(&tft); break; case STATE_PAUSE: drawPause(); break; case STATE_GAME_OVER: drawGameOver(); break; } } prev_game_state = game_state; // Update the screen based on the game state switch(game_state) { case STATE_TITLE: handleTitle(); break; case STATE_START: handleStart(); break; case STATE_PLAY: handlePlay(); break; case STATE_SCORE: handleScore(); break; case STATE_PAUSE: handlePause(); break; case STATE_GAME_OVER: handleGameOver(); break; } updateAudio(); //delay(1); } /* * Handles the STATE_TITLE game state logic */ void handleTitle() { if (btn_released[BTN_X]) { num_players = 1; game_state = STATE_START; return; } if (btn_released[BTN_Y]) { num_players = 2; game_state = STATE_START; return; } } /* * Handles the STATE_START game state logic */ void handleStart() { game_state = STATE_PLAY; } /* * Handles the STATE_PLAYING game state logic */ void handlePlay() { // player controls logic if (btn_released[BTN_X]) { drawPause(); return; } // Do update logic and checks update_result_type result; result = ball.update(); switch(result) { case RESULT_BOUNCE: playBounceWall(); break; case RESULT_SCORE1: player[0].changeScore(1); playScore(false, true); game_state = STATE_SCORE; break; case RESULT_SCORE2: player[1].changeScore(1); playScore(true, false); game_state = STATE_SCORE; break; default: break; } if (game_state != STATE_PLAY) return; // Redraw net - TODO: still gaps too long int16_t ball_y = ball.getY() - 4; for (int i = ball_y; i < ball_y + 4; i++) { if (i & 0x0004) tft.drawPixel(NET_LINE, i, LINE_COLOR); } result = player[0].update(joy_y_left, &ball); if (result == RESULT_BOUNCE) playBouncePaddle(true, false); result = player[1].update(joy_y_right, &ball); if (result == RESULT_BOUNCE) playBouncePaddle(false, true); // Draw results to the screen ball.draw(&tft); player[0].draw(&tft); player[1].draw(&tft); } /* * Handles the STATE_PAUSED game state logic */ void handlePause() { if (btn_released[BTN_X]) { erasePause(); } } /* * Handles the STATE_GAME_OVER game state logic */ void handleGameOver() { if (btn_released[BTN_Y]) { drawTitle(); } } /* * Handles the STATE_SCORE game state logic */ void handleScore() { if (millis() - state_start_time >= SCORE_DELAY_MS) { game_state = STATE_PLAY; return; } player[0].update(joy_y_left, &ball); player[1].update(joy_y_right, &ball); player[0].draw(&tft); player[1].draw(&tft); }
22.296296
123
0.664524
DigiTorus86
a4872d9a660d3f47f1c639a2a71dd46c6679986c
5,289
cpp
C++
evolutionary_prototype(final code)/collision_controller.cpp
egeorgiev1/UR10_motion_planner
e51228f88626eb4be8d9d98c25b37050dc9c8b31
[ "Apache-2.0" ]
1
2021-11-17T01:02:05.000Z
2021-11-17T01:02:05.000Z
evolutionary_prototype(final code)/collision_controller.cpp
egeorgiev1/UR10_motion_planner
e51228f88626eb4be8d9d98c25b37050dc9c8b31
[ "Apache-2.0" ]
null
null
null
evolutionary_prototype(final code)/collision_controller.cpp
egeorgiev1/UR10_motion_planner
e51228f88626eb4be8d9d98c25b37050dc9c8b31
[ "Apache-2.0" ]
null
null
null
#include "test_fcl_utility.h" #include "collision_controller.h" #include <iostream> using namespace std; CollisionController::CollisionController( CollisionModel* robot_collision_model, PointCloudView* point_cloud_view, fcl::BroadPhaseCollisionManager<double>* scene_collision_manager ) : _robot_collision_model(robot_collision_model), _point_cloud_view(point_cloud_view), _scene_collision_manager(scene_collision_manager) {} void CollisionController::schedule_collision_detection() { _must_perform_collision_detection = true; } void CollisionController::frameRendered(const Ogre::FrameEvent& evt) { if(_must_perform_collision_detection) { _must_perform_collision_detection = false; // Perform collision detection here, display contact points (TODO: BE ABLE TO DISABLE THIS!!!) // NOTE: FCL works so that a single CollisionData object could be used to // accummulate the results from multiple collision detection tasks!!! fcl::test::CollisionData<double> self_collision_data; self_collision_data.request.enable_contact = true; self_collision_data.request.num_max_contacts = 10'000; fcl::test::CollisionData<double> scene_collision_data; scene_collision_data.request.enable_contact = true; scene_collision_data.request.num_max_contacts = 10'000; // TEST(To separate in another class(must not be done for self-collision detection???)) fcl::test::DistanceData<double> scene_distance_data; scene_distance_data.request.enable_nearest_points = true; auto robot_collision_manager = _robot_collision_model->get_broadphase_managers(); cout << "Number of managed robot collision meshes" << robot_collision_manager->size() << endl; cout << "Number of managed scene collision meshes" << _scene_collision_manager->size() << endl; robot_collision_manager->collide( robot_collision_manager, &self_collision_data, CollisionModel::self_collision_function<double> //fcl::test::defaultCollisionFunction<double> ); cout << "I CRASH AFTER THIS" << endl; robot_collision_manager->collide( _scene_collision_manager, &scene_collision_data, CollisionModel::scene_collision_function<double> // FOR LOGGING!!! //fcl::test::defaultCollisionFunction<double> ); cout << "I CRASH AFTER THIS" << endl; // TEST(To separate in another class(must not be done for self-collision detection???)) robot_collision_manager->distance( _scene_collision_manager, &scene_distance_data, //CollisionModel::scene_collision_function<double> // FOR LOGGING!!! fcl::test::defaultDistanceFunction<double> ); cout << "I CRASH AFTER THIS" << endl; cout << endl; cout << "Self-collision points: " << self_collision_data.result.numContacts() << endl; cout << "Robot-scene points: " << scene_collision_data.result.numContacts() << endl; cout << "Min-distance from scene: " << scene_distance_data.result.min_distance << endl; // TEST cout << endl; // Contact points aggregation points_array_t contact_points; // TEST(add to result contacts) contact_points.push_back( {{ scene_distance_data.result.nearest_points[0].x(), scene_distance_data.result.nearest_points[0].y(), scene_distance_data.result.nearest_points[0].z() }} ); contact_points.push_back( {{ scene_distance_data.result.nearest_points[1].x(), scene_distance_data.result.nearest_points[1].y(), scene_distance_data.result.nearest_points[1].z() }} ); // SAMPLING_BOUNDS_DEBUG_OUTPUT // TEST - ORIGINAL // {{ 0.6, 0, 0 }}, // {{ -0.6, 0.6, 0.6 }}, // TEST - TRANSFORMED FOR OGRE3D COORDINATE SYSTEM // {{ -0.6, 0, 0 }}, // {{ 0.6, 0.6, 0.6 }}, // contact_points.push_back( // {{ -0.6, 0, 0 }} // ); // contact_points.push_back( // {{ 0.6, 0.6, 0.6 }} // ); // Add self-collision contact points for(size_t i = 0; i < self_collision_data.result.numContacts(); i++) { contact_points.push_back( {{ self_collision_data.result.getContact(i).pos.x(), self_collision_data.result.getContact(i).pos.y(), self_collision_data.result.getContact(i).pos.z() }} ); } // Add robot-scene collision contact points for(size_t i = 0; i < scene_collision_data.result.numContacts(); i++) { contact_points.push_back( {{ scene_collision_data.result.getContact(i).pos.x(), scene_collision_data.result.getContact(i).pos.y(), scene_collision_data.result.getContact(i).pos.z() }} ); } // Show contact points _point_cloud_view->set_points(contact_points); } }
37.778571
103
0.619966
egeorgiev1
a4878ef2f2de4abfd9cb382340719f9b4f1d0ba4
805
cpp
C++
Queue/InbuiltQueue.cpp
sohamnandi77/Cpp-Data-Structures-And-Algorithm
f29a14760964103a5b58cfff925cd8f7ed5aa6c1
[ "MIT" ]
2
2021-05-21T17:10:02.000Z
2021-05-29T05:13:06.000Z
Queue/InbuiltQueue.cpp
sohamnandi77/Cpp-Data-Structures-And-Algorithm
f29a14760964103a5b58cfff925cd8f7ed5aa6c1
[ "MIT" ]
null
null
null
Queue/InbuiltQueue.cpp
sohamnandi77/Cpp-Data-Structures-And-Algorithm
f29a14760964103a5b58cfff925cd8f7ed5aa6c1
[ "MIT" ]
null
null
null
#include <iostream> #include <queue> using namespace std; // # Application of Queue // -> Single Resource and Multiple Consumers // -> Synchronization between slow and fast devices // -> In Operating System (Semaphores, FCFS Sheduling,Spooling, buffers for devices like Keyboard) // -> In computer Networks (Routers/Switches and mail Queues) // -> Variations: Deque, Priority Queue(Heap),Doubly Ended Priority Queue int main() { queue<int> q; q.push(10); q.push(20); q.push(30); q.push(40); q.push(50); q.push(60); cout << q.front() << endl; q.pop(); q.pop(); q.pop(); cout << q.size() << endl; cout << q.empty() << endl; // print the queue while (!q.empty()) { cout << q.front() << endl; q.pop(); } return 0; }
21.184211
98
0.590062
sohamnandi77
a493ba13372e556f1a83390d71e5ef075334c55c
4,846
cxx
C++
plugins/cg_fltk/fltk_layout_group.cxx
MarioHenze/cgv
bacb2d270b1eecbea1e933b8caad8d7e11d807c2
[ "BSD-3-Clause" ]
11
2017-09-30T12:21:55.000Z
2021-04-29T21:31:57.000Z
plugins/cg_fltk/fltk_layout_group.cxx
MarioHenze/cgv
bacb2d270b1eecbea1e933b8caad8d7e11d807c2
[ "BSD-3-Clause" ]
2
2017-07-11T11:20:08.000Z
2018-03-27T12:09:02.000Z
plugins/cg_fltk/fltk_layout_group.cxx
MarioHenze/cgv
bacb2d270b1eecbea1e933b8caad8d7e11d807c2
[ "BSD-3-Clause" ]
24
2018-03-27T11:46:16.000Z
2021-05-01T20:28:34.000Z
#include "fltk_layout_group.h" #include <cgv/utils/scan.h> #include <cgv/gui/provider.h> using namespace cgv::base; using namespace cgv::gui; #ifdef WIN32 #pragma warning (disable:4311) #endif #include <fltk/Group.h> #include <fltk/draw.h> #include <fltk/Cursor.h> #include <fltk/events.h> #include <fltk/ScrollGroup.h> #include <fltk/PackedGroup.h> #include <fltk/Button.h> #ifdef WIN32 #pragma warning (default:4311) #endif fltk_layout_group::fltk_layout_group(int x, int y, int w, int h, const std::string& _name) : cgv::gui::gui_group(_name), CG<fltk::Group>(x, y, w, h, "") { label(get_name().c_str()); user_data(static_cast<cgv::base::base*>(this)); } /// only uses the implementation of fltk_base std::string fltk_layout_group::get_property_declarations() { std::string decl = fltk_base::get_property_declarations(); decl+=";layout:string;border-style:string;"; if (formatter) decl+=formatter->get_property_declarations(); return decl; } /// abstract interface for the setter bool fltk_layout_group::set_void(const std::string& property, const std::string& value_type, const void* value_ptr) { if (property == "layout") { get_variant(formatter_name, value_type, value_ptr); if (formatter_name == "table") formatter = new layout_table(cgv::base::group_ptr(this)); if (formatter_name == "inline") formatter = new layout_inline(cgv::base::group_ptr(this)); } else if (property == "border-style") { get_variant(border_style, value_type, value_ptr); update_box_type(); redraw(); } else if (formatter && formatter->set_void(property, value_type, value_ptr)) return true; else { fltk_base::set_void(this, this, property, value_type, value_ptr); } return true; } /// abstract interface for the getter bool fltk_layout_group::get_void(const std::string& property, const std::string& value_type, void* value_ptr) { if (property == "layout") set_variant(formatter_name, value_type, value_ptr); else if (property == "border-style") set_variant(border_style, value_type, value_ptr); else if (formatter && formatter->get_void(property, value_type, value_ptr)) return true; else { // if (property == "label") { // std::cout << "layout label" << std::endl; // } return fltk_base::get_void(this, this, property, value_type, value_ptr); } return true; } void fltk_layout_group::update_box_type() { if (border_style == "sunken") box(fltk::DOWN_BOX); else if (border_style == "lifted") box(fltk::UP_BOX); else if (border_style == "thinsunken") box(fltk::THIN_DOWN_BOX); else if (border_style == "thinlifted") box(fltk::THIN_UP_BOX); else if (border_style == "framed") box(fltk::BORDER_BOX); // more types can be added using: // http://www.fltk.org/doc-2.0/html/group__boxes.html } /// return a fltk::Widget pointer that can be cast into a fltk::Group void* fltk_layout_group::get_user_data() const { return (fltk::Widget*)(this); } /// put default sizes into dimension fields and set inner_group to be active void fltk_layout_group::prepare_new_element(cgv::gui::gui_group_ptr ggp, int& x, int& y, int& w, int& h) { x = 0; y = 0; w = 200; h = 20; begin(); } /// overload to trigger initialization of alignment void fltk_layout_group::remove_all_children(cgv::gui::gui_group_ptr ggp) { fltk_gui_group::remove_all_children(ggp); } /// align last element and add element to group void fltk_layout_group::finalize_new_element(cgv::gui::gui_group_ptr ggp, const std::string& _align, cgv::base::base_ptr element) { end(); // save the alignment information element->set<std::string>("alignment", _align); // the default width and height element->set<int>("dw", element->get<int>("w")); element->set<int>("dh", element->get<int>("h")); cgv::base::group::append_child(element); } void fltk_layout_group::register_object(base_ptr object, const std::string& options) { if (!cgv::utils::is_element(get_name(),options)) return; provider* p = object->get_interface<cgv::gui::provider>(); if (p && get_provider_parent(p).empty()) { set_provider_parent(p,gui_group_ptr(this)); p->create_gui(); } } /// void fltk_layout_group::unregister_object(cgv::base::base_ptr object, const std::string& options) { if (!options.empty() && !cgv::utils::is_element(get_name(),options)) return; provider* p = object->get_interface<cgv::gui::provider>(); if (p && get_provider_parent(p) == this) remove_all_children(); } void fltk_layout_group::layout() { if (!formatter.empty()) formatter->resize(w(), h()); // relayout children //for (int i=0; i<fltk::Group::children(); i++) // fltk::Group::child(i)->layout(); // fltk::Group::layout(); }
25.640212
130
0.677466
MarioHenze
a4951e9fe8e5df1fc6f9997d072e549859fc6348
510
cc
C++
CPPQEDutils/ComplexArrayExtensions.cc
bartoszek/cppqed
712b601e377642885f40cbf8a65eb1525360f654
[ "BSL-1.0" ]
null
null
null
CPPQEDutils/ComplexArrayExtensions.cc
bartoszek/cppqed
712b601e377642885f40cbf8a65eb1525360f654
[ "BSL-1.0" ]
null
null
null
CPPQEDutils/ComplexArrayExtensions.cc
bartoszek/cppqed
712b601e377642885f40cbf8a65eb1525360f654
[ "BSL-1.0" ]
null
null
null
// Copyright András Vukics 2006–2020. Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.txt) #include "ComplexArrayExtensions.h" namespace blitzplusplus { namespace dodirect { using namespace linalg; using namespace blitz::tensor; template<> void doDirect<true >(CMatrix& m, const CVector& v1, const CVector& v2) {m=v1(i)*v2(j);} template<> void doDirect<false>(CMatrix& m, const CVector& v1, const CVector& v2) {m=v1(i)+v2(j);} } // dodirect } // blitzplusplus
26.842105
132
0.737255
bartoszek
a49806fe781ebbfca44d86382b4aafae67482d82
2,029
cpp
C++
collection/cp/bcw_codebook-master/codes/Geometry/KD_tree/p1_KD_Tree.cpp
daemonslayer/Notebook
a9880be9bd86955afd6b8f7352822bc18673eda3
[ "Apache-2.0" ]
1
2019-03-24T13:12:01.000Z
2019-03-24T13:12:01.000Z
collection/cp/bcw_codebook-master/codes/Geometry/KD_tree/p1_KD_Tree.cpp
daemonslayer/Notebook
a9880be9bd86955afd6b8f7352822bc18673eda3
[ "Apache-2.0" ]
null
null
null
collection/cp/bcw_codebook-master/codes/Geometry/KD_tree/p1_KD_Tree.cpp
daemonslayer/Notebook
a9880be9bd86955afd6b8f7352822bc18673eda3
[ "Apache-2.0" ]
null
null
null
const INF = 1100000000; class NODE{ public: int x,y,x1,x2,y1,y2; int i,f; NODE *L,*R; }; inline long long dis(NODE& a,NODE& b){ long long dx=a.x-b.x; long long dy=a.y-b.y; return dx*dx+dy*dy; } NODE node[100000]; bool cmpx(const NODE& a,const NODE& b){ return a.x<b.x; } bool cmpy(const NODE& a,const NODE& b){ return a.y<b.y; } NODE* KDTree(int L,int R,int dep){ if(L>R) return 0; int M=(L+R)/2; if(dep%2==0){ nth_element(node+L,node+M,node+R+1,cmpx); node[M].f=0; }else{ nth_element(node+L,node+M,node+R+1,cmpy); node[M].f=1; } node[M].x1=node[M].x2=node[M].x; node[M].y1=node[M].y2=node[M].y; node[M].L=KDTree(L,M-1,dep+1); if(node[M].L){ node[M].x1=min(node[M].x1,node[M].L->x1); node[M].x2=max(node[M].x2,node[M].L->x2); node[M].y1=min(node[M].y1,node[M].L->y1); node[M].y2=max(node[M].y2,node[M].L->y2); } node[M].R=KDTree(M+1,R,dep+1); if(node[M].R){ node[M].x1=min(node[M].x1,node[M].R->x1); node[M].x2=max(node[M].x2,node[M].R->x2); node[M].y1=min(node[M].y1,node[M].R->y1); node[M].y2=max(node[M].y2,node[M].R->y2); } return node+M; } inline int touch(NODE* r,int x,int y,long long d){ long long d2; d2 = (long long)(sqrt(d)+1); if(x<r->x1-d2 || x>r->x2+d2 || y<r->y1-d2 || y>r->y2+d2) return 0; return 1; } void nearest(NODE* r,int z,long long &md){ if(!r || !touch(r,node[z].x,node[z].y,md)) return; long long d; if(node[z].i!=r->i){ d=dis(*r,node[z]); if(d<md) md=d; } if(r->f==0){ if(node[z].x<r->x){ nearest(r->L,z,md); nearest(r->R,z,md); }else{ nearest(r->R,z,md); nearest(r->L,z,md); } }else{ if(node[z].y<r->y){ nearest(r->L,z,md); nearest(r->R,z,md); }else{ nearest(r->R,z,md); nearest(r->L,z,md); } } } int main(){ int TT,n,i; long long d; NODE* root; scanf("%d",&TT); while(TT--){ scanf("%d",&n); for(i=0;i<n;i++){ scanf("%d %d",&node[i].x,&node[i].y); node[i].i=i; } root=KDTree(0,n-1,0); for(i=0;i<n;i++){ d=9000000000000000000LL; nearest(root,i,d); ans[node[i].i]=d; } } }
21.357895
57
0.559389
daemonslayer
a49b585d1de37a01b3dce14c750ecb09dcbeec0d
155
hh
C++
include/cppti/Utils.hh
Ethiraric/cpptalksindex
0f342f944d3da6d456694bee199e89570b07588f
[ "MIT" ]
4
2020-10-06T10:12:59.000Z
2021-05-22T07:41:29.000Z
include/cppti/Utils.hh
Ethiraric/cpptalksindex
0f342f944d3da6d456694bee199e89570b07588f
[ "MIT" ]
null
null
null
include/cppti/Utils.hh
Ethiraric/cpptalksindex
0f342f944d3da6d456694bee199e89570b07588f
[ "MIT" ]
null
null
null
#ifndef CPPTI_UTILS_HH_ #define CPPTI_UTILS_HH_ #include <string> namespace cppti { void toSnakeCase(std::string& str); } #endif /* !CPPTI_UTILS_HH_ */
12.916667
35
0.748387
Ethiraric
a49ca13224da26d48fc919448637421a355fa7fc
10,177
cpp
C++
utils/preprocess/beer.cpp
charlespnh/shortest-beer-path
c133969bbfd977498623f39e665e60e66890b998
[ "MIT" ]
1
2021-09-13T04:01:12.000Z
2021-09-13T04:01:12.000Z
utils/preprocess/beer.cpp
Phuc2002/shortest-beer-path
c133969bbfd977498623f39e665e60e66890b998
[ "MIT" ]
null
null
null
utils/preprocess/beer.cpp
Phuc2002/shortest-beer-path
c133969bbfd977498623f39e665e60e66890b998
[ "MIT" ]
null
null
null
#include <algorithm> #include <utility> #include <cstdio> #include <iostream> using namespace std; #include "../../include/preprocess/beer.h" #include "../../include/outerplanar.h" #include "../../include/graph/dcel.h" double beer::weightB(struct halfedge* e) { return dcel::edgeB(e)->distB; } double beer::weightB(struct vertex* v) { return dcel::edgeB(v)->distB; } struct vertex* beer::originB(struct halfedge* e) { return dcel::edgeB(e)->u; } struct vertex* beer::targetB(struct halfedge* e) { return dcel::edgeB(e)->v; } struct vertex* beer::originB(struct vertex* v) { return v; } struct vertex* beer::targetB(struct vertex* v) { return v; } struct b_edge* beer::get_edgeB(struct vertex* u, struct vertex* v){ if (u == v) return dcel::edgeB(u); struct halfedge* uv = graph::get_edge(u, v); if (uv) return dcel::edgeB(uv); return NULL; } // post-order traversal of D(G) // compute distB(a, b, G\R) void beer::beerDistNotRoot(struct node* F){ if (F == NULL) return; struct halfedge* ab = dcel::edge(F); struct halfedge* ac = dcel::prev(ab); struct halfedge* bc = dcel::next(ab); beer::beerDistNotRoot(dcel::left(F)); beer::beerDistNotRoot(dcel::right(F)); // for all v in face F for (int i = 0; i < 3; i++, ab = dcel::next(ab)){ struct halfedge* uv = ab; struct halfedge* vw = bc; struct vertex* v = dcel::target(uv); struct vertex* u = dcel::origin(uv); struct vertex* w = dcel::target(vw); v->beer_edge->distB = min(beer::weightB(v), min(2 * dcel::weight(uv) + beer::weightB(u), 2 * dcel::weight(vw) + beer::weightB(w))); if (beer::weightB(v) == 2 * dcel::weight(uv) + beer::weightB(u)) v->beer_edge->pathB = make_pair(u, 0); else if (beer::weightB(v) == 2 * dcel::weight(vw) + beer::weightB(w)) v->beer_edge->pathB = make_pair(w, 0); } // distB(a, b, G\R) struct vertex* a = dcel::target(ac); struct vertex* b = dcel::target(ab); struct vertex* c = dcel::target(bc); if (beer::originB(ab) != a) swap(ab->beer_edge->u, ab->beer_edge->v); ab->beer_edge->distB = min(min(dcel::weight(ab) + beer::weightB(a), dcel::weight(ab) + beer::weightB(b)), min(beer::weightB(ac) + dcel::weight(bc), dcel::weight(ac) + beer::weightB(bc))); if (beer::weightB(ab) == dcel::weight(ab) + beer::weightB(a)) ab->beer_edge->pathB = make_pair(a, 0); else if (beer::weightB(ab) == dcel::weight(ab) + beer::weightB(b)) ab->beer_edge->pathB = make_pair(b, 1); else if (beer::weightB(ab) == beer::weightB(ac) + dcel::weight(bc)) ab->beer_edge->pathB = make_pair(c, 0); else ab->beer_edge->pathB = make_pair(c, 1); } // compute beer dist for edge E in subgraph G not R void beer::computeBeerDistNotRoot(struct node* R){ struct halfedge* E = dcel::edge(R); struct halfedge* traverse_e = dcel::twin(E); struct vertex *u, *v, *w; struct halfedge *uv, *vw; // Base case post-order traversal: for all v in V(G) do { v = dcel::target(traverse_e); if (dcel::beer(v)) v->beer_edge->distB = 0; // v->beer_edge->beer = NIL; // else v->beer->distB = INF; traverse_e = dcel::next(traverse_e); } while(traverse_e != dcel::twin(E)); // Base case post-order traversal: for all exterior edge (u, v) in E(G) do { uv = traverse_e; u = dcel::origin(uv); v = dcel::target(uv); if (dcel::beer(u) || dcel::beer(v)) uv->beer_edge->distB = dcel::weight(uv); // uv->beer_edge->pathB = NIL; // else uv->beer_edge->distB = INF; traverse_e = dcel::next(traverse_e); } while(traverse_e != dcel::twin(E)); // Recurrence: for all interior edges in face R for (int i = 0; i < 3; i++, E = dcel::next(E)) beer::beerDistNotRoot(dcel::face(dcel::twin(E))); // Base case pre-order traversal: for all v in face R for (int i = 0; i < 3; i++, E = dcel::next(E)){ uv = E; vw = dcel::next(E); v = dcel::target(uv); /* (u -> v) v */ u = dcel::origin(uv); /* (w -> u) / R \ */ w = dcel::target(vw); /* (v -> w) w --- u */ v->beer_edge->distB = min(beer::weightB(v), min(2 * dcel::weight(uv) + beer::weightB(u), 2 * dcel::weight(vw) + beer::weightB(w))); if (beer::weightB(v) == 2 * dcel::weight(uv) + beer::weightB(u)) v->beer_edge->pathB = make_pair(u, 0); else if (beer::weightB(v) == 2 * dcel::weight(vw) + beer::weightB(w)) v->beer_edge->pathB = make_pair(w, 0); } } // pre-order traversal of D(G) void beer::beerDistRoot(struct node* F){ // distB(a, b, G_R) is already computed (in previous recursive call during pre-order traversal) if (F == NULL) return; struct halfedge* ab = dcel::edge(F); struct halfedge* ac = dcel::prev(ab); struct halfedge* bc = dcel::next(ab); struct vertex* a = dcel::target(ac); struct vertex* b = dcel::target(ab); struct vertex* c = dcel::target(bc); double tmp; c->beer_edge->distB = min(beer::weightB(c), min(2 * dcel::weight(ac) + beer::weightB(a), 2 * dcel::weight(bc) + beer::weightB(b))); if (beer::weightB(c) == 2 * dcel::weight(ac) + beer::weightB(a)) c->beer_edge->pathB = make_pair(a, 0); else if (beer::weightB(c) == 2 * dcel::weight(bc) + beer::weightB(b)) c->beer_edge->pathB = make_pair(b, 0); // compute distB(c, a, G_R) bool relax = true; tmp = beer::weightB(ac); ac->beer_edge->distB = min(beer::weightB(ac), min(min(dcel::weight(ac) + beer::weightB(a), dcel::weight(ac) + beer::weightB(c)), min(beer::weightB(ab) + dcel::weight(bc), dcel::weight(ab) + beer::weightB(bc)))); if (beer::weightB(ac) == tmp) relax = false; else if (beer::weightB(ac) == dcel::weight(ac) + beer::weightB(a)) ac->beer_edge->pathB = make_pair(a, 1); else if (beer::weightB(ac) == dcel::weight(ac) + beer::weightB(c)) ac->beer_edge->pathB = make_pair(c, 0); else if (beer::weightB(ac) == beer::weightB(ab) + dcel::weight(bc)) ac->beer_edge->pathB = make_pair(b, 1); else ac->beer_edge->pathB = make_pair(b, 0); if (relax && beer::originB(ac) != c) swap(ac->beer_edge->u, ac->beer_edge->v); // compute distB(b, c, G_R) relax = true; tmp = beer::weightB(bc); bc->beer_edge->distB = min(beer::weightB(bc), min(min(dcel::weight(bc) + beer::weightB(b), dcel::weight(bc) + beer::weightB(c)), min(beer::weightB(ab) + dcel::weight(ac), dcel::weight(ab) + beer::weightB(ac)))); if (beer::weightB(bc) == tmp) relax = false; else if (beer::weightB(bc) == dcel::weight(bc) + beer::weightB(b)) bc->beer_edge->pathB = make_pair(b, 0); else if (beer::weightB(bc) == dcel::weight(bc) + beer::weightB(c)) bc->beer_edge->pathB = make_pair(c, 1); else if (beer::weightB(bc) == beer::weightB(ab) + dcel::weight(ac)) bc->beer_edge->pathB = make_pair(a, 0); else bc->beer_edge->pathB = make_pair(a, 1); if (relax && beer::originB(bc) != b) swap(bc->beer_edge->u, bc->beer_edge->v); beer::beerDistRoot(dcel::left(F)); beer::beerDistRoot(dcel::right(F)); } // compute beer dist for all edge E in subgraph G with R void beer::computeBeerDistRoot(struct node* R){ // Base case pre-order traversal: for all v in face R... computed during post-order traversal // Base case pre-order traversal: for all edge (u, v) in face R struct halfedge* E = dcel::edge(R); for (int i = 0; i < 3; i++, E = dcel::next(E)){ struct halfedge* uv = E; struct halfedge* uw = dcel::prev(E); struct halfedge* wv = dcel::next(E); struct vertex* v = dcel::target(uv); struct vertex* u = dcel::target(uw); struct vertex* w = dcel::target(wv); double tmp; bool relax = true; tmp = beer::weightB(uv); uv->beer_edge->distB = min(beer::weightB(uv), min(min(dcel::weight(uv) + beer::weightB(u), dcel::weight(uv) + beer::weightB(v)), min(beer::weightB(uw) + dcel::weight(wv), dcel::weight(uw) + beer::weightB(wv)))); if (beer::weightB(uv) == tmp) relax = false; else if (beer::weightB(uv) == dcel::weight(uv) + beer::weightB(u)) uv->beer_edge->pathB = make_pair(u, 0); else if (beer::weightB(uv) == dcel::weight(uv) + beer::weightB(v)) uv->beer_edge->pathB = make_pair(v, 1); else if (beer::weightB(uv) == beer::weightB(uw) + dcel::weight(wv)) uv->beer_edge->pathB = make_pair(w, 0); else uv->beer_edge->pathB = make_pair(w, 1); if (relax && beer::originB(uv) != u) swap(uv->beer_edge->u, uv->beer_edge->v); } for (int i = 0; i < 3; i++, E = dcel::next(E)) beer::beerDistRoot(dcel::face(dcel::twin(E))); } vector<struct vertex*> beer::print_beer_path(struct vertex* v){ return print_beer_subpath(dcel::edgeB(v)); } vector<struct vertex*> beer::print_beer_path(struct halfedge* uv){ vector<struct vertex*> pathB = beer::print_beer_path(dcel::edgeB(uv)); if (dcel::origin(uv) != pathB.front()) reverse(pathB.begin(), pathB.end()); return pathB; } vector<struct vertex*> beer::print_beer_path(struct b_edge* uv){ vector<struct vertex*> pathB = {uv->u}; vector<struct vertex*> subPathB = beer::print_beer_subpath(uv); pathB.insert(pathB.end(), subPathB.begin(), subPathB.end()); return pathB; } vector<struct vertex*> beer::print_beer_subpath(struct b_edge* e){ if (dcel::beer(e->u) || dcel::beer(e->v)) return {e->v}; // u - w - v vector<struct vertex*> path; auto [w, beerLoc] = e->pathB; if (beerLoc == 0){ struct b_edge* subpathB = beer::get_edgeB(e->u, w); if (subpathB->u != e->u && subpathB->v != w){ swap(subpathB->u, subpathB->v); subpathB->pathB.second = !subpathB->pathB.second; } // u - w is the beer subpath path = print_beer_subpath(subpathB); path.push_back(e->v); } else{ struct b_edge* subpathB = beer::get_edgeB(w, e->v); if (subpathB->u != w && subpathB->v != e->v){ swap(subpathB->u, subpathB->v); subpathB->pathB.second = !subpathB->pathB.second; } // w - v is the beer subpath vector<struct vertex*> sub_path = beer::print_beer_subpath(subpathB); path = {w}; path.insert(path.end(), sub_path.begin(), sub_path.end()); } return path; }
34.498305
132
0.606466
charlespnh
a49faf9c953fe1d6822b9a12c44d27de9e4c127c
49
cpp
C++
SFINAE/Foo.cpp
dave-c/workspace-snippets
f1ace623023f185f972fa35ac57c9fe8a651ffae
[ "MIT" ]
null
null
null
SFINAE/Foo.cpp
dave-c/workspace-snippets
f1ace623023f185f972fa35ac57c9fe8a651ffae
[ "MIT" ]
null
null
null
SFINAE/Foo.cpp
dave-c/workspace-snippets
f1ace623023f185f972fa35ac57c9fe8a651ffae
[ "MIT" ]
null
null
null
#include "Foo.h" Foo::Foo() {} Foo::~Foo() {}
5.444444
16
0.469388
dave-c
a49ff3a3d231179b3562f06585a217e626948b88
915
cpp
C++
Pertemuan 1/tugas5.cpp
riqulaziz/Computer-Programming-Biomedical-Engineering-UNAIR
90d96c177fe1d3019ec371d1be3e4a9857557e69
[ "Apache-2.0" ]
1
2021-12-09T15:31:04.000Z
2021-12-09T15:31:04.000Z
Pertemuan 1/tugas5.cpp
riqulaziz/Computer-Programming-Biomedical-Engineering-UNAIR
90d96c177fe1d3019ec371d1be3e4a9857557e69
[ "Apache-2.0" ]
null
null
null
Pertemuan 1/tugas5.cpp
riqulaziz/Computer-Programming-Biomedical-Engineering-UNAIR
90d96c177fe1d3019ec371d1be3e4a9857557e69
[ "Apache-2.0" ]
null
null
null
#include<iostream> #include<conio.h> #include<math.h> using namespace std; int main() { int i,j; float jumlah,kurang,kali,bagi,mod; cout<<"Masukan nilai i = ";cin>>i; cout<<"Masukan nilai j = ";cin>>j; jumlah= i+j; // penjumlahan kurang = i-j; // pengurangan kali = i*j; // perkalian bagi = i/j; // pembagian mod = i%j; // modulus cout<<"-------------------------------"<<endl; cout<<"|"<<" Operasi "<<"|"<<" Hasil Operasi "<<"|"<<endl; cout<<"-------------------------------"<<endl; cout<<"| "<<i<<" + "<<j<<" | "<<jumlah<<" |"<<endl; cout<<"| "<<i<<" - "<<j<<" | "<<kurang<<" |"<<endl; cout<<"| "<<i<<" * "<<j<<" | "<<kali<<" |"<<endl; cout<<"| "<<i<<" div "<<j<<" | "<<bagi<<" |"<<endl; cout<<"| "<<i<<" mod "<<j<<" | "<<mod<<" |"<<endl; cout<<"-------------------------------"<<endl; return 0 ; }
32.678571
70
0.389071
riqulaziz
a4a033c6333d8f5f3e2c8352e30ad9a27b386729
1,043
hpp
C++
src/controllers/npc_controller.hpp
astrellon/simple-space
20e98d4f562a78b1efeaedb0a0012f3c9306ac7e
[ "MIT" ]
1
2020-09-23T11:17:35.000Z
2020-09-23T11:17:35.000Z
src/controllers/npc_controller.hpp
astrellon/simple-space
20e98d4f562a78b1efeaedb0a0012f3c9306ac7e
[ "MIT" ]
null
null
null
src/controllers/npc_controller.hpp
astrellon/simple-space
20e98d4f562a78b1efeaedb0a0012f3c9306ac7e
[ "MIT" ]
null
null
null
#pragma once #include <queue> #include <memory> #include <SFML/System.hpp> #include "character_controller.hpp" #include "npc_needs.hpp" #include "actions/npc_action.hpp" namespace space { class Dialogue; class Interaction; class NpcController : public CharacterController { public: // Fields // Constructor NpcController(GameSession &session); // Methods static const std::string ControllerType() { return "npc"; } virtual std::string type() const { return ControllerType(); } NpcNeeds &needs() { return _needs; } virtual void update(sf::Time dt); void dialogue(const Dialogue *dialogue); const Dialogue *dialogue() const { return _dialogue; } protected: // Fields NpcNeeds _needs; std::queue<std::unique_ptr<NpcAction>> _highLevelActions; const Dialogue *_dialogue; Interaction *_startDialogueAction; }; } // space
23.704545
73
0.598274
astrellon
a4a3913af3c0ffda6de292fffe348340d1e9e651
24,242
cpp
C++
src/org/apache/poi/sl/draw/SLGraphics.cpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
src/org/apache/poi/sl/draw/SLGraphics.cpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
src/org/apache/poi/sl/draw/SLGraphics.cpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
// Generated from /POI/java/org/apache/poi/sl/draw/SLGraphics.java #include <org/apache/poi/sl/draw/SLGraphics.hpp> #include <java/awt/BasicStroke.hpp> #include <java/awt/Color.hpp> #include <java/awt/Font.hpp> #include <java/awt/FontMetrics.hpp> #include <java/awt/Graphics.hpp> #include <java/awt/GraphicsConfiguration.hpp> #include <java/awt/GraphicsDevice.hpp> #include <java/awt/GraphicsEnvironment.hpp> #include <java/awt/Image.hpp> #include <java/awt/Paint.hpp> #include <java/awt/Polygon.hpp> #include <java/awt/Rectangle.hpp> #include <java/awt/RenderingHints_Key.hpp> #include <java/awt/RenderingHints.hpp> #include <java/awt/Shape.hpp> #include <java/awt/Stroke.hpp> #include <java/awt/Toolkit.hpp> #include <java/awt/font/FontRenderContext.hpp> #include <java/awt/font/GlyphVector.hpp> #include <java/awt/font/TextLayout.hpp> #include <java/awt/geom/AffineTransform.hpp> #include <java/awt/geom/Arc2D_Double.hpp> #include <java/awt/geom/Arc2D.hpp> #include <java/awt/geom/Ellipse2D_Double.hpp> #include <java/awt/geom/Ellipse2D.hpp> #include <java/awt/geom/GeneralPath.hpp> #include <java/awt/geom/Line2D_Double.hpp> #include <java/awt/geom/Line2D.hpp> #include <java/awt/geom/Path2D_Double.hpp> #include <java/awt/geom/RoundRectangle2D_Double.hpp> #include <java/awt/geom/RoundRectangle2D.hpp> #include <java/awt/image/BufferedImage.hpp> #include <java/awt/image/BufferedImageOp.hpp> #include <java/awt/image/ImageObserver.hpp> #include <java/lang/Boolean.hpp> #include <java/lang/Class.hpp> #include <java/lang/ClassCastException.hpp> #include <java/lang/CloneNotSupportedException.hpp> #include <java/lang/Double.hpp> #include <java/lang/Math.hpp> #include <java/lang/NullPointerException.hpp> #include <java/lang/Object.hpp> #include <java/lang/RuntimeException.hpp> #include <java/lang/String.hpp> #include <java/lang/Throwable.hpp> #include <java/util/List.hpp> #include <java/util/Map.hpp> #include <org/apache/poi/sl/draw/DrawPaint.hpp> #include <org/apache/poi/sl/usermodel/FreeformShape.hpp> #include <org/apache/poi/sl/usermodel/GroupShape.hpp> #include <org/apache/poi/sl/usermodel/Insets2D.hpp> #include <org/apache/poi/sl/usermodel/PaintStyle_SolidPaint.hpp> #include <org/apache/poi/sl/usermodel/PaintStyle.hpp> #include <org/apache/poi/sl/usermodel/SimpleShape.hpp> #include <org/apache/poi/sl/usermodel/StrokeStyle_LineDash.hpp> #include <org/apache/poi/sl/usermodel/TextBox.hpp> #include <org/apache/poi/sl/usermodel/TextParagraph.hpp> #include <org/apache/poi/sl/usermodel/TextRun.hpp> #include <org/apache/poi/sl/usermodel/VerticalAlignment.hpp> #include <org/apache/poi/util/POILogFactory.hpp> #include <org/apache/poi/util/POILogger.hpp> #include <Array.hpp> #include <ObjectArray.hpp> template<typename T, typename U> static T java_cast(U* u) { if(!u) return static_cast<T>(nullptr); auto t = dynamic_cast<T>(u); if(!t) throw new ::java::lang::ClassCastException(); return t; } template<typename T> static T* npc(T* t) { if(!t) throw new ::java::lang::NullPointerException(); return t; } poi::sl::draw::SLGraphics::SLGraphics(const ::default_init_tag&) : super(*static_cast< ::default_init_tag* >(0)) { clinit(); } poi::sl::draw::SLGraphics::SLGraphics(::poi::sl::usermodel::GroupShape* group) : SLGraphics(*static_cast< ::default_init_tag* >(0)) { ctor(group); } void poi::sl::draw::SLGraphics::init() { log = ::poi::util::POILogFactory::getLogger(static_cast< ::java::lang::Class* >(this->getClass())); } void poi::sl::draw::SLGraphics::ctor(::poi::sl::usermodel::GroupShape* group) { super::ctor(); init(); this->_group = group; _transform = new ::java::awt::geom::AffineTransform(); _stroke = new ::java::awt::BasicStroke(); _paint = ::java::awt::Color::black(); _font = new ::java::awt::Font(u"Arial"_j, ::java::awt::Font::PLAIN, int32_t(12)); _background = ::java::awt::Color::black(); _foreground = ::java::awt::Color::white(); _hints = new ::java::awt::RenderingHints(nullptr); } poi::sl::usermodel::GroupShape* poi::sl::draw::SLGraphics::getShapeGroup() { return _group; } java::awt::Font* poi::sl::draw::SLGraphics::getFont() { return _font; } void poi::sl::draw::SLGraphics::setFont(::java::awt::Font* font) { this->_font = font; } java::awt::Color* poi::sl::draw::SLGraphics::getColor() { return _foreground; } void poi::sl::draw::SLGraphics::setColor(::java::awt::Color* c) { setPaint(static_cast< ::java::awt::Paint* >(c)); } java::awt::Stroke* poi::sl::draw::SLGraphics::getStroke() { return _stroke; } void poi::sl::draw::SLGraphics::setStroke(::java::awt::Stroke* s) { this->_stroke = s; } java::awt::Paint* poi::sl::draw::SLGraphics::getPaint() { return _paint; } void poi::sl::draw::SLGraphics::setPaint(::java::awt::Paint* paint) { if(paint == nullptr) return; this->_paint = paint; if(dynamic_cast< ::java::awt::Color* >(paint) != nullptr) _foreground = java_cast< ::java::awt::Color* >(paint); } java::awt::geom::AffineTransform* poi::sl::draw::SLGraphics::getTransform() { return new ::java::awt::geom::AffineTransform(_transform); } void poi::sl::draw::SLGraphics::setTransform(::java::awt::geom::AffineTransform* Tx) { _transform = new ::java::awt::geom::AffineTransform(Tx); } void poi::sl::draw::SLGraphics::draw(::java::awt::Shape* shape) { auto path = new ::java::awt::geom::Path2D_Double(npc(_transform)->createTransformedShape(shape)); auto p = npc(_group)->createFreeform(); npc(p)->setPath(path); npc(p)->setFillColor(nullptr); applyStroke(p); if(dynamic_cast< ::java::awt::Color* >(_paint) != nullptr) { npc(p)->setStrokeStyle(new ::java::lang::ObjectArray({static_cast< ::java::lang::Object* >(java_cast< ::java::awt::Color* >(_paint))})); } } void poi::sl::draw::SLGraphics::drawString(::java::lang::String* s, float x, float y) { auto txt = npc(_group)->createTextBox(); ::poi::sl::usermodel::TextRun* rt = java_cast< ::poi::sl::usermodel::TextRun* >(java_cast< ::java::lang::Object* >(npc(npc(java_cast< ::poi::sl::usermodel::TextParagraph* >(npc(npc(txt)->getTextParagraphs())->get(0)))->getTextRuns())->get(0))); npc(rt)->setFontSize(::java::lang::Double::valueOf(static_cast< double >(npc(_font)->getSize()))); npc(rt)->setFontFamily(npc(_font)->getFamily()); if(getColor() != nullptr) npc(rt)->setFontColor(static_cast< ::poi::sl::usermodel::PaintStyle* >(DrawPaint::createSolidPaint(getColor()))); if(npc(_font)->isBold()) npc(rt)->setBold(true); if(npc(_font)->isItalic()) npc(rt)->setItalic(true); npc(txt)->setText(s); npc(txt)->setInsets(new ::poi::sl::usermodel::Insets2D(int32_t(0), int32_t(0), int32_t(0), int32_t(0))); npc(txt)->setWordWrap(false); npc(txt)->setHorizontalCentered(::java::lang::Boolean::valueOf(false)); npc(txt)->setVerticalAlignment(::poi::sl::usermodel::VerticalAlignment::MIDDLE); auto layout = new ::java::awt::font::TextLayout(s, _font, getFontRenderContext()); auto ascent = npc(layout)->getAscent(); auto width = static_cast< float >(::java::lang::Math::floor(npc(layout)->getAdvance())); auto height = ascent * int32_t(2); y -= height / int32_t(2) + ascent / int32_t(2); npc(txt)->setAnchor(new ::java::awt::Rectangle(static_cast< int32_t >(x), static_cast< int32_t >(y), static_cast< int32_t >(width), static_cast< int32_t >(height))); } void poi::sl::draw::SLGraphics::fill(::java::awt::Shape* shape) { auto path = new ::java::awt::geom::Path2D_Double(npc(_transform)->createTransformedShape(shape)); auto p = npc(_group)->createFreeform(); npc(p)->setPath(path); applyPaint(p); npc(p)->setStrokeStyle(new ::java::lang::ObjectArray()); } void poi::sl::draw::SLGraphics::translate(int32_t x, int32_t y) { npc(_transform)->translate(x, y); } void poi::sl::draw::SLGraphics::clip(::java::awt::Shape* s) { if(npc(log)->check(::poi::util::POILogger::WARN)) { npc(log)->log(::poi::util::POILogger::WARN, new ::java::lang::ObjectArray({static_cast< ::java::lang::Object* >(u"Not implemented"_j)})); } } java::awt::Shape* poi::sl::draw::SLGraphics::getClip() { if(npc(log)->check(::poi::util::POILogger::WARN)) { npc(log)->log(::poi::util::POILogger::WARN, new ::java::lang::ObjectArray({static_cast< ::java::lang::Object* >(u"Not implemented"_j)})); } return nullptr; } void poi::sl::draw::SLGraphics::scale(double sx, double sy) { npc(_transform)->scale(sx, sy); } void poi::sl::draw::SLGraphics::drawRoundRect(int32_t x, int32_t y, int32_t width, int32_t height, int32_t arcWidth, int32_t arcHeight) { ::java::awt::geom::RoundRectangle2D* rect = new ::java::awt::geom::RoundRectangle2D_Double(x, y, width, height, arcWidth, arcHeight); draw(static_cast< ::java::awt::Shape* >(rect)); } void poi::sl::draw::SLGraphics::drawString(::java::lang::String* str, int32_t x, int32_t y) { drawString(str, static_cast< float >(x), static_cast< float >(y)); } void poi::sl::draw::SLGraphics::fillOval(int32_t x, int32_t y, int32_t width, int32_t height) { ::java::awt::geom::Ellipse2D* oval = new ::java::awt::geom::Ellipse2D_Double(x, y, width, height); fill(static_cast< ::java::awt::Shape* >(oval)); } void poi::sl::draw::SLGraphics::fillRoundRect(int32_t x, int32_t y, int32_t width, int32_t height, int32_t arcWidth, int32_t arcHeight) { ::java::awt::geom::RoundRectangle2D* rect = new ::java::awt::geom::RoundRectangle2D_Double(x, y, width, height, arcWidth, arcHeight); fill(static_cast< ::java::awt::Shape* >(rect)); } void poi::sl::draw::SLGraphics::fillArc(int32_t x, int32_t y, int32_t width, int32_t height, int32_t startAngle, int32_t arcAngle) { ::java::awt::geom::Arc2D* arc = new ::java::awt::geom::Arc2D_Double(x, y, width, height, startAngle, arcAngle, ::java::awt::geom::Arc2D::PIE); fill(static_cast< ::java::awt::Shape* >(arc)); } void poi::sl::draw::SLGraphics::drawArc(int32_t x, int32_t y, int32_t width, int32_t height, int32_t startAngle, int32_t arcAngle) { ::java::awt::geom::Arc2D* arc = new ::java::awt::geom::Arc2D_Double(x, y, width, height, startAngle, arcAngle, ::java::awt::geom::Arc2D::OPEN); draw(static_cast< ::java::awt::Shape* >(arc)); } void poi::sl::draw::SLGraphics::drawPolyline(::int32_tArray* xPoints, ::int32_tArray* yPoints, int32_t nPoints) { if(nPoints > 0) { auto path = new ::java::awt::geom::GeneralPath(); npc(path)->moveTo(static_cast< float >((*xPoints)[int32_t(0)]), static_cast< float >((*yPoints)[int32_t(0)])); for (auto i = int32_t(1); i < nPoints; i++) npc(path)->lineTo(static_cast< float >((*xPoints)[i]), static_cast< float >((*yPoints)[i])); draw(static_cast< ::java::awt::Shape* >(path)); } } void poi::sl::draw::SLGraphics::drawOval(int32_t x, int32_t y, int32_t width, int32_t height) { ::java::awt::geom::Ellipse2D* oval = new ::java::awt::geom::Ellipse2D_Double(x, y, width, height); draw(static_cast< ::java::awt::Shape* >(oval)); } bool poi::sl::draw::SLGraphics::drawImage(::java::awt::Image* img, int32_t x, int32_t y, ::java::awt::Color* bgcolor, ::java::awt::image::ImageObserver* observer) { if(npc(log)->check(::poi::util::POILogger::WARN)) { npc(log)->log(::poi::util::POILogger::WARN, new ::java::lang::ObjectArray({static_cast< ::java::lang::Object* >(u"Not implemented"_j)})); } return false; } bool poi::sl::draw::SLGraphics::drawImage(::java::awt::Image* img, int32_t x, int32_t y, int32_t width, int32_t height, ::java::awt::Color* bgcolor, ::java::awt::image::ImageObserver* observer) { if(npc(log)->check(::poi::util::POILogger::WARN)) { npc(log)->log(::poi::util::POILogger::WARN, new ::java::lang::ObjectArray({static_cast< ::java::lang::Object* >(u"Not implemented"_j)})); } return false; } bool poi::sl::draw::SLGraphics::drawImage(::java::awt::Image* img, int32_t dx1, int32_t dy1, int32_t dx2, int32_t dy2, int32_t sx1, int32_t sy1, int32_t sx2, int32_t sy2, ::java::awt::image::ImageObserver* observer) { if(npc(log)->check(::poi::util::POILogger::WARN)) { npc(log)->log(::poi::util::POILogger::WARN, new ::java::lang::ObjectArray({static_cast< ::java::lang::Object* >(u"Not implemented"_j)})); } return false; } bool poi::sl::draw::SLGraphics::drawImage(::java::awt::Image* img, int32_t dx1, int32_t dy1, int32_t dx2, int32_t dy2, int32_t sx1, int32_t sy1, int32_t sx2, int32_t sy2, ::java::awt::Color* bgcolor, ::java::awt::image::ImageObserver* observer) { if(npc(log)->check(::poi::util::POILogger::WARN)) { npc(log)->log(::poi::util::POILogger::WARN, new ::java::lang::ObjectArray({static_cast< ::java::lang::Object* >(u"Not implemented"_j)})); } return false; } bool poi::sl::draw::SLGraphics::drawImage(::java::awt::Image* img, int32_t x, int32_t y, ::java::awt::image::ImageObserver* observer) { if(npc(log)->check(::poi::util::POILogger::WARN)) { npc(log)->log(::poi::util::POILogger::WARN, new ::java::lang::ObjectArray({static_cast< ::java::lang::Object* >(u"Not implemented"_j)})); } return false; } void poi::sl::draw::SLGraphics::dispose() { } void poi::sl::draw::SLGraphics::drawLine(int32_t x1, int32_t y1, int32_t x2, int32_t y2) { ::java::awt::geom::Line2D* line = new ::java::awt::geom::Line2D_Double(x1, y1, x2, y2); draw(static_cast< ::java::awt::Shape* >(line)); } void poi::sl::draw::SLGraphics::fillPolygon(::int32_tArray* xPoints, ::int32_tArray* yPoints, int32_t nPoints) { auto polygon = new ::java::awt::Polygon(xPoints, yPoints, nPoints); fill(static_cast< ::java::awt::Shape* >(polygon)); } void poi::sl::draw::SLGraphics::fillRect(int32_t x, int32_t y, int32_t width, int32_t height) { auto rect = new ::java::awt::Rectangle(x, y, width, height); fill(static_cast< ::java::awt::Shape* >(rect)); } void poi::sl::draw::SLGraphics::drawRect(int32_t x, int32_t y, int32_t width, int32_t height) { auto rect = new ::java::awt::Rectangle(x, y, width, height); draw(static_cast< ::java::awt::Shape* >(rect)); } void poi::sl::draw::SLGraphics::drawPolygon(::int32_tArray* xPoints, ::int32_tArray* yPoints, int32_t nPoints) { auto polygon = new ::java::awt::Polygon(xPoints, yPoints, nPoints); draw(static_cast< ::java::awt::Shape* >(polygon)); } void poi::sl::draw::SLGraphics::clipRect(int32_t x, int32_t y, int32_t width, int32_t height) { clip(static_cast< ::java::awt::Shape* >(new ::java::awt::Rectangle(x, y, width, height))); } void poi::sl::draw::SLGraphics::setClip(::java::awt::Shape* clip) { if(npc(log)->check(::poi::util::POILogger::WARN)) { npc(log)->log(::poi::util::POILogger::WARN, new ::java::lang::ObjectArray({static_cast< ::java::lang::Object* >(u"Not implemented"_j)})); } } java::awt::Rectangle* poi::sl::draw::SLGraphics::getClipBounds() { auto c = getClip(); if(c == nullptr) { return nullptr; } return npc(c)->getBounds(); } void poi::sl::draw::SLGraphics::drawString(::java::text::AttributedCharacterIterator* iterator, int32_t x, int32_t y) { drawString(iterator, static_cast< float >(x), static_cast< float >(y)); } void poi::sl::draw::SLGraphics::clearRect(int32_t x, int32_t y, int32_t width, int32_t height) { auto paint = getPaint(); setColor(getBackground()); fillRect(x, y, width, height); setPaint(paint); } void poi::sl::draw::SLGraphics::copyArea(int32_t x, int32_t y, int32_t width, int32_t height, int32_t dx, int32_t dy) { } void poi::sl::draw::SLGraphics::setClip(int32_t x, int32_t y, int32_t width, int32_t height) { setClip(static_cast< ::java::awt::Shape* >(new ::java::awt::Rectangle(x, y, width, height))); } void poi::sl::draw::SLGraphics::rotate(double theta) { npc(_transform)->rotate(theta); } void poi::sl::draw::SLGraphics::rotate(double theta, double x, double y) { npc(_transform)->rotate(theta, x, y); } void poi::sl::draw::SLGraphics::shear(double shx, double shy) { npc(_transform)->shear(shx, shy); } java::awt::font::FontRenderContext* poi::sl::draw::SLGraphics::getFontRenderContext() { auto isAntiAliased = npc(::java::awt::RenderingHints::VALUE_TEXT_ANTIALIAS_ON())->equals(getRenderingHint(::java::awt::RenderingHints::KEY_TEXT_ANTIALIASING())); auto usesFractionalMetrics = npc(::java::awt::RenderingHints::VALUE_FRACTIONALMETRICS_ON())->equals(getRenderingHint(::java::awt::RenderingHints::KEY_FRACTIONALMETRICS())); return new ::java::awt::font::FontRenderContext(new ::java::awt::geom::AffineTransform(), isAntiAliased, usesFractionalMetrics); } void poi::sl::draw::SLGraphics::transform(::java::awt::geom::AffineTransform* Tx) { npc(_transform)->concatenate(Tx); } void poi::sl::draw::SLGraphics::drawImage(::java::awt::image::BufferedImage* img, ::java::awt::image::BufferedImageOp* op, int32_t x, int32_t y) { img = npc(op)->filter(img, nullptr); drawImage(static_cast< ::java::awt::Image* >(img), x, y, static_cast< ::java::awt::image::ImageObserver* >(nullptr)); } void poi::sl::draw::SLGraphics::setBackground(::java::awt::Color* color) { if(color == nullptr) return; _background = color; } java::awt::Color* poi::sl::draw::SLGraphics::getBackground() { return _background; } void poi::sl::draw::SLGraphics::setComposite(::java::awt::Composite* comp) { if(npc(log)->check(::poi::util::POILogger::WARN)) { npc(log)->log(::poi::util::POILogger::WARN, new ::java::lang::ObjectArray({static_cast< ::java::lang::Object* >(u"Not implemented"_j)})); } } java::awt::Composite* poi::sl::draw::SLGraphics::getComposite() { if(npc(log)->check(::poi::util::POILogger::WARN)) { npc(log)->log(::poi::util::POILogger::WARN, new ::java::lang::ObjectArray({static_cast< ::java::lang::Object* >(u"Not implemented"_j)})); } return nullptr; } java::lang::Object* poi::sl::draw::SLGraphics::getRenderingHint(::java::awt::RenderingHints_Key* hintKey) { return npc(_hints)->get(static_cast< ::java::lang::Object* >(hintKey)); } void poi::sl::draw::SLGraphics::setRenderingHint(::java::awt::RenderingHints_Key* hintKey, ::java::lang::Object* hintValue) { npc(_hints)->put(static_cast< ::java::lang::Object* >(hintKey), hintValue); } void poi::sl::draw::SLGraphics::drawGlyphVector(::java::awt::font::GlyphVector* g, float x, float y) { auto glyphOutline = npc(g)->getOutline(x, y); fill(glyphOutline); } java::awt::GraphicsConfiguration* poi::sl::draw::SLGraphics::getDeviceConfiguration() { return npc(npc(::java::awt::GraphicsEnvironment::getLocalGraphicsEnvironment())->getDefaultScreenDevice())->getDefaultConfiguration(); } void poi::sl::draw::SLGraphics::addRenderingHints(::java::util::Map* hints) { npc(this->_hints)->putAll(static_cast< ::java::util::Map* >(hints)); } void poi::sl::draw::SLGraphics::translate(double tx, double ty) { npc(_transform)->translate(tx, ty); } void poi::sl::draw::SLGraphics::drawString(::java::text::AttributedCharacterIterator* iterator, float x, float y) { if(npc(log)->check(::poi::util::POILogger::WARN)) { npc(log)->log(::poi::util::POILogger::WARN, new ::java::lang::ObjectArray({static_cast< ::java::lang::Object* >(u"Not implemented"_j)})); } } bool poi::sl::draw::SLGraphics::hit(::java::awt::Rectangle* rect, ::java::awt::Shape* s, bool onStroke) { if(onStroke) { s = npc(getStroke())->createStrokedShape(s); } s = npc(getTransform())->createTransformedShape(s); return npc(s)->intersects(rect); } java::awt::RenderingHints* poi::sl::draw::SLGraphics::getRenderingHints() { return _hints; } void poi::sl::draw::SLGraphics::setRenderingHints(::java::util::Map* hints) { this->_hints = new ::java::awt::RenderingHints(nullptr); npc(this->_hints)->putAll(static_cast< ::java::util::Map* >(hints)); } bool poi::sl::draw::SLGraphics::drawImage(::java::awt::Image* img, ::java::awt::geom::AffineTransform* xform, ::java::awt::image::ImageObserver* obs) { if(npc(log)->check(::poi::util::POILogger::WARN)) { npc(log)->log(::poi::util::POILogger::WARN, new ::java::lang::ObjectArray({static_cast< ::java::lang::Object* >(u"Not implemented"_j)})); } return false; } bool poi::sl::draw::SLGraphics::drawImage(::java::awt::Image* img, int32_t x, int32_t y, int32_t width, int32_t height, ::java::awt::image::ImageObserver* observer) { if(npc(log)->check(::poi::util::POILogger::WARN)) { npc(log)->log(::poi::util::POILogger::WARN, new ::java::lang::ObjectArray({static_cast< ::java::lang::Object* >(u"Not implemented"_j)})); } return false; } java::awt::Graphics* poi::sl::draw::SLGraphics::create() { try { return java_cast< ::java::awt::Graphics* >(clone()); } catch (::java::lang::CloneNotSupportedException* e) { throw new ::java::lang::RuntimeException(static_cast< ::java::lang::Throwable* >(e)); } } java::awt::FontMetrics* poi::sl::draw::SLGraphics::getFontMetrics(::java::awt::Font* f) { return npc(::java::awt::Toolkit::getDefaultToolkit())->getFontMetrics(f); } void poi::sl::draw::SLGraphics::setXORMode(::java::awt::Color* c1) { if(npc(log)->check(::poi::util::POILogger::WARN)) { npc(log)->log(::poi::util::POILogger::WARN, new ::java::lang::ObjectArray({static_cast< ::java::lang::Object* >(u"Not implemented"_j)})); } } void poi::sl::draw::SLGraphics::setPaintMode() { if(npc(log)->check(::poi::util::POILogger::WARN)) { npc(log)->log(::poi::util::POILogger::WARN, new ::java::lang::ObjectArray({static_cast< ::java::lang::Object* >(u"Not implemented"_j)})); } } void poi::sl::draw::SLGraphics::drawRenderedImage(::java::awt::image::RenderedImage* img, ::java::awt::geom::AffineTransform* xform) { if(npc(log)->check(::poi::util::POILogger::WARN)) { npc(log)->log(::poi::util::POILogger::WARN, new ::java::lang::ObjectArray({static_cast< ::java::lang::Object* >(u"Not implemented"_j)})); } } void poi::sl::draw::SLGraphics::drawRenderableImage(::java::awt::image::renderable::RenderableImage* img, ::java::awt::geom::AffineTransform* xform) { if(npc(log)->check(::poi::util::POILogger::WARN)) { npc(log)->log(::poi::util::POILogger::WARN, new ::java::lang::ObjectArray({static_cast< ::java::lang::Object* >(u"Not implemented"_j)})); } } void poi::sl::draw::SLGraphics::applyStroke(::poi::sl::usermodel::SimpleShape* shape) { if(dynamic_cast< ::java::awt::BasicStroke* >(_stroke) != nullptr) { auto bs = java_cast< ::java::awt::BasicStroke* >(_stroke); npc(shape)->setStrokeStyle(new ::java::lang::ObjectArray({static_cast< ::java::lang::Object* >(::java::lang::Double::valueOf(static_cast< double >(npc(bs)->getLineWidth())))})); auto dash = npc(bs)->getDashArray_(); if(dash != nullptr) { npc(shape)->setStrokeStyle(new ::java::lang::ObjectArray({static_cast< ::java::lang::Object* >(::poi::sl::usermodel::StrokeStyle_LineDash::DASH)})); } } } void poi::sl::draw::SLGraphics::applyPaint(::poi::sl::usermodel::SimpleShape* shape) { if(dynamic_cast< ::java::awt::Color* >(_paint) != nullptr) { npc(shape)->setFillColor(java_cast< ::java::awt::Color* >(_paint)); } } extern java::lang::Class *class_(const char16_t *c, int n); java::lang::Class* poi::sl::draw::SLGraphics::class_() { static ::java::lang::Class* c = ::class_(u"org.apache.poi.sl.draw.SLGraphics", 33); return c; } java::awt::Graphics* poi::sl::draw::SLGraphics::create(int32_t x, int32_t y, int32_t width, int32_t height) { return super::create(x, y, width, height); } void poi::sl::draw::SLGraphics::drawPolygon(::java::awt::Polygon* p) { super::drawPolygon(p); } void poi::sl::draw::SLGraphics::fillPolygon(::java::awt::Polygon* p) { super::fillPolygon(p); } java::awt::Rectangle* poi::sl::draw::SLGraphics::getClipBounds(::java::awt::Rectangle* r) { return super::getClipBounds(r); } java::awt::FontMetrics* poi::sl::draw::SLGraphics::getFontMetrics() { return super::getFontMetrics(); } java::lang::Class* poi::sl::draw::SLGraphics::getClass0() { return class_(); }
37.067278
248
0.671397
pebble2015
a4a3ad70c3c2f5b520fa2905d19efaea8f3b71f7
3,399
cpp
C++
uart.cpp
jekhor/pneumatic-tc-firmware
a532d78a154cc963d98c239c916485f5383f3dcf
[ "CC-BY-3.0" ]
1
2018-10-08T13:28:32.000Z
2018-10-08T13:28:32.000Z
uart.cpp
jekhor/pneumatic-tc-firmware
a532d78a154cc963d98c239c916485f5383f3dcf
[ "CC-BY-3.0" ]
9
2019-08-21T18:07:49.000Z
2019-09-30T19:48:28.000Z
uart.cpp
jekhor/pneumatic-tc-firmware
a532d78a154cc963d98c239c916485f5383f3dcf
[ "CC-BY-3.0" ]
null
null
null
#include <stdio.h> #include "uart.h" #include <HardwareSerial.h> //#define FULL_TERM_SUPPORT FILE uartstream; #define RX_BUFSIZE 80 int uart_putchar(char c, FILE *stream) { if (c == '\n') Serial.write('\r'); Serial.write(c); return 0; } #ifdef FULL_TERM_SUPPORT /* * Receive a character from the UART Rx. * * This features a simple line-editor that allows to delete and * re-edit the characters entered, until either CR or NL is entered. * Printable characters entered will be echoed using uart_putchar(). * * Editing characters: * * . \b (BS) or \177 (DEL) delete the previous character * . ^u kills the entire input buffer * . ^w deletes the previous word * . ^r sends a CR, and then reprints the buffer * . \t will be replaced by a single space * * All other control characters will be ignored. * * The internal line buffer is RX_BUFSIZE (80) characters long, which * includes the terminating \n (but no terminating \0). If the buffer * is full (i. e., at RX_BUFSIZE-1 characters in order to keep space for * the trailing \n), any further input attempts will send a \a to * uart_putchar() (BEL character), although line editing is still * allowed. * * Input errors while talking to the UART will cause an immediate * return of -1 (error indication). Notably, this will be caused by a * framing error (e. g. serial line "break" condition), by an input * overrun, and by a parity error (if parity was enabled and automatic * parity recognition is supported by hardware). * * Successive calls to uart_getchar() will be satisfied from the * internal buffer until that buffer is emptied again. */ int uart_getchar(FILE *stream) { uint8_t c; char *cp, *cp2; static char b[RX_BUFSIZE]; static char *rxp; if (rxp == 0) for (cp = b;;) { while (Serial.available() <= 0) {}; c = Serial.read(); /* behaviour similar to Unix stty ICRNL */ if (c == '\r') c = '\n'; if (c == '\n') { *cp = c; uart_putchar(c, stream); rxp = b; break; } else if (c == '\t') c = ' '; if ((c >= (uint8_t)' ' && c <= (uint8_t)'\x7e') || c >= (uint8_t)'\xa0') { if (cp == b + RX_BUFSIZE - 1) uart_putchar('\a', stream); else { *cp++ = c; uart_putchar(c, stream); } continue; } switch (c) { case 'c' & 0x1f: return -1; case '\b': case '\x7f': if (cp > b) { uart_putchar('\b', stream); uart_putchar(' ', stream); uart_putchar('\b', stream); cp--; } break; case 'r' & 0x1f: uart_putchar('\r', stream); for (cp2 = b; cp2 < cp; cp2++) uart_putchar(*cp2, stream); break; case 'u' & 0x1f: while (cp > b) { uart_putchar('\b', stream); uart_putchar(' ', stream); uart_putchar('\b', stream); cp--; } break; case 'w' & 0x1f: while (cp > b && cp[-1] != ' ') { uart_putchar('\b', stream); uart_putchar(' ', stream); uart_putchar('\b', stream); cp--; } break; } } c = *rxp++; if (c == '\n') rxp = 0; return c; } #else int uart_getchar(FILE *stream) { uint8_t c; while (Serial.available() <= 0) {}; c = Serial.read(); return c; } #endif void setup_uart() { fdev_setup_stream(&uartstream, uart_putchar, uart_getchar, _FDEV_SETUP_RW); stdout = &uartstream; stdin = &uartstream; }
20.72561
76
0.594881
jekhor
a4a3f959d7315d280fa90acc6d0289d2cce27e5e
1,028
cpp
C++
src/Math/PathFinding/IndexedPriorityQueue.cpp
scemino/EnggeFramework
6526bff3c4e6e9ed2cad102f1e3a37d3ce19ef37
[ "MIT" ]
2
2021-11-02T06:47:50.000Z
2021-12-16T09:55:06.000Z
src/Math/PathFinding/IndexedPriorityQueue.cpp
scemino/EnggeFramework
6526bff3c4e6e9ed2cad102f1e3a37d3ce19ef37
[ "MIT" ]
2
2021-02-07T00:04:30.000Z
2021-02-09T23:23:21.000Z
src/Math/PathFinding/IndexedPriorityQueue.cpp
scemino/EnggeFramework
6526bff3c4e6e9ed2cad102f1e3a37d3ce19ef37
[ "MIT" ]
null
null
null
#include <utility> #include "IndexedPriorityQueue.h" namespace ngf { IndexedPriorityQueue::IndexedPriorityQueue(std::vector<float> &keys) : _keys(keys) { } void IndexedPriorityQueue::insert(int index) { _data.push_back(index); reorderUp(); } int IndexedPriorityQueue::pop() { int r = _data[0]; _data[0] = _data[_data.size() - 1]; _data.pop_back(); reorderDown(); return r; } void IndexedPriorityQueue::reorderUp() { if (_data.empty()) return; size_t a = _data.size() - 1; while (a > 0) { if (_keys[_data[a]] >= _keys[_data[a - 1]]) return; int tmp = _data[a]; _data[a] = _data[a - 1]; _data[a - 1] = tmp; a--; } } void IndexedPriorityQueue::reorderDown() { if (_data.empty()) return; for (int a = 0; a < static_cast<int>(_data.size() - 1); a++) { if (_keys[_data[a]] <= _keys[_data[a + 1]]) return; int tmp = _data[a]; _data[a] = _data[a + 1]; _data[a + 1] = tmp; } } bool IndexedPriorityQueue::isEmpty() { return _data.empty(); } }
20.156863
68
0.600195
scemino
a4ac6e100fdc98dd876da0fa982d28bf0ac138c8
12,264
cpp
C++
implementations/ugene/src/corelibs/U2View/src/ov_assembly/AssemblyConsensusArea.cpp
r-barnes/sw_comparison
1ac2c9cc10a32badd6b8fb1e96516c97f7800176
[ "BSD-Source-Code" ]
null
null
null
implementations/ugene/src/corelibs/U2View/src/ov_assembly/AssemblyConsensusArea.cpp
r-barnes/sw_comparison
1ac2c9cc10a32badd6b8fb1e96516c97f7800176
[ "BSD-Source-Code" ]
null
null
null
implementations/ugene/src/corelibs/U2View/src/ov_assembly/AssemblyConsensusArea.cpp
r-barnes/sw_comparison
1ac2c9cc10a32badd6b8fb1e96516c97f7800176
[ "BSD-Source-Code" ]
null
null
null
/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2020 UniPro <ugene@unipro.ru> * http://ugene.net * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "AssemblyConsensusArea.h" #include <QFileInfo> #include <QMouseEvent> #include <QPainter> #include <U2Algorithm/AssemblyConsensusAlgorithmRegistry.h> #include <U2Algorithm/BuiltInAssemblyConsensusAlgorithms.h> #include <U2Core/BaseDocumentFormats.h> #include <U2Core/DocumentModel.h> #include <U2Core/GUrlUtils.h> #include <U2Core/QObjectScopedPointer.h> #include <U2Core/U2AssemblyUtils.h> #include <U2Core/U2SafePoints.h> #include "AssemblyBrowser.h" #include "AssemblyConsensusTask.h" #include "ExportConsensusDialog.h" #include "ExportConsensusTask.h" #include "ExportConsensusVariationsDialog.h" #include "ExportConsensusVariationsTask.h" namespace U2 { AssemblyConsensusArea::AssemblyConsensusArea(AssemblyBrowserUi *ui) : AssemblySequenceArea(ui, AssemblyConsensusAlgorithm::EMPTY_CHAR), consensusAlgorithmMenu(NULL), consensusAlgorithm(NULL), canceled(false) { setToolTip(tr("Consensus sequence")); setObjectName("Consensus area"); connect(&consensusTaskRunner, SIGNAL(si_finished()), SLOT(sl_consensusReady())); AssemblyConsensusAlgorithmRegistry *registry = AppContext::getAssemblyConsensusAlgorithmRegistry(); QString defaultId = BuiltInAssemblyConsensusAlgorithms::DEFAULT_ALGO; AssemblyConsensusAlgorithmFactory *f = registry->getAlgorithmFactory(defaultId); SAFE_POINT(f != NULL, QString("consensus algorithm factory %1 not found").arg(defaultId), ); consensusAlgorithm = QSharedPointer<AssemblyConsensusAlgorithm>(f->createAlgorithm()); setDiffCellRenderer(); createContextMenu(); } void AssemblyConsensusArea::createContextMenu() { contextMenu = new QMenu(this); contextMenu->addMenu(getConsensusAlgorithmMenu()); QAction *exportCoverage = contextMenu->addAction(tr("Export coverage...")); exportCoverage->setObjectName("Export coverage"); connect(exportCoverage, SIGNAL(triggered()), browser, SLOT(sl_exportCoverage())); QAction *exportAction = contextMenu->addAction(tr("Export consensus...")); connect(exportAction, SIGNAL(triggered()), SLOT(sl_exportConsensus())); exportConsensusVariationsAction = contextMenu->addAction(tr("Export consensus variations...")); connect(exportConsensusVariationsAction, SIGNAL(triggered()), SLOT(sl_exportConsensusVariations())); exportConsensusVariationsAction->setDisabled(true); diffAction = contextMenu->addAction(tr("Show difference from reference")); diffAction->setCheckable(true); diffAction->setChecked(true); connect(diffAction, SIGNAL(toggled(bool)), SLOT(sl_drawDifferenceChanged(bool))); } bool AssemblyConsensusArea::canDrawSequence() { return !getModel()->isEmpty(); } QByteArray AssemblyConsensusArea::getSequenceRegion(U2OpStatus &os) { Q_UNUSED(os); return lastResult.consensus; } // If required region is not fully included in cache, other positions are filled with AssemblyConsensusAlgorithm::EMPTY_CHAR static ConsensusInfo getPart(ConsensusInfo cache, U2Region region) { ConsensusInfo result; result.region = region; result.algorithmId = cache.algorithmId; result.consensus = QByteArray(region.length, AssemblyConsensusAlgorithm::EMPTY_CHAR); if (!cache.region.isEmpty() && cache.region.intersects(region)) { U2Region intersection = cache.region.intersect(region); SAFE_POINT(!intersection.isEmpty(), "consensus cache: intersection cannot be empty, possible race condition?", result); int offsetInCache = intersection.startPos - cache.region.startPos; int offsetInResult = intersection.startPos - region.startPos; memcpy(result.consensus.data() + offsetInResult, cache.consensus.constData() + offsetInCache, intersection.length); } return result; } void AssemblyConsensusArea::launchConsensusCalculation() { if (areCellsVisible()) { U2Region visibleRegion = getVisibleRegion(); previousRegion = visibleRegion; if (cache.region.contains(visibleRegion) && cache.algorithmId == consensusAlgorithm->getId()) { lastResult = getPart(cache, visibleRegion); consensusTaskRunner.cancel(); } else { AssemblyConsensusTaskSettings settings; settings.region = visibleRegion; settings.model = getModel(); settings.consensusAlgorithm = consensusAlgorithm; consensusTaskRunner.run(new AssemblyConsensusTask(settings)); } } canceled = false; sl_redraw(); } void AssemblyConsensusArea::sl_offsetsChanged() { if (areCellsVisible() && getVisibleRegion() != previousRegion) { launchConsensusCalculation(); } } void AssemblyConsensusArea::sl_zoomPerformed() { launchConsensusCalculation(); } void AssemblyConsensusArea::drawSequence(QPainter &p) { if (areCellsVisible()) { U2Region visibleRegion = getVisibleRegion(); if (!consensusTaskRunner.isIdle() || canceled) { if (!cache.region.isEmpty() && cache.region.intersects(visibleRegion)) { // Draw a known part while others are still being calculated // To do it, temporarily substitute lastResult with values from cache, then return it back ConsensusInfo storedLastResult = lastResult; lastResult = getPart(cache, visibleRegion); AssemblySequenceArea::drawSequence(p); p.fillRect(rect(), QColor(0xff, 0xff, 0xff, 0x7f)); lastResult = storedLastResult; } QString message = consensusTaskRunner.isIdle() ? tr("Consensus calculation canceled") : tr("Calculating consensus..."); p.drawText(rect(), Qt::AlignCenter, message); } else if (lastResult.region == visibleRegion && lastResult.algorithmId == consensusAlgorithm->getId()) { AssemblySequenceArea::drawSequence(p); } else if (cache.region.contains(visibleRegion) && cache.algorithmId == consensusAlgorithm->getId()) { lastResult = getPart(cache, visibleRegion); AssemblySequenceArea::drawSequence(p); } else { launchConsensusCalculation(); } } } QMenu *AssemblyConsensusArea::getConsensusAlgorithmMenu() { if (consensusAlgorithmMenu == NULL) { consensusAlgorithmMenu = new QMenu(tr("Consensus algorithm")); AssemblyConsensusAlgorithmRegistry *registry = AppContext::getAssemblyConsensusAlgorithmRegistry(); QList<AssemblyConsensusAlgorithmFactory *> factories = registry->getAlgorithmFactories(); foreach (AssemblyConsensusAlgorithmFactory *f, factories) { QAction *action = consensusAlgorithmMenu->addAction(f->getName()); action->setCheckable(true); action->setChecked(f == consensusAlgorithm->getFactory()); action->setData(f->getId()); connect(consensusAlgorithmMenu, SIGNAL(triggered(QAction *)), SLOT(sl_consensusAlgorithmChanged(QAction *))); algorithmActions << action; } } return consensusAlgorithmMenu; } QList<QAction *> AssemblyConsensusArea::getAlgorithmActions() { // ensure that menu is created getConsensusAlgorithmMenu(); return algorithmActions; } void AssemblyConsensusArea::sl_consensusAlgorithmChanged(QAction *action) { QString id = action->data().toString(); AssemblyConsensusAlgorithmRegistry *registry = AppContext::getAssemblyConsensusAlgorithmRegistry(); AssemblyConsensusAlgorithmFactory *f = registry->getAlgorithmFactory(id); SAFE_POINT(f != NULL, QString("cannot change consensus algorithm, invalid id %1").arg(id), ); consensusAlgorithm = QSharedPointer<AssemblyConsensusAlgorithm>(f->createAlgorithm()); foreach (QAction *a, consensusAlgorithmMenu->actions()) { a->setChecked(a == action); } launchConsensusCalculation(); } void AssemblyConsensusArea::sl_drawDifferenceChanged(bool drawDifference) { if (drawDifference) { setDiffCellRenderer(); } else { setNormalCellRenderer(); } sl_redraw(); } void AssemblyConsensusArea::mousePressEvent(QMouseEvent *e) { if (e->button() == Qt::RightButton) { updateActions(); contextMenu->exec(QCursor::pos()); } } void AssemblyConsensusArea::sl_consensusReady() { if (consensusTaskRunner.isIdle()) { if (consensusTaskRunner.isSuccessful()) { cache = lastResult = consensusTaskRunner.getResult(); canceled = false; } else { canceled = true; } sl_redraw(); } } void AssemblyConsensusArea::sl_exportConsensus() { const DocumentFormat *defaultFormat = BaseDocumentFormats::get(BaseDocumentFormats::FASTA); SAFE_POINT(defaultFormat != NULL, "Internal: couldn't find default document format for consensus", ); ExportConsensusTaskSettings settings; settings.region = getModel()->getGlobalRegion(); settings.model = getModel(); settings.consensusAlgorithm = consensusAlgorithm; settings.saveToFile = true; settings.formatId = defaultFormat->getFormatId(); settings.seqObjName = getModel()->getAssembly().visualName + "_consensus"; settings.addToProject = true; settings.keepGaps = true; GUrl url(U2DbiUtils::ref2Url(getModel()->getDbiConnection().dbi->getDbiRef())); settings.fileName = GUrlUtils::getNewLocalUrlByFormat(url, getModel()->getAssembly().visualName, settings.formatId, "_consensus"); QObjectScopedPointer<ExportConsensusDialog> dlg = new ExportConsensusDialog(this, settings, getVisibleRegion()); const int dialogResult = dlg->exec(); CHECK(!dlg.isNull(), ); if (QDialog::Accepted == dialogResult) { settings = dlg->getSettings(); AppContext::getTaskScheduler()->registerTopLevelTask(new ExportConsensusTask(settings)); } } void AssemblyConsensusArea::sl_exportConsensusVariations() { const DocumentFormat *defaultFormat = BaseDocumentFormats::get(BaseDocumentFormats::SNP); SAFE_POINT(defaultFormat != NULL, "Internal: couldn't find default document format for consensus variations", ); ExportConsensusVariationsTaskSettings settings; settings.region = getModel()->getGlobalRegion(); settings.model = getModel(); settings.consensusAlgorithm = consensusAlgorithm; settings.formatId = defaultFormat->getFormatId(); settings.seqObjName = getModel()->getAssembly().visualName; settings.addToProject = true; settings.keepGaps = true; settings.mode = Mode_Variations; settings.refSeq = getModel()->getRefereneceEntityRef(); GUrl url(U2DbiUtils::ref2Url(getModel()->getDbiConnection().dbi->getDbiRef())); settings.fileName = GUrlUtils::getNewLocalUrlByFormat(url, getModel()->getAssembly().visualName, settings.formatId, ""); QObjectScopedPointer<ExportConsensusVariationsDialog> dlg = new ExportConsensusVariationsDialog(this, settings, getVisibleRegion()); const int dialogResult = dlg->exec(); CHECK(!dlg.isNull(), ); if (QDialog::Accepted == dialogResult) { settings = dlg->getSettings(); AppContext::getTaskScheduler()->registerTopLevelTask(new ExportConsensusVariationsTask(settings)); } } void AssemblyConsensusArea::updateActions() { if (!getModel()->hasReference()) { exportConsensusVariationsAction->setDisabled(true); } else { exportConsensusVariationsAction->setDisabled(false); } } } // namespace U2
40.88
145
0.718118
r-barnes
a4ad14bb9b65c254cb98144af9f12c8d2ba453cb
4,277
cpp
C++
WOF2/src/WOF/match/spatialQuery/FootballerBallInterceptManager.cpp
jadnohra/World-Of-Football
fc4c9dd23e0b2d8381ae8f62b1c387af7f28fcfc
[ "MIT" ]
3
2018-12-02T14:09:22.000Z
2021-11-22T07:14:05.000Z
WOF2/src/WOF/match/spatialQuery/FootballerBallInterceptManager.cpp
jadnohra/World-Of-Football
fc4c9dd23e0b2d8381ae8f62b1c387af7f28fcfc
[ "MIT" ]
1
2018-12-03T22:54:38.000Z
2018-12-03T22:54:38.000Z
WOF2/src/WOF/match/spatialQuery/FootballerBallInterceptManager.cpp
jadnohra/World-Of-Football
fc4c9dd23e0b2d8381ae8f62b1c387af7f28fcfc
[ "MIT" ]
2
2020-09-22T21:04:14.000Z
2021-05-24T09:43:28.000Z
#include "FootballerBallInterceptManager.h" #include "../inc/Scene.h" #include "../Match.h" #include "../DataTypes.h" namespace WOF { namespace match { FootballerBallInterceptManager::FootballerBallInterceptManager() { } void FootballerBallInterceptManager::init(Match& match) { if (mMatch.isValid()) { assrt(false); } mMatch = &match; { BallSimulation& simul = mSimul; simul.enableSyncMode(true); simul.enableSimul(true); simul.setupUsingMatch(match); } } void FootballerBallInterceptManager::load(Match& match, BufferString& tempStr, DataChunk& mainChunk, CoordSysConv* pConv) { SoftRef<DataChunk> chunk = mainChunk.getChild(L"ballPathIntercept"); if (chunk.isValid()) { mSimul.loadConfig(mMatch, tempStr, chunk, pConv); } } void FootballerBallInterceptManager::frameMove(Match& match, const Time& time) { mSimul.updateSync(mMatch->getBall()); } void FootballerBallInterceptManager::render(Renderer& renderer, const bool& flagExtraRenders, RenderPassEnum pass) { if (pass == RP_Normal) { /* if (mMatch->mTweakShowPitchBallBounceMarker && mBallPitchBounceMarker.isValid() && mSimul.isValidSync()) { const Vector3& ballPos = mMatch->getBall().getPos(); if (ballPos.el[Scene_Up] >= mMatch->mTweakPitchBallBounceMarkerHeight) { Time time = mMatch->getClock().getTime(); for (BallSimulation::Index i = mSimul.getSyncFlowCollSampleIndex(); i < mSimul.getCollSampleCount(); ++i) { const BallSimulation::CollSample& collSample = mSimul.getCollSample(i); if (collSample.time >= time && collSample.collider.isValid() && collSample.collider->objectType == Node_Pitch) { mBallPitchBounceMarker->mTransformLocal.setPosition(collSample.pos); mBallPitchBounceMarker->nodeMarkDirty(); mBallPitchBounceMarker->render(renderer, true, flagExtraRenders, pass); break; } } } } */ if (mMatch->mTweakShowPitchBallBounceMarker && mSimul.isValidSync()) { RenderSprite& sprite = mMatch->getBallPitchMarkerSprite(); const Vector3& ballPos = mMatch->getBall().getPos(); if (ballPos.el[Scene_Up] >= mMatch->mTweakPitchBallBounceMarkerHeight) { Time time = mMatch->getClock().getTime(); for (BallSimulation::Index i = mSimul.getSyncFlowCollSampleIndex(); i < mSimul.getCollSampleCount(); ++i) { const BallSimulation::CollSample& collSample = mSimul.getCollSample(i); if (collSample.time >= time && collSample.collider.isValid() && collSample.collider->objectType == Node_Pitch) { sprite.transform3D().setPosition(collSample.pos); sprite.render3D(renderer); break; } } } } if (flagExtraRenders) mSimul.render(renderer, true); } } /* bool FootballerBallInterceptManager::requestUpdate(Match& match, Footballer& footballer, const Time& time) { //limit this and delay some requests for performance. update(match, footballer, time); return true; } bool FootballerBallInterceptManager::update(Match& match, Footballer& footballer, const Time& time) { PathIntercept& pathIntercept = footballer.getBallPathIntercept(); SoftPtr<BallSimulation::Index> sampleIndex; if (pathIntercept.simulID == mAnalyzedSimul.getSimulID()) { if (pathIntercept.analysisTime == time) { return pathIntercept.type == PI_InterceptorWait; } else { if (pathIntercept.type == PI_InterceptorWait) sampleIndex = &pathIntercept.sampleIndex; } } return mAnalyzedSimul.updateShortestTimeInterceptState(match, footballer, mSimul, time, sampleIndex); } bool FootballerBallInterceptManager::isStillIntercepting(Match& match, Footballer& footballer, const Time& time) { PathIntercept& pathIntercept = footballer.getBallPathIntercept(); if (pathIntercept.simulID == mAnalyzedSimul.getSimulID()) { if (pathIntercept.type == PI_InterceptorWait && pathIntercept.expiryTime >= time) { return mAnalyzedSimul.getIntersectionTime(footballer, mAnalyzedSimul.getSimulID(), pathIntercept.sampleIndex, dref(mAnalyzedSimul.getSample(pathIntercept.sampleIndex)), pathIntercept, mAnalyzedSimul.getSimul()->getStartTime(), time, true); } } return false; } */ } }
28.138158
243
0.707271
jadnohra
a4af7ba24ee529069fe724f5be8af260108f6259
24,308
cpp
C++
Source/WebCore/platform/graphics/mg/GraphicsContextMg.cpp
VincentWei/mdolphin-core
48ffdcf587a48a7bb4345ae469a45c5b64ffad0e
[ "Apache-2.0" ]
6
2017-05-31T01:46:45.000Z
2018-06-12T10:53:30.000Z
Source/WebCore/platform/graphics/mg/GraphicsContextMg.cpp
FMSoftCN/mdolphin-core
48ffdcf587a48a7bb4345ae469a45c5b64ffad0e
[ "Apache-2.0" ]
null
null
null
Source/WebCore/platform/graphics/mg/GraphicsContextMg.cpp
FMSoftCN/mdolphin-core
48ffdcf587a48a7bb4345ae469a45c5b64ffad0e
[ "Apache-2.0" ]
2
2017-07-17T06:02:42.000Z
2018-09-19T10:08:38.000Z
/* ** $Id: GraphicsContextMg.cpp 24 2010-09-26 11:21:19Z lijiangwei $ ** ** GraphicsContextMg.cpp: graphics context implements file. ** ** Copyright (C) 2003 ~ 2010 Beijing Feynman Software Technology Co., Ltd. ** ** All rights reserved by Feynman Software. ** ** Current maintainer: lvlei ** ** Create date: 2010-06-01 */ #include "minigui.h" #include "config.h" #include <wtf/MathExtras.h> #include "Path.h" #include "AffineTransform.h" #include "GraphicsContext.h" #include "FloatRect.h" #include "Font.h" #include "FontData.h" #include "IntRect.h" #include "NotImplemented.h" #if ENABLE(CAIRO_MG) #include <cairo.h> #include <cairo-minigui.h> #include "ContextShadow.h" #include "GraphicsContextCairo.h" #endif namespace WebCore { #ifndef MEMDC_FLAG_SRCPIXELALPHA #define MEMDC_FLAG_SRCPIXELALPHA MEMDC_FLAG_NONE #endif class GraphicsContextPlatformPrivate { public: GraphicsContextPlatformPrivate(); ~GraphicsContextPlatformPrivate(); Vector<AffineTransform> stack; AffineTransform matrix; HDC viewdc; HDC context; Vector<HDC> layers; #if ENABLE(CAIRO_MG) ContextShadow shadow; Vector<ContextShadow> shadowStack; #endif }; static inline void setPenColor(HDC dc, const Color& col) { SetPenColor (dc, RGBA2Pixel(dc, (BYTE)col.red(), (BYTE)col.green(), (BYTE)col.blue(), (BYTE)col.alpha())); } static inline void setBrushColor(HDC dc, const Color& col) { SetBrushColor (dc, RGBA2Pixel(dc, (BYTE)col.red(), (BYTE)col.green(), (BYTE)col.blue(), (BYTE)col.alpha())); } // A fillRect helper static inline void fillRectSourceOver(HDC dc, const FloatRect& rect, const Color& col) { #ifdef SHOW_BUG4317 setBrushColor(dc, col); SetRasterOperation (dc, (col.alpha() == 0xFF) ? ROP_SET : ROP_AND); FillBox (dc, (int)rect.x(), (int)rect.y(), (int)rect.width(), (int)rect.height()); SetRasterOperation (dc, ROP_SET); #else /* * Becareful! if with or height <=0 , the FillBox think the width or height is the whole DC */ if ((int)rect.width()<=0 || (int)rect.height() <= 0) return; if (col.alpha() == 0xFF) { // printf("---- fill rect=%d,%d,%d,%d, color=%d,%d,%d\n",(int)rect.x(), (int)rect.y(), (int)rect.width(), (int)rect.height(), (BYTE)col.red(),(BYTE)col.green(), (BYTE)col.blue()); setBrushColor (dc, col); SetRasterOperation (dc, ROP_SET); FillBox (dc, (int)rect.x(), (int)rect.y(), (int)rect.width(), (int)rect.height()); } else { int width = (int)rect.width(); int x = (int)rect.x(); int y = (int)rect.y(); HDC memdc = CreateCompatibleDCEx (dc, width, 1); setBrushColor (memdc, col); FillBox (memdc, 0, 0, width, 1); SetMemDCAlpha (memdc, MEMDC_FLAG_SRCPIXELALPHA, 255); for (int i = 0; i < (int)rect.height(); i++) { BitBlt (memdc, 0, 0, width, 1, dc, x, y++, 0); } DeleteMemDC (memdc); } #endif } GraphicsContextPlatformPrivate::GraphicsContextPlatformPrivate() : viewdc(0) , context(0) { } GraphicsContextPlatformPrivate::~GraphicsContextPlatformPrivate() { } void GraphicsContext::platformInit(PlatformGraphicsContext* context) { m_data = new GraphicsContextPlatformPrivate; if (context) { m_data->viewdc = *context; m_data->context = m_data->viewdc; } } void GraphicsContext::platformDestroy() { delete m_data; } HDC *GraphicsContext::platformContext() const { return &m_data->context; } #if ENABLE(CAIRO_MG) GraphicsContextCairo* GraphicsContext::newCairoContext(GraphicsContext *context) { if (context && !context->isCairoCanvas()) { HDC hdc = *(HDC* )context->platformContext(); RefPtr<cairo_surface_t> mgSurface = cairo_minigui_surface_create(hdc); RefPtr<cairo_t> mgCr = adoptRef(cairo_create(mgSurface.get())); GraphicsContextCairo *cairoContext = new GraphicsContextCairo(mgCr.get()); if (cairoContext) { if (context->fillGradient()) { cairoContext->setFillGradient(context->fillGradient()); } else if (context->fillPattern()) { cairoContext->setFillPattern(context->fillPattern()); } else { cairoContext->setFillColor(context->fillColor(), ColorSpaceDeviceRGB); } cairoContext->setCTM(context->getCTM()); } return cairoContext; } return NULL; } void GraphicsContext::deleteCairoContext(GraphicsContextCairo *context) { if (context && context->isCairoCanvas()) delete context; } #endif void GraphicsContext::savePlatformState() { SaveDC (m_data->context); m_data->stack.append(m_data->matrix); #if ENABLE(CAIRO_MG) m_data->shadowStack.append(m_data->shadow); #endif } void GraphicsContext::restorePlatformState() { #if ENABLE(CAIRO_MG) if (m_data->shadowStack.isEmpty()) m_data->shadow = ContextShadow(); else { m_data->shadow = m_data->shadowStack.last(); m_data->shadowStack.removeLast(); } #endif m_data->matrix = m_data->stack.last(); m_data->stack.removeLast(); RestoreDC (m_data->context, -1); } // Draws a filled rectangle with a stroked border. void GraphicsContext::drawRect(const IntRect& r) { if (paintingDisabled()) return; IntRect rect = m_data->matrix.mapRect(r); HDC hdc = m_data->context; if (fillColor().alpha()) fillRectSourceOver(hdc, rect, fillColor()); if (strokeStyle() != NoStroke) { setPenColor(hdc, strokeColor()); FloatRect r(rect); r.inflate(-.5f); SetPenWidth (hdc, static_cast<int>(strokeThickness())); Rectangle(hdc, (int)r.x(), (int)r.y(), (int)(r.x()+r.width()), (int)(r.y()+r.height())); } } // This is only used to draw borders. void GraphicsContext::drawLine(const IntPoint& po1, const IntPoint& po2) { if (paintingDisabled()) return; IntPoint point1 = m_data->matrix.mapPoint(po1); IntPoint point2 = m_data->matrix.mapPoint(po2); HDC hdc = m_data->context; StrokeStyle penStyle = strokeStyle(); if (penStyle == NoStroke) return; SaveDC(hdc); float width = strokeThickness(); if (width < 1) width = 1; FloatPoint p1 = point1; FloatPoint p2 = point2; bool isVerticalLine = (p1.x() == p2.x()); adjustLineToPixelBoundaries(p1, p2, width, penStyle); SetPenWidth (hdc, static_cast<int>(width)); int patWidth = 0; switch (penStyle) { case NoStroke: case SolidStroke: SetPenType( hdc, PT_SOLID); break; case DottedStroke: patWidth = static_cast<int>(width); SetPenType( hdc, PT_ON_OFF_DASH); break; case DashedStroke: patWidth = 3*static_cast<int>(width); SetPenType( hdc, PT_ON_OFF_DASH); break; } setPenColor (hdc, strokeColor()); //to set antialias to false if (patWidth) { // Do a rect fill of our endpoints. This ensures we always have the // appearance of being a border. We then draw the actual dotted/dashed line. if (isVerticalLine) { fillRectSourceOver(hdc, FloatRect(p1.x()-width/2, p1.y()-width, width, width), strokeColor()); fillRectSourceOver(hdc, FloatRect(p2.x()-width/2, p2.y(), width, width), strokeColor()); } else { fillRectSourceOver(hdc, FloatRect(p1.x()-width, p1.y()-width/2, width, width), strokeColor()); fillRectSourceOver(hdc, FloatRect(p2.x(), p2.y()-width/2, width, width), strokeColor()); } // Example: 80 pixels with a width of 30 pixels. // Remainder is 20. The maximum pixels of line we could paint // will be 50 pixels. int distance = (isVerticalLine ? (point2.y() - point1.y()) : (point2.x() - point1.x())) - 2*static_cast<int>(width); int remainder = distance%patWidth; int coverage = distance-remainder; int numSegments = coverage/patWidth; float patternOffset = 0; // Special case 1px dotted borders for speed. if (patWidth == 1) patternOffset = 1.0; else { bool evenNumberOfSegments = numSegments%2 == 0; if (remainder) evenNumberOfSegments = !evenNumberOfSegments; if (evenNumberOfSegments) { if (remainder) { patternOffset += patWidth - remainder; patternOffset += remainder/2; } else patternOffset = patWidth/2; } else if (!evenNumberOfSegments) { if (remainder) patternOffset = (patWidth - remainder)/2; } } unsigned char pattern[2] = {(unsigned char)patWidth, (unsigned char)patWidth}; SetPenDashes( hdc, (int)patternOffset, pattern, 2); } LineEx(hdc, (int)p1.x(), (int)p1.y(), (int)p2.x(), (int)p2.y()); RestoreDC(hdc, -1); } // This method is only used to draw the little circles used in lists. void GraphicsContext::drawEllipse(const IntRect& r) { if (paintingDisabled()) return; IntRect rect = m_data->matrix.mapRect(r); HDC hdc = m_data->context; SaveDC(hdc); if (fillColor().alpha()) { setBrushColor(hdc, fillColor()); //FIXME: should be alpha blend FillEllipse (hdc, rect.x()+rect.width()/2, rect.y()+rect.height()/2, rect.width()/2, rect.height()/2); } if (strokeStyle() != NoStroke) { setPenColor(hdc, strokeColor()); SetPenWidth (hdc, strokeThickness()); Ellipse(hdc, rect.x()+rect.width()/2, rect.y()+rect.height()/2, rect.width()/2, rect.height()/2); } RestoreDC(hdc, -1); } void GraphicsContext::strokeArc(const IntRect& r, int startAngle, int angleSpan) { if (paintingDisabled()) return; IntRect rc = m_data->matrix.mapRect(r); HDC hdc = m_data->context; SaveDC(hdc); if (strokeStyle() != NoStroke) { setPenColor(hdc, strokeColor()); SetPenWidth(hdc, strokeThickness()); ArcEx(hdc, rc.x(), rc.y(), rc.width(), rc.height(), startAngle * 64, angleSpan * 64); } RestoreDC(hdc, -1); } void GraphicsContext::drawConvexPolygon(size_t numPoints, const FloatPoint* points, bool shouldAntialias) { if (paintingDisabled()) return; if (numPoints <= 1) return; HDC hdc = m_data->context; POINT *sp = new POINT[numPoints]; if (!sp) return; SaveDC(hdc); for (size_t i = 0; i < numPoints; i++) { double x, y; m_data->matrix.map(points[i].x(), points[i].y(), x, y); sp[i].x = (int)lround(x); sp[i].y = (int)lround(y); } if (fillColor().alpha()) { setBrushColor(hdc, fillColor()); FillPolygon (hdc, sp, (int)numPoints); } if (strokeStyle() != NoStroke) { setPenColor(hdc, strokeColor()); SetPenWidth(hdc, static_cast<int>(strokeThickness())); PolyLineEx (hdc, sp, static_cast<int>(numPoints)); } RestoreDC(hdc, -1); delete [] sp; } void GraphicsContext::fillRect(const FloatRect& r) { if (paintingDisabled()) return; fillRect(r, m_state.fillColor, ColorSpaceDeviceRGB); } void GraphicsContext::fillRect(const FloatRect& r, const Color& color, ColorSpace) { if (paintingDisabled()) return; FloatRect rect = m_data->matrix.mapRect(r); #if ENABLE(CAIRO_MG) if (hasShadow()) { GraphicsContextCairo* context = newCairoContext(this); m_data->shadow.drawRectShadow(context, enclosingIntRect(rect)); deleteCairoContext(context); } #endif if (color.alpha()) fillRectSourceOver(m_data->context, rect, color); } void GraphicsContext::clip(const FloatRect& r) { if (paintingDisabled()) return; IntRect rect = enclosingIntRect(r); HDC hdc = m_data->context; RECT rc = m_data->matrix.mapRect(rect); ClipRectIntersect(hdc, &rc); } void GraphicsContext::drawLineForText(const FloatPoint& origin, float width, bool printing) { if (paintingDisabled()) return; StrokeStyle savedStrokeStyle = strokeStyle(); setStrokeStyle(SolidStroke); //IntPoint origin = point; //origin.setY(point.y()-1); FloatPoint endPoint = origin + FloatSize(width, 0); // FIXME: Loss of precision here. Might consider rounding. drawLine(IntPoint(origin.x(), origin.y()), IntPoint(endPoint.x(), endPoint.y())); setStrokeStyle(savedStrokeStyle); } void GraphicsContext::translate(float x, float y) { if (paintingDisabled()) return; m_data->matrix.translate((float)x, (float)y); } void GraphicsContext::strokeRect(const FloatRect& rect, float width) { //This function paints a line of the specified width along the path of a rectangle. //The line surrounds the center of the path, with half of the total width on either side. //As a side effect when you call this function, Quartz clears the current path. HDC hdc = m_data->context; unsigned int oldwidth = SetPenWidth(hdc, width); IntRect intrect((int)rect.x(), (int)rect.y(), (int)rect.width(), (int)rect.height()); drawRect(intrect); (void)SetPenWidth(hdc, oldwidth); } void GraphicsContext::setPlatformStrokeThickness(float width) { if (paintingDisabled()) return; HDC hdc = m_data->context; (void)SetPenWidth(hdc, width); } void GraphicsContext::setLineCap(LineCap cap) { if (paintingDisabled()) return; HDC hdc = m_data->context; (void)SetPenCapStyle(hdc, cap); } void GraphicsContext::setLineJoin(LineJoin join) { if (paintingDisabled()) return; HDC hdc = m_data->context; (void)SetPenJoinStyle(hdc, join); } void GraphicsContext::setAlpha(float opacity) { if (paintingDisabled()) return; HDC hdc = m_data->context; SetMemDCAlpha(hdc, MEMDC_FLAG_SRCALPHA, (BYTE)(opacity*255)); } void GraphicsContext::clip(const Path& path) { if (paintingDisabled()) return; clip(enclosingIntRect(path.boundingRect())); } void GraphicsContext::scale(const FloatSize& size) { m_data->matrix.scale (size.width(), size.height()); } FloatRect GraphicsContext::roundToDevicePixels(const FloatRect& r, RoundingMode) { FloatRect frect = m_data->matrix.mapRect(r); FloatRect result; POINT p; p.x = (int)frect.x(); p.y = (int)frect.y(); HDC hdc = m_data->context; LPtoDP (hdc, &p); p.x = (int)roundf((float)p.x); p.y = (int)roundf((float)p.y); DPtoLP (hdc, &p); result.setX((float)p.x); result.setY((float)p.y); p.x = (int)(frect.x()+frect.width()); p.y = (int)(frect.y()+frect.height()); LPtoDP (hdc, &p); p.x = (int)roundf((float)p.x); p.y = (int)roundf((float)p.y); DPtoLP (hdc, &p); result.setWidth((float)(p.x - result.x())); result.setHeight((float)(p.y - result.y())); return result; } void GraphicsContext::setPlatformFillColor(const Color& fill, ColorSpace) { if (paintingDisabled()) return; HDC hdc = m_data->context; setBrushColor(hdc, fill); } void GraphicsContext::setPlatformStrokeColor(const Color& color, ColorSpace) { if (paintingDisabled()) return; HDC hdc = m_data->context; setPenColor(hdc, color); } AffineTransform GraphicsContext::getCTM() const { return AffineTransform(m_data->matrix.a(), m_data->matrix.b(), m_data->matrix.c(), m_data->matrix.d(), m_data->matrix.e(), m_data->matrix.f()); } void GraphicsContext::setCTM(const AffineTransform & matrix) { m_data->matrix = matrix; } //not implements void GraphicsContext::strokePath(const Path& path) { notImplemented(); } void GraphicsContext::fillPath (const Path& path) { notImplemented(); } void GraphicsContext::clipOut(const IntRect& rect) { HDC hdc = m_data->context; RECT rc = m_data->matrix.mapRect(rect); ExcludeClipRect(hdc, &rc); } static void fillRoundCorner(HDC hdc, RECT& clipRect, RECT &rectWin, const IntSize& size, AffineTransform& matrix) { IntRect cornerRect(0, 0, size.width(), size.height()); cornerRect = matrix.mapRect(cornerRect); int rw = cornerRect.width(); int rh = cornerRect.height(); rw = rw > (RECTW(rectWin)>>1) ? (RECTW(rectWin)>>1) : rw; rh = rh > (RECTH(rectWin)>>1) ? (RECTH(rectWin)>>1) : rh; SaveDC(hdc); ClipRectIntersect(hdc, &clipRect); RoundRect(hdc, rectWin.left, rectWin.top, rectWin.right, rectWin.bottom, rw, rh); RestoreDC(hdc, -1); } void GraphicsContext::fillRoundedRect(const IntRect& r, const IntSize& topLeft, const IntSize& topRight, const IntSize& bottomLeft, const IntSize& bottomRight, const Color& color, ColorSpace space) { #if ENABLE(CAIRO_MG) GraphicsContextCairo* context = newCairoContext(this); context->fillRoundedRect(r, topLeft, topRight, bottomLeft, bottomRight, color, space); deleteCairoContext(context); #else IntRect dstRect = r; dstRect = m_data->matrix.mapRect(dstRect); RECT rectWin = dstRect; IntPoint centerPoint = IntPoint(rectWin.left + (RECTW(rectWin)>>1), rectWin.top + (RECTH(rectWin)>>1)); int centerX = centerPoint.x(); int centerY = centerPoint.y(); HDC hdc = m_data->context; setBrushColor (hdc, color); // Draw top left half RECT clipRect(rectWin); clipRect.right = centerX; clipRect.bottom = centerY; fillRoundCorner(hdc, clipRect, rectWin, topLeft, m_data->matrix); // Draw top right clipRect = rectWin; clipRect.left = centerX; clipRect.bottom = centerY; fillRoundCorner(hdc, clipRect, rectWin, topRight, m_data->matrix); // Draw bottom left clipRect = rectWin; clipRect.right = centerX; clipRect.top = centerY; fillRoundCorner(hdc, clipRect, rectWin, bottomLeft, m_data->matrix); // Draw bottom right clipRect = rectWin; clipRect.left = centerX; clipRect.top = centerY; fillRoundCorner(hdc, clipRect, rectWin, bottomRight, m_data->matrix); #endif } void GraphicsContext::setURLForRect(const KURL& link, const IntRect& destRect) { notImplemented(); } void GraphicsContext::rotate(float) { notImplemented(); } void GraphicsContext::addInnerRoundedRectClip(const IntRect& rect, int thickness) { notImplemented(); } void GraphicsContext::setPlatformShadow(FloatSize const& size, float blur, Color const& color, ColorSpace) { #if ENABLE(CAIRO_MG) // Cairo doesn't support shadows natively, they are drawn manually in the draw* functions if (m_state.shadowsIgnoreTransforms) { // Meaning that this graphics context is associated with a CanvasRenderingContext // We flip the height since CG and HTML5 Canvas have opposite Y axis m_state.shadowOffset = FloatSize(size.width(), -size.height()); m_data->shadow = ContextShadow(color, blur, FloatSize(size.width(), -size.height())); } else m_data->shadow = ContextShadow(color, blur, FloatSize(size.width(), size.height())); m_data->shadow.setShadowsIgnoreTransforms(m_state.shadowsIgnoreTransforms); #endif } #if ENABLE(CAIRO_MG) ContextShadow* GraphicsContext::contextShadow() { return &m_data->shadow; } #endif void GraphicsContext::clearPlatformShadow() { #if ENABLE(CAIRO_MG) m_data->shadow.clear(); #endif } void GraphicsContext::beginTransparencyLayer(float opacity) { if (paintingDisabled()) return; HDC memdc = CreateCompatibleDC(m_data->viewdc); m_data->layers.append(memdc); SetMemDCAlpha(memdc, MEMDC_FLAG_SRCALPHA, opacity*255); m_data->context = memdc; } void GraphicsContext::endTransparencyLayer() { if (paintingDisabled()) return; HDC memdc = m_data->layers.last(); m_data->layers.removeLast(); if (!m_data->layers.isEmpty()) { m_data->context = m_data->layers.last(); } else { m_data->context = m_data->viewdc; } BitBlt(memdc, 0, 0, 0, 0, m_data->context, 0, 0, 0); DeleteCompatibleDC(memdc); } void GraphicsContext::clearRect(const FloatRect&) { notImplemented(); } void GraphicsContext::setMiterLimit(float) { notImplemented(); } void GraphicsContext::canvasClip(const Path&) { notImplemented(); } void GraphicsContext::clipOut(const Path&) { notImplemented(); } void GraphicsContext::concatCTM(const AffineTransform&) { notImplemented(); } void GraphicsContext::drawFocusRing(const Vector<IntRect>& rects, int width, int loffset, const Color& color) { if (paintingDisabled() || !color.isValid()) return; unsigned rectCount = rects.size(); if (!rects.size()) return; HDC hdc = m_data->context; int radius = (width - 1) / 2; int offset = radius + loffset; IntRect finalFocusRect; for (unsigned i = 0; i < rectCount; i++) { IntRect focusRect = rects[i]; focusRect.inflate(offset); finalFocusRect.unite(focusRect); } IntRect rc = m_data->matrix.mapRect(finalFocusRect); #if !ENABLE(FOCUSRING_TV) RECT rect(rc); GetDefaultWindowElementRenderer()->draw_focus_frame(hdc, &rect, color.rgb()); #else const Color col(0xFF, 0x00, 0x00); POINT sp[5]; sp[0].x = rc.x(); sp[0].y = rc.y(); sp[1].x = rc.x() + rc.width(); sp[1].y = rc.y(); sp[2].x = rc.x() + rc.width(); sp[2].y = rc.y() + rc.height(); sp[3].x = rc.x(); sp[3].y = rc.y() + rc.height(); sp[4].x = rc.x(); sp[4].y = rc.y(); int oldPen = SetPenType(hdc, PT_SOLID); int oldWidth = SetPenWidth(hdc, 3); setPenColor(hdc, col); PolyLineEx(hdc, sp, 5); SetPenType(hdc, oldPen); SetPenWidth(hdc, oldWidth); #endif } void GraphicsContext::drawFocusRing(const Path& path, int width, int /* offset */, const Color& color) { notImplemented(); } void GraphicsContext::setImageInterpolationQuality(InterpolationQuality) { notImplemented(); } InterpolationQuality GraphicsContext::imageInterpolationQuality() const { return InterpolationDefault; } void GraphicsContext::setPlatformShouldAntialias(bool b) { notImplemented(); } void GraphicsContext::clipPath(const Path& path, WindRule clipRule) { notImplemented(); } void GraphicsContext::setLineDash(const DashArray&, float dashOffset) { notImplemented(); } void GraphicsContext::clipConvexPolygon(size_t numPoints, const FloatPoint* points, bool antialiased) { notImplemented(); } void GraphicsContext::drawLineForTextChecking(const FloatPoint& origin, float width, TextCheckingLineStyle style) { notImplemented(); } void GraphicsContext::setPlatformCompositeOperation(CompositeOperator op) { //TODO if (paintingDisabled()) return; HDC hdc = m_data->context; switch (op) { case CompositeClear: //return CAIRO_OPERATOR_CLEAR; break; case CompositeCopy: //return CAIRO_OPERATOR_SOURCE; break; case CompositeSourceOver: SetRasterOperation (hdc, ROP_SET); break; case CompositeSourceIn: //return CAIRO_OPERATOR_IN; break; case CompositeSourceOut: //return CAIRO_OPERATOR_OUT; break; case CompositeSourceAtop: //return CAIRO_OPERATOR_ATOP; break; case CompositeDestinationOver: //return CAIRO_OPERATOR_DEST_OVER; break; case CompositeDestinationIn: //return CAIRO_OPERATOR_DEST_IN; break; case CompositeDestinationOut: //return CAIRO_OPERATOR_DEST_OUT; break; case CompositeDestinationAtop: //return CAIRO_OPERATOR_DEST_ATOP; break; case CompositeXOR: SetRasterOperation (hdc, ROP_XOR); break; case CompositePlusDarker: SetRasterOperation (hdc, ROP_SET); break; case CompositeHighlight: SetRasterOperation (hdc, ROP_SET); break; case CompositePlusLighter: SetRasterOperation (hdc, ROP_SET); break; default: SetRasterOperation (hdc, ROP_SET); break; } } } //end nameSpace WebCore
26.919158
186
0.639995
VincentWei
a4b02c08856cae5a46ec7e09150f3f0cf2830e03
552
cpp
C++
uva/575 - Skew Binary.cpp
taufique71/sports-programming
c29a92b5e5424c7de6f94e302fc6783561de9b3d
[ "MIT" ]
null
null
null
uva/575 - Skew Binary.cpp
taufique71/sports-programming
c29a92b5e5424c7de6f94e302fc6783561de9b3d
[ "MIT" ]
null
null
null
uva/575 - Skew Binary.cpp
taufique71/sports-programming
c29a92b5e5424c7de6f94e302fc6783561de9b3d
[ "MIT" ]
null
null
null
#include <iostream> #include <cstring> using namespace std; long int power(int n,int j) { long int res=1; int i; for(i=0;i<j;i++) { res=res*n; } return res; } int main() { char num[100]; int k,i; while(cin>>num) { if(!strcmp(num,"0")) break; int len=strlen(num); long int dec=0; for(i=len-1;i>=0;i--) { k=len-i; dec=dec+(num[i]-48)*(power(2,k)-1); } cout<<dec<<endl; } return 0; }
16.235294
48
0.425725
taufique71
a4b253a86cf66b40aa26baf044cf4dee4710d992
1,779
cc
C++
combination-sum-ii.cc
ArCan314/leetcode
8e22790dc2f34f5cf2892741ff4e5d492bb6d0dd
[ "MIT" ]
null
null
null
combination-sum-ii.cc
ArCan314/leetcode
8e22790dc2f34f5cf2892741ff4e5d492bb6d0dd
[ "MIT" ]
null
null
null
combination-sum-ii.cc
ArCan314/leetcode
8e22790dc2f34f5cf2892741ff4e5d492bb6d0dd
[ "MIT" ]
null
null
null
#include <string> #include <unordered_set> #include <vector> #include <algorithm> class Solution { public: static std::string toString(std::vector<int> vec) { std::string temp; for (const auto num : vec) temp.append(std::to_string(num)).push_back('#'); return temp; } static bool IsDup(std::vector<int> result, std::unordered_set<std::string> &combs) { std::sort(result.begin(), result.end()); if (combs.insert(toString(result)).second) return false; return true; } void _combinationSum2( const std::vector<int> &candidates, std::vector<std::vector<int>> &results, std::unordered_set<std::string> &combs, std::vector<int> &cur_comb, int cur_ind, int tar) { if (!tar) { if (!IsDup(cur_comb, combs)) results.push_back(cur_comb); } if (cur_ind == candidates.size()) return; for (int i = cur_ind; i < candidates.size(); i++) { if (tar - candidates[i] >= 0) { cur_comb.push_back(candidates[i]); _combinationSum2(candidates, results, combs, cur_comb, i + 1, tar - candidates[i]); cur_comb.pop_back(); } else break; } } std::vector<std::vector<int>> combinationSum2(std::vector<int> &candidates, int target) { std::sort(candidates.begin(), candidates.end()); std::unordered_set<std::string> combs; std::vector<std::vector<int>> results; std::vector<int> result; _combinationSum2(candidates, results, combs, result, 0, target); return results; } };
27.369231
99
0.540191
ArCan314
a4b2aba75b02c06c37d5e6fe0930b469e1916cd7
1,540
cpp
C++
2019.7.2/D_Persona5.cpp
wang2470616413/MyCode
23f4d6c12d0475e67e892ce39745bcada9c10197
[ "MIT" ]
1
2019-04-20T09:52:50.000Z
2019-04-20T09:52:50.000Z
2019.7.2/D_Persona5.cpp
wang2470616413/MyCode
23f4d6c12d0475e67e892ce39745bcada9c10197
[ "MIT" ]
null
null
null
2019.7.2/D_Persona5.cpp
wang2470616413/MyCode
23f4d6c12d0475e67e892ce39745bcada9c10197
[ "MIT" ]
null
null
null
#include<stdio.h> #include<string.h> #define ll long long #define mmset(a,b) memset(a,b,sizeof(a)) #define error printf("error\n") using namespace std; const int N = 1e6 + 10; const ll MOD = 1e9 + 7; ll F[N]; ll data[N]; ll res = 1; ll aux = 0; void init(ll p) { F[0] = 1; for(int i = 1;i <= p;i++) F[i] = F[i-1]*i % (MOD); } ll inv(ll a,ll m) { if(a == 1)return 1; return inv(m%a,m)*(m-m/a)%m; } ll pow(ll a, ll n, ll p) //快速幂 a^n % p { ll ans = 1; while(n) { if(n & 1) ans = ans * a % p; a = a * a % p; n >>= 1; } return ans; } ll niYuan(ll a, ll b) //费马小定理求逆元 { return pow(a, b - 2, b); } ll C(ll a, ll b) //计算C(a, b) { return F[a] * niYuan(F[b], MOD) % MOD * niYuan(F[a - b], MOD) % MOD; } ll Lucas(ll a, ll b) { if(a < MOD && b < MOD) return C(a, b); return C(a % MOD, b % MOD) * Lucas(a / MOD, b / MOD); } ll modmul(ll ans,ll a) { ll t=0; while (a) { if(a&1) t=(t+ans)%MOD; ans=(ans+ans)%MOD; a=a>>1; } return t; } /* 3 1 1 1 3 1 2 3 */ int main() { int n; while(~scanf("%d",&n)) { res = 1, aux = 0; for(int i = 1; i <= n; i++) { scanf("%d",&data[i]); aux += data[i]; } init(aux + 5); for(int i = 1; i <= n - 1; i++) { res = modmul(res,(Lucas(aux,data[i]))); aux -= data[i]; } printf("%lld\n",res); } return 0; }
16.210526
54
0.416234
wang2470616413
a4b3b7230b6eb2d244efbede1bc95cee09f65f95
6,986
cc
C++
components/material/data/MaterialMenuSource.cc
SBKarr/stappler
d9311cba0b0e9362be55feca39a866d7bccd6dff
[ "MIT" ]
10
2015-06-16T16:52:53.000Z
2021-04-15T09:21:22.000Z
components/material/data/MaterialMenuSource.cc
SBKarr/stappler
d9311cba0b0e9362be55feca39a866d7bccd6dff
[ "MIT" ]
3
2015-09-23T10:04:00.000Z
2020-09-10T15:47:34.000Z
components/material/data/MaterialMenuSource.cc
SBKarr/stappler
d9311cba0b0e9362be55feca39a866d7bccd6dff
[ "MIT" ]
3
2018-11-11T00:37:49.000Z
2020-09-07T03:04:31.000Z
// This is an open source non-commercial project. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com /** Copyright (c) 2016 Roman Katuntsev <sbkarr@stappler.org> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. **/ #include "Material.h" #include "MaterialMenuSource.h" NS_MD_BEGIN bool MenuSourceItem::init() { return true; } Rc<MenuSourceItem> MenuSourceItem::copy() const { auto ret = Rc<MenuSourceItem>::create(); ret->setCustomData(_customData); return ret; } void MenuSourceItem::setCustomData(const data::Value &val) { _customData = val; setDirty(); } void MenuSourceItem::setCustomData(data::Value &&val) { _customData = std::move(val); setDirty(); } const stappler::data::Value &MenuSourceItem::getCustomData() const { return _customData; } MenuSourceItem * MenuSourceItem::setAttachCallback(const AttachCallback &cb) { _attachCallback = cb; return this; } MenuSourceItem * MenuSourceItem::setDetachCallback(const AttachCallback &cb) { _detachCallback = cb; return this; } MenuSourceItem::Type MenuSourceItem::getType() const { return _type; } void MenuSourceItem::onNodeAttached(cocos2d::Node *n) { if (_attachCallback) { _attachCallback(this, n); } } void MenuSourceItem::onNodeDetached(cocos2d::Node *n) { if (_detachCallback) { _detachCallback(this, n); } } void MenuSourceItem::setDirty() { Subscription::setDirty(); } MenuSourceButton::~MenuSourceButton() { } bool MenuSourceButton::init(const String &str, IconName name, const Callback &cb) { if (!init()) { return false; } _name = str; _nameIcon = name; _callback = cb; return true; } bool MenuSourceButton::init() { if (!MenuSourceItem::init()) { return false; } _type = Type::Button; return true; } Rc<MenuSourceItem> MenuSourceButton::copy() const { auto ret = Rc<MenuSourceButton>::create(); ret->setName(_name); ret->setNameIcon(_nameIcon); ret->setValue(_name); ret->setValueIcon(_nameIcon); ret->setSelected(_selected); ret->setNextMenu(_nextMenu); ret->setCallback(_callback); ret->setCustomData(_customData); return ret; } void MenuSourceButton::setName(const String &val) { if (_name != val) { _name = val; setDirty(); } } const String & MenuSourceButton::getName() const { return _name; } void MenuSourceButton::setValue(const String &val) { if (_value != val) { _value = val; setDirty(); } } const String & MenuSourceButton::getValue() const { return _value; } void MenuSourceButton::setNameIcon(IconName icon) { if (_nameIcon != icon) { _nameIcon = icon; setDirty(); } } IconName MenuSourceButton::getNameIcon() const { return _nameIcon; } void MenuSourceButton::setValueIcon(IconName icon) { if (_valueIcon != icon) { _valueIcon = icon; setDirty(); } } IconName MenuSourceButton::getValueIcon() const { return _valueIcon; } void MenuSourceButton::setCallback(const Callback &cb) { _callback = cb; setDirty(); } const MenuSourceButton::Callback & MenuSourceButton::getCallback() const { return _callback; } void MenuSourceButton::setNextMenu(MenuSource *menu) { if (menu != _nextMenu) { _nextMenu = menu; setDirty(); } } MenuSource * MenuSourceButton::getNextMenu() const { return _nextMenu; } void MenuSourceButton::setSelected(bool value) { if (_selected != value) { _selected = value; setDirty(); } } bool MenuSourceButton::isSelected() const { return _selected; } bool MenuSourceCustom::init() { if (!MenuSourceItem::init()) { return false; } _type = Type::Custom; return true; } bool MenuSourceCustom::init(float h, const FactoryFunction &func, float minWidth) { return init([h] (float w) { return h; }, func); } bool MenuSourceCustom::init(const HeightFunction &h, const FactoryFunction &func, float minWidth) { if (!init()) { return false; } _minWidth = minWidth; _heightFunction = h; _function = func; return true; } Rc<MenuSourceItem> MenuSourceCustom::copy() const { auto ret = Rc<MenuSourceCustom>::create(_heightFunction, _function); ret->setCustomData(_customData); return ret; } float MenuSourceCustom::getMinWidth() const { return _minWidth; } float MenuSourceCustom::getHeight(float w) const { return _heightFunction(w); } const MenuSourceCustom::HeightFunction & MenuSourceCustom::getHeightFunction() const { return _heightFunction; } const MenuSourceCustom::FactoryFunction & MenuSourceCustom::getFactoryFunction() const { return _function; } MenuSource::~MenuSource() { } void MenuSource::setHintCount(size_t h) { _hintCount = h; } size_t MenuSource::getHintCount() const { return _hintCount; } Rc<MenuSource> MenuSource::copy() const { auto ret = Rc<MenuSource>::create(); for (auto &it : _items) { ret->addItem(it->copy()); } ret->setHintCount(_hintCount); return ret; } void MenuSource::addItem(MenuSourceItem *item) { if (item) { _items.emplace_back(item); setDirty(); } } Rc<MenuSourceButton> MenuSource::addButton(const String &str, const Callback &cb) { auto item = Rc<MenuSourceButton>::create(str, IconName::None, cb); addItem(item); return item; } Rc<MenuSourceButton> MenuSource::addButton(const String &str, IconName name, const Callback &cb) { auto item = Rc<MenuSourceButton>::create(str, name, cb); addItem(item); return item; } Rc<MenuSourceCustom> MenuSource::addCustom(float h, const MenuSourceCustom::FactoryFunction &func, float w) { auto item = Rc<MenuSourceCustom>::create(h, func, w); addItem(item); return item; } Rc<MenuSourceCustom> MenuSource::addCustom(const HeightFunction &h, const FactoryFunction &func, float w) { auto item = Rc<MenuSourceCustom>::create(h, func, w); addItem(item); return item; } Rc<MenuSourceItem> MenuSource::addSeparator() { auto item = Rc<MenuSourceItem>::create(); addItem(item); return item; } void MenuSource::clear() { _items.clear(); setDirty(); } uint32_t MenuSource::count() { return (uint32_t)_items.size(); } const Vector<Rc<MenuSourceItem>> &MenuSource::getItems() const { return _items; } NS_MD_END
23.681356
109
0.734612
SBKarr
8a54e356bad832914b1ba3bc3cb2424e0312b24f
753
cpp
C++
Sources/Scene/Component/SyrinxRenderer.cpp
LeptusHe/SyrinxEngine
5ecdfdd53eb421bdfba61ed183a1ac688d117b97
[ "MIT" ]
3
2020-04-24T07:58:52.000Z
2021-11-17T11:08:46.000Z
Sources/Scene/Component/SyrinxRenderer.cpp
LeptusHe/SyrinxEngine
5ecdfdd53eb421bdfba61ed183a1ac688d117b97
[ "MIT" ]
null
null
null
Sources/Scene/Component/SyrinxRenderer.cpp
LeptusHe/SyrinxEngine
5ecdfdd53eb421bdfba61ed183a1ac688d117b97
[ "MIT" ]
2
2019-10-02T01:49:46.000Z
2021-11-16T15:25:59.000Z
#include "Component/SyrinxRenderer.h" #include <Common/SyrinxAssert.h> namespace Syrinx { Renderer::Renderer() : mMesh(nullptr), mMaterial(nullptr) { SYRINX_ENSURE(!mMesh); SYRINX_ENSURE(!mMaterial); } void Renderer::setMesh(Mesh *mesh) { mMesh = mesh; SYRINX_ENSURE(mMesh); SYRINX_ENSURE(mMesh == mesh); } void Renderer::setMaterial(Material *material) { mMaterial = material; SYRINX_ENSURE(mMaterial); SYRINX_ENSURE(mMaterial == material); } const Mesh* Renderer::getMesh() const { return mMesh; } const Material* Renderer::getMaterial() const { return mMaterial; } bool Renderer::isValid() const { return mMesh && mMaterial; } } // namespace Syrinx
16.369565
58
0.652058
LeptusHe
8a5556acd077257946ce0108e924e6374f0a176b
9,252
cpp
C++
lib/MagnetRTD/MagnetRTD.cpp
greenspaceexplorer/MagnetHSK
41ab4758a21ecf7f980032ee0f2f569b120f8ebf
[ "MIT" ]
null
null
null
lib/MagnetRTD/MagnetRTD.cpp
greenspaceexplorer/MagnetHSK
41ab4758a21ecf7f980032ee0f2f569b120f8ebf
[ "MIT" ]
null
null
null
lib/MagnetRTD/MagnetRTD.cpp
greenspaceexplorer/MagnetHSK
41ab4758a21ecf7f980032ee0f2f569b120f8ebf
[ "MIT" ]
null
null
null
#include "MagnetRTD.h" MagnetRTD::MagnetRTD(SPIClass *mySPI, uint8_t clock, uint8_t chip_select){ // Set internal variables thisSPI = mySPI; clk = clock; cs = chip_select; } //------------------------------------------------------------------------------ MagnetRTD::~MagnetRTD(){} //------------------------------------------------------------------------------ void MagnetRTD::setup(){ // Initialize SPI communication on the housekeeping board pinMode(clk,OUTPUT); digitalWrite(clk,1); thisSPI->begin(); pinMode(cs,OUTPUT); configure_channels(); configure_memory_table(); configure_global_parameters(); } //------------------------------------------------------------------------------ sMagnetRTD MagnetRTD::readTemp(uint8_t cmd) { sMagnetRTD out; switch (cmd) { case eTopStackRTDcels: { out.value = this->returnTemperature(cs,TopStack); break; } case eTopNonStackRTDcels: { out.value = this->returnTemperature(cs,TopNonStack); break; } case eBottomStackRTDcels: { out.value = this->returnTemperature(cs,BottomStack); break; } case eBottomNonStackRTDcels: { out.value = this->returnTemperature(cs,BottomNonStack); break; } case eShieldRTD1cels: { out.value = this->returnTemperature(cs,Shield1); break; } case eShieldRTD2cels: { out.value = this->returnTemperature(cs,Shield2); break; } default: { out.value = -1.0; // invalid command break; } } return out; } //------------------------------------------------------------------------------ sMagnetRTD MagnetRTD::readResist(uint8_t cmd) { sMagnetRTD out; switch (cmd) { case eTopStackRTDohms: { out.value = this->returnResistance(cs,TopStack); break; } case eTopNonStackRTDohms: { out.value = this->returnResistance(cs,TopNonStack); break; } case eBottomStackRTDohms: { out.value = this->returnResistance(cs,BottomStack); break; } case eBottomNonStackRTDohms: { out.value = this->returnResistance(cs,BottomNonStack); break; } case eShieldRTD1ohms: { out.value = this->returnResistance(cs,Shield1); break; } case eShieldRTD2ohms: { out.value = this->returnResistance(cs,Shield2); break; } default: { out.value = -1.0; // invalid command break; } } return out; } //------------------------------------------------------------------------------ sMagnetRTDAll MagnetRTD::readAll(uint8_t cmd) { sMagnetRTDAll out; if (cmd == eRTDallCels) { out.top_stack = this->readTemp(eTopStackRTDcels).value; out.top_nonstack = this->readTemp(eTopNonStackRTDcels).value; out.btm_stack = this->readTemp(eBottomStackRTDcels).value; out.btm_nonstack = this->readTemp(eBottomNonStackRTDcels).value; out.shield1 = this->readTemp(eShieldRTD1cels).value; out.shield2 = this->readTemp(eShieldRTD2cels).value; } else if (cmd == eRTDallOhms) { out.top_stack = this->readResist(eTopStackRTDohms).value; out.top_nonstack = this->readResist(eTopNonStackRTDohms).value; out.btm_stack = this->readResist(eBottomStackRTDohms).value; out.btm_nonstack = this->readResist(eBottomNonStackRTDohms).value; out.shield1 = this->readResist(eShieldRTD1ohms).value; out.shield2 = this->readResist(eShieldRTD2ohms).value; } else { out.top_stack = -1.; out.top_nonstack = -1.; out.btm_stack = -1.; out.btm_nonstack = -1.; out.shield1 = -1.; out.shield2 = -1.; } return out; } //------------------------------------------------------------------------------ int MagnetRTD::wait_for_process_to_finish(uint8_t chip_select) { uint8_t process_finished = 0; uint8_t data; int goAhead = 1; // unsigned long CurrentTime; // unsigned long ElapsedTime; unsigned long StartTime = millis(); while (process_finished == 0) { data = this->transfer_byte(chip_select, READ_FROM_RAM, COMMAND_STATUS_REGISTER, 0); process_finished = data & 0x40; if ((millis() - StartTime) > MaxWaitSpi) { goAhead = 0; return goAhead; } } // Serial.print(" t="); // Serial.print(millis() - StartTime); // Serial.print(" "); return goAhead; } //------------------------------------------------------------------------------ uint16_t MagnetRTD::get_start_address(uint16_t base_address, uint8_t channel_number) { return base_address + 4 * (channel_number-1); } //------------------------------------------------------------------------------ uint8_t MagnetRTD::transfer_byte(uint8_t chip_select, uint8_t ram_read_or_write, uint16_t start_address, uint8_t input_data) { uint8_t tx[4], rx[4]; tx[3] = ram_read_or_write; tx[2] = (uint8_t)(start_address >> 8); tx[1] = (uint8_t)start_address; tx[0] = input_data; this->spi_transfer_block(chip_select, tx, rx, 4); return rx[0]; } //------------------------------------------------------------------------------ bool MagnetRTD::is_number_in_array(uint8_t number, uint8_t *array, uint8_t array_length) // Find out if a number is an element in an array { bool found = false; for (uint8_t i=0; i< array_length; i++) { if (number == array[i]) { found = true; } } return found; } //------------------------------------------------------------------------------ uint32_t MagnetRTD::transfer_four_bytes(uint8_t chip_select, uint8_t ram_read_or_write, uint16_t start_address, uint32_t input_data) { uint32_t output_data; uint8_t tx[7], rx[7]; tx[6] = ram_read_or_write; tx[5] = highByte(start_address); tx[4] = lowByte(start_address); tx[3] = (uint8_t)(input_data >> 24); tx[2] = (uint8_t)(input_data >> 16); tx[1] = (uint8_t)(input_data >> 8); tx[0] = (uint8_t)input_data; this->spi_transfer_block(chip_select, tx, rx, 7); output_data = (uint32_t)rx[3] << 24 | (uint32_t)rx[2] << 16 | (uint32_t)rx[1] << 8 | (uint32_t)rx[0]; return output_data; } //------------------------------------------------------------------------------ // Reads and sends a byte array void MagnetRTD::spi_transfer_block(uint8_t cs_pin, uint8_t *tx, uint8_t *rx, uint8_t length) { int8_t i; output_low(cs_pin); //! 1) Pull CS low for (i = (length - 1); i >= 0; i--) rx[i] = thisSPI->transfer(tx[i]); //! 2) Read and send byte array output_high(cs_pin); //! 3) Pull CS high } //------------------------------------------------------------------------------ float MagnetRTD::returnResistance(uint8_t chip_select, uint8_t channel_number) { int goAhead; goAhead = convert_channel(chip_select, channel_number); if (goAhead == 1) { int32_t raw_data; float voltage_or_resistance_result; uint16_t start_address = this->get_start_address(VOUT_CH_BASE, channel_number); raw_data = this->transfer_four_bytes(chip_select, READ_FROM_RAM, start_address, 0); voltage_or_resistance_result = (float)raw_data / 1024; return voltage_or_resistance_result; } else { return Nonsense; } } //------------------------------------------------------------------------------ float MagnetRTD::returnTemperature(uint8_t chip_select, uint8_t channel_number) { int goAhead; goAhead = convert_channel(chip_select, channel_number); if (goAhead == 1) { uint32_t raw_data; uint8_t fault_data; uint16_t start_address = this->get_start_address(CONVERSION_RESULT_MEMORY_BASE, channel_number); uint32_t raw_conversion_result; int32_t signed_data; float scaled_result; raw_data = this->transfer_four_bytes(chip_select, READ_FROM_RAM, start_address, 0); // 24 LSB's are conversion result raw_conversion_result = raw_data & 0xFFFFFF; signed_data = raw_conversion_result; // Convert the 24 LSB's into a signed 32-bit integer if (signed_data & 0x800000) signed_data = signed_data | 0xFF000000; scaled_result = float(signed_data) / 1024; return scaled_result; } else { return -9999; } } //------------------------------------------------------------------------------ int MagnetRTD::convert_channel(uint8_t chip_select, uint8_t channel_number) { // Start conversion this->transfer_byte(chip_select, WRITE_TO_RAM, COMMAND_STATUS_REGISTER, CONVERSION_CONTROL_BYTE | channel_number); int goAhead; goAhead = this->wait_for_process_to_finish(chip_select); return goAhead; }
27.535714
88
0.540208
greenspaceexplorer
8a55bdc3dd28c55ea0ee577a8799eccfd4517fba
2,414
cc
C++
tools/gn/gyp_target_writer.cc
nagineni/chromium-crosswalk
5725642f1c67d0f97e8613ec1c3e8107ab53fdf8
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
tools/gn/gyp_target_writer.cc
nagineni/chromium-crosswalk
5725642f1c67d0f97e8613ec1c3e8107ab53fdf8
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
tools/gn/gyp_target_writer.cc
nagineni/chromium-crosswalk
5725642f1c67d0f97e8613ec1c3e8107ab53fdf8
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2013 The Chromium 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 "tools/gn/gyp_target_writer.h" #include <iostream> #include "base/file_util.h" #include "base/files/file_path.h" #include "tools/gn/build_settings.h" #include "tools/gn/filesystem_utils.h" #include "tools/gn/gyp_binary_target_writer.h" #include "tools/gn/scheduler.h" #include "tools/gn/settings.h" #include "tools/gn/target.h" GypTargetWriter::GypTargetWriter(const Target* target, std::ostream& out) : settings_(target->settings()), target_(target), out_(out) { } GypTargetWriter::~GypTargetWriter() { } // static void GypTargetWriter::WriteFile(const SourceFile& gyp_file, const std::vector<TargetGroup>& targets, Err* err) { if (targets.empty()) return; const BuildSettings* debug_build_settings = targets[0].debug->settings()->build_settings(); std::stringstream file; file << "# Generated by GN. Do not edit.\n\n"; file << "{\n"; file << " 'skip_includes': 1,\n"; if (targets[0].debug->settings()->IsMac()) { // Global settings for make/ninja. This must match common.gypi :( file << " 'make_global_settings': [\n"; file << " ['CC', 'third_party/llvm-build/Release+Asserts/bin/clang'],\n"; file << " ['CXX', 'third_party/llvm-build/Release+Asserts/bin/clang++'],\n"; file << " ['CC.host', '$(CC)'],\n"; file << " ['CXX.host', '$(CXX)'],\n"; file << " ],\n"; } // TODO(brettw) android. file << " 'targets': [\n"; for (size_t i = 0; i < targets.size(); i++) { switch (targets[i].debug->output_type()) { case Target::COPY_FILES: case Target::CUSTOM: case Target::GROUP: break; // TODO(brettw) case Target::EXECUTABLE: case Target::STATIC_LIBRARY: case Target::SHARED_LIBRARY: case Target::SOURCE_SET: { GypBinaryTargetWriter writer(targets[i], file); writer.Run(); break; } default: CHECK(0); } } file << " ],\n}\n"; base::FilePath gyp_file_path = debug_build_settings->GetFullPath(gyp_file); std::string contents = file.str(); file_util::WriteFile(gyp_file_path, contents.c_str(), static_cast<int>(contents.size())); }
29.439024
80
0.61309
nagineni
8a57390a40c4eecd165993b213e765472047d571
10,553
cpp
C++
src/hash_value.cpp
MiguelBel/natalie
8439d45982b0edb14e51cd1958a865bb7f540b2d
[ "MIT" ]
null
null
null
src/hash_value.cpp
MiguelBel/natalie
8439d45982b0edb14e51cd1958a865bb7f540b2d
[ "MIT" ]
null
null
null
src/hash_value.cpp
MiguelBel/natalie
8439d45982b0edb14e51cd1958a865bb7f540b2d
[ "MIT" ]
null
null
null
#include "natalie.hpp" namespace Natalie { // this is used by the hashmap library and assumes that obj->env has been set size_t HashValue::hash(const void *key) { return static_cast<const HashValue::Key *>(key)->hash; } // this is used by the hashmap library to compare keys int HashValue::compare(const void *a, const void *b) { Key *a_p = (Key *)a; Key *b_p = (Key *)b; // NOTE: Only one of the keys will have a relevant Env, i.e. the one with a non-null global_env. // This is a bit of a hack to get around the fact that we can't pass any extra args to hashmap_* functions. // TODO: Write our own hashmap implementation that passes Env around. :^) Env *env = a_p->env.global_env() ? &a_p->env : &b_p->env; assert(env); assert(env->global_env()); return a_p->key->send(env, "eql?", 1, &b_p->key)->is_truthy() ? 0 : 1; // return 0 for exact match } Value *HashValue::get(Env *env, Value *key) { Key key_container; key_container.key = key; key_container.env = *env; key_container.hash = key->send(env, "hash")->as_integer()->to_int64_t(); Val *container = static_cast<Val *>(hashmap_get(&m_hashmap, &key_container)); Value *val = container ? container->val : nullptr; return val; } Value *HashValue::get_default(Env *env, Value *key) { if (m_default_block) { Value *args[2] = { this, key }; return NAT_RUN_BLOCK_WITHOUT_BREAK(env, m_default_block, 2, args, nullptr); } else { return m_default_value; } } void HashValue::put(Env *env, Value *key, Value *val) { NAT_ASSERT_NOT_FROZEN(this); Key key_container; key_container.key = key; key_container.env = *env; key_container.hash = key->send(env, "hash")->as_integer()->to_int64_t(); Val *container = static_cast<Val *>(hashmap_get(&m_hashmap, &key_container)); if (container) { container->key->val = val; container->val = val; } else { if (m_is_iterating) { NAT_RAISE(env, "RuntimeError", "can't add a new key into hash during iteration"); } container = static_cast<Val *>(malloc(sizeof(Val))); container->key = key_list_append(env, key, val); container->val = val; hashmap_put(&m_hashmap, container->key, container); // NOTE: env must be current and relevant at all times // See note on hashmap_compare for more details container->key->env = {}; } } Value *HashValue::remove(Env *env, Value *key) { Key key_container; key_container.key = key; key_container.env = *env; key_container.hash = key->send(env, "hash")->as_integer()->to_int64_t(); Val *container = static_cast<Val *>(hashmap_remove(&m_hashmap, &key_container)); if (container) { key_list_remove_node(container->key); Value *val = container->val; free(container); return val; } else { return nullptr; } } Value *HashValue::default_proc(Env *env) { return ProcValue::from_block_maybe(env, m_default_block); } Value *HashValue::default_value(Env *env) { if (m_default_value) return m_default_value; return env->nil_obj(); } HashValue::Key *HashValue::key_list_append(Env *env, Value *key, Value *val) { if (m_key_list) { Key *first = m_key_list; Key *last = m_key_list->prev; Key *new_last = static_cast<Key *>(malloc(sizeof(Key))); new_last->key = key; new_last->val = val; // <first> ... <last> <new_last> -| // ^______________________________| new_last->prev = last; new_last->next = first; new_last->env = Env::new_detatched_block_env(env); new_last->hash = key->send(env, "hash")->as_integer()->to_int64_t(); new_last->removed = false; first->prev = new_last; last->next = new_last; return new_last; } else { Key *node = static_cast<Key *>(malloc(sizeof(Key))); node->key = key; node->val = val; node->prev = node; node->next = node; node->env = Env::new_detatched_block_env(env); node->hash = key->send(env, "hash")->as_integer()->to_int64_t(); node->removed = false; m_key_list = node; return node; } } void HashValue::key_list_remove_node(Key *node) { Key *prev = node->prev; Key *next = node->next; // <prev> <-> <node> <-> <next> if (node == next) { // <node> -| // ^_______| node->prev = nullptr; node->next = nullptr; node->removed = true; m_key_list = nullptr; return; } else if (m_key_list == node) { // starting point is the node to be removed, so shift them forward by one m_key_list = next; } // remove the node node->removed = true; prev->next = next; next->prev = prev; } Value *HashValue::initialize(Env *env, Value *default_value, Block *block) { if (block) { if (default_value) { NAT_RAISE(env, "ArgumentError", "wrong number of arguments (given 1, expected 0)"); } set_default_block(block); } else if (default_value) { set_default_value(default_value); } return this; } // Hash[] Value *HashValue::square_new(Env *env, ssize_t argc, Value **args) { if (argc == 0) { return new HashValue { env }; } else if (argc == 1) { Value *value = args[0]; if (value->type() == Value::Type::Hash) { return value; } else if (value->type() == Value::Type::Array) { HashValue *hash = new HashValue { env }; for (auto &pair : *value->as_array()) { if (pair->type() != Value::Type::Array) { NAT_RAISE(env, "ArgumentError", "wrong element in array to Hash[]"); } ssize_t size = pair->as_array()->size(); if (size < 1 || size > 2) { NAT_RAISE(env, "ArgumentError", "invalid number of elements (%d for 1..2)", size); } Value *key = (*pair->as_array())[0]; Value *value = size == 1 ? env->nil_obj() : (*pair->as_array())[1]; hash->put(env, key, value); } return hash; } } if (argc % 2 != 0) { NAT_RAISE(env, "ArgumentError", "odd number of arguments for Hash"); } HashValue *hash = new HashValue { env }; for (ssize_t i = 0; i < argc; i += 2) { Value *key = args[i]; Value *value = args[i + 1]; hash->put(env, key, value); } return hash; } Value *HashValue::inspect(Env *env) { StringValue *out = new StringValue { env, "{" }; ssize_t last_index = size() - 1; ssize_t index = 0; for (HashValue::Key &node : *this) { StringValue *key_repr = node.key->send(env, "inspect")->as_string(); out->append_string(env, key_repr); out->append(env, "=>"); StringValue *val_repr = node.val->send(env, "inspect")->as_string(); out->append_string(env, val_repr); if (index < last_index) { out->append(env, ", "); } index++; } out->append_char(env, '}'); return out; } Value *HashValue::ref(Env *env, Value *key) { Value *val = get(env, key); if (val) { return val; } else { return get_default(env, key); } } Value *HashValue::refeq(Env *env, Value *key, Value *val) { put(env, key, val); return val; } Value *HashValue::delete_key(Env *env, Value *key) { NAT_ASSERT_NOT_FROZEN(this); Value *val = remove(env, key); if (val) { return val; } else { return env->nil_obj(); } } Value *HashValue::size(Env *env) { assert(size() <= NAT_MAX_INT); return new IntegerValue { env, static_cast<int64_t>(size()) }; } Value *HashValue::eq(Env *env, Value *other_value) { if (!other_value->is_hash()) { return env->false_obj(); } HashValue *other = other_value->as_hash(); if (size() != other->size()) { return env->false_obj(); } Value *other_val; for (HashValue::Key &node : *this) { other_val = other->get(env, node.key); if (!other_val) { return env->false_obj(); } if (!node.val->send(env, "==", 1, &other_val, nullptr)->is_truthy()) { return env->false_obj(); } } return env->true_obj(); } #define NAT_RUN_BLOCK_AND_POSSIBLY_BREAK_WHILE_ITERATING_HASH(env, the_block, argc, args, block, hash) ({ \ Value *_result = the_block->_run(env, argc, args, block); \ if (_result->has_break_flag()) { \ _result->remove_break_flag(); \ hash->set_is_iterating(false); \ return _result; \ } \ _result; \ }) Value *HashValue::each(Env *env, Block *block) { NAT_ASSERT_BLOCK(); // TODO: return Enumerator when no block given Value *block_args[2]; for (HashValue::Key &node : *this) { block_args[0] = node.key; block_args[1] = node.val; NAT_RUN_BLOCK_AND_POSSIBLY_BREAK_WHILE_ITERATING_HASH(env, block, 2, block_args, nullptr, this); } return this; } Value *HashValue::keys(Env *env) { ArrayValue *array = new ArrayValue { env }; for (HashValue::Key &node : *this) { array->push(node.key); } return array; } Value *HashValue::values(Env *env) { ArrayValue *array = new ArrayValue { env }; for (HashValue::Key &node : *this) { array->push(node.val); } return array; } Value *HashValue::sort(Env *env) { ArrayValue *ary = new ArrayValue { env }; for (HashValue::Key &node : *this) { ArrayValue *pair = new ArrayValue { env }; pair->push(node.key); pair->push(node.val); ary->push(pair); } return ary->sort(env); } Value *HashValue::has_key(Env *env, Value *key) { Value *val = get(env, key); if (val) { return env->true_obj(); } else { return env->false_obj(); } } }
32.773292
111
0.548659
MiguelBel
8a5c3c9f98f315765a9fd560976ac5d593fff95e
17,111
cpp
C++
NULL Engine/Source/E_Inspector.cpp
xsiro/NULL_Engine
bb8da3de7f507b27d895cf8066a03faa115ff3c6
[ "MIT" ]
null
null
null
NULL Engine/Source/E_Inspector.cpp
xsiro/NULL_Engine
bb8da3de7f507b27d895cf8066a03faa115ff3c6
[ "MIT" ]
null
null
null
NULL Engine/Source/E_Inspector.cpp
xsiro/NULL_Engine
bb8da3de7f507b27d895cf8066a03faa115ff3c6
[ "MIT" ]
null
null
null
#include "MathGeoTransform.h" #include "Color.h" #include "Application.h" #include "M_Renderer3D.h" #include "M_Editor.h" #include "GameObject.h" #include "Component.h" #include "C_Transform.h" #include "C_Mesh.h" #include "C_Material.h" #include "C_Light.h" #include "C_Camera.h" #include "E_Inspector.h" #define MAX_VALUE 100000 #define MIN_VALUE -100000 E_Inspector::E_Inspector() : EditorPanel("Inspector"), show_delete_component_popup (false), component_type (0), map_to_display (0), component_to_delete (nullptr) { } E_Inspector::~E_Inspector() { component_to_delete = nullptr; } bool E_Inspector::Draw(ImGuiIO& io) { bool ret = true; ImGui::Begin("Inspector"); SetIsHovered(); GameObject* selected = App->editor->GetSelectedGameObjectThroughEditor(); if (selected != nullptr && !selected->is_master_root && !selected->is_scene_root) { DrawGameObjectInfo(selected); DrawComponents(selected); ImGui::Separator(); AddComponentCombo(selected); if (show_delete_component_popup) { DeleteComponentPopup(selected); } } //ImGui::Text("WantCaptureMouse: %d", io.WantCaptureMouse); //ImGui::Text("WantCaptureKeyboard: %d", io.WantCaptureKeyboard); //ImGui::Text("WantTextInput: %d", io.WantTextInput); //ImGui::Text("WantSetMousePos: %d", io.WantSetMousePos); //ImGui::Text("NavActive: %d, NavVisible: %d", io.NavActive, io.NavVisible); ImGui::End(); return ret; } bool E_Inspector::CleanUp() { bool ret = true; return ret; } // --- INSPECTOR METHODS --- void E_Inspector::DrawGameObjectInfo(GameObject* selected_game_object) { // --- IS ACTIVE --- bool game_object_is_active = selected_game_object->IsActive(); if (ImGui::Checkbox("Is Active", &game_object_is_active)) { selected_game_object->SetIsActive(game_object_is_active); } ImGui::SameLine(); // --- GAME OBJECT'S NAME --- ImGui::SetNextItemWidth(ImGui::GetWindowWidth() * 0.33f); static char buffer[64]; strcpy_s(buffer, selected_game_object->GetName()); if (ImGui::InputText("Name", buffer, IM_ARRAYSIZE(buffer), ImGuiInputTextFlags_EnterReturnsTrue)) { selected_game_object->SetName(buffer); } ImGui::SameLine(); HelpMarker("Press ENTER to Rename"); ImGui::SameLine(); // --- IS STATIC --- //bool is_static = selected_game_object->IsStatic(); bool is_static = true; if (ImGui::Checkbox("Is Static", &is_static)) { selected_game_object->SetIsStatic(is_static); } // --- TAG --- ImGui::SetNextItemWidth(ImGui::GetWindowWidth() * 0.33f); static char tag_combo[64] = { "Untagged\0Work\0In\0Progress" }; static int current_tag = 0; ImGui::Combo("Tag", &current_tag, tag_combo); ImGui::SameLine(218.0f); // --- LAYER --- ImGui::SetNextItemWidth(ImGui::GetWindowWidth() * 0.33f); static char layer_combo[64] = { "Default\0Work\0In\0Progress" }; static int current_layer = 0; ImGui::Combo("Layer", &current_layer, layer_combo); ImGui::Separator(); } void E_Inspector::DrawComponents(GameObject* selected_game_object) { if (selected_game_object == nullptr) { LOG("[ERROR] Editor Inspector: Could not draw the selected GameObject's components! Error: Selected GameObject was nullptr."); return; } for (uint i = 0; i < selected_game_object->components.size(); ++i) { Component* component = selected_game_object->components[i]; if (component == nullptr) { continue; } COMPONENT_TYPE type = component->GetType(); switch (type) { case COMPONENT_TYPE::TRANSFORM: { DrawTransformComponent((C_Transform*)component); } break; case COMPONENT_TYPE::MESH: { DrawMeshComponent((C_Mesh*)component); } break; case COMPONENT_TYPE::MATERIAL: { DrawMaterialComponent((C_Material*)component); } break; case COMPONENT_TYPE::LIGHT: { DrawLightComponent((C_Light*)component); } break; case COMPONENT_TYPE::CAMERA: { DrawCameraComponent((C_Camera*)component); } break; } if (type == COMPONENT_TYPE::NONE) { LOG("[WARNING] Selected GameObject %s has a non-valid component!", selected_game_object->GetName()); } } } void E_Inspector::DrawTransformComponent(C_Transform* c_transform) { bool show = true; // Dummy bool to delete the component related with the collpsing header. if (ImGui::CollapsingHeader("Transform", &show, ImGuiTreeNodeFlags_DefaultOpen)) { if (c_transform != nullptr) { // --- IS ACTIVE --- bool transform_is_active = c_transform->IsActive(); if (ImGui::Checkbox("Transform Is Active", &transform_is_active)) { //transform->SetIsActive(transform_is_active); c_transform->SetIsActive(transform_is_active); } ImGui::Separator(); // --- POSITION --- ImGui::Text("Position"); ImGui::SameLine(100.0f); float3 position = c_transform->GetLocalPosition(); if (ImGui::DragFloat3("P", (float*)&position, 0.05f, 0.0f, 0.0f, "%.3f", NULL)) { c_transform->SetLocalPosition(position); } // --- ROTATION --- ImGui::Text("Rotation"); ImGui::SameLine(100.0f); /*float3 rotation = transform->GetLocalEulerRotation(); if (ImGui::DragFloat3("R", (float*)&rotation, 1.0f, 0.0f, 0.0f, "%.3f", NULL)) { transform->SetLocalEulerRotation(rotation); }*/ float3 rotation = c_transform->GetLocalEulerRotation() * RADTODEG; if (ImGui::DragFloat3("R", (float*)&rotation, 1.0f, 0.0f, 0.0f, "%.3f", NULL)) { c_transform->SetLocalRotation(rotation * DEGTORAD); } // --- SCALE --- ImGui::Text("Scale"); ImGui::SameLine(100.0f); float3 scale = c_transform->GetLocalScale(); if (ImGui::DragFloat3("S", (float*)&scale, 0.05f, 0.0f, 0.0f, "%.3f", NULL)) { c_transform->SetLocalScale(scale); } } if (!show) { LOG("[ERROR] Transform components cannot be deleted!"); } ImGui::Separator(); } } void E_Inspector::DrawMeshComponent(C_Mesh* c_mesh) { bool show = true; if (ImGui::CollapsingHeader("Mesh", &show, ImGuiTreeNodeFlags_DefaultOpen)) { if (c_mesh != nullptr) { // --- IS ACTIVE --- bool mesh_is_active = c_mesh->IsActive(); if (ImGui::Checkbox("Mesh Is Active", &mesh_is_active)) { c_mesh->SetIsActive(mesh_is_active); } ImGui::Separator(); // --- FILE PATH --- ImGui::Text("File:"); ImGui::SameLine(); ImGui::TextColored(ImVec4(0.0f, 1.0f, 0.0f, 1.0f), "%s", c_mesh->GetMeshFile()); ImGui::Separator(); // --- MESH DATA --- ImGui::TextColored(ImVec4(0.0f, 1.0f, 1.0f, 1.0f), "Mesh Data:"); uint num_vertices = 0; uint num_normals = 0; uint num_tex_coords = 0; uint num_indices = 0; c_mesh->GetMeshData(num_vertices, num_normals, num_tex_coords, num_indices); ImGui::Text("Vertices:"); ImGui::SameLine(); ImGui::TextColored(ImVec4(1.0f, 1.0f, 0.0f, 1.0f), " %u", num_vertices); ImGui::Text("Normals:"); ImGui::SameLine(); ImGui::TextColored(ImVec4(1.0f, 1.0f, 0.0f, 1.0f), " %u", num_normals); ImGui::Text("Tex Coords:"); ImGui::SameLine(); ImGui::TextColored(ImVec4(1.0f, 1.0f, 0.0f, 1.0f), "%u", num_tex_coords); ImGui::Text("Indices:"); ImGui::SameLine(); ImGui::TextColored(ImVec4(1.0f, 1.0f, 0.0f, 1.0f), " %u", num_indices); ImGui::Separator(); // --- DRAW MODE --- ImGui::TextColored(ImVec4(0.0f, 1.0f, 1.0f, 1.0f), "Draw Mode:"); bool show_wireframe = c_mesh->GetShowWireframe(); if (ImGui::Checkbox("Show Wireframe", &show_wireframe)) { c_mesh->SetShowWireframe(show_wireframe); } bool show_bounding_box = c_mesh->GetShowBoundingBox(); if (ImGui::Checkbox("Show Bounding Box", &show_bounding_box)) { c_mesh->SetShowBoundingBox(show_bounding_box); c_mesh->GetOwner()->show_bounding_boxes = show_bounding_box; } bool draw_vert_normals = c_mesh->GetDrawVertexNormals(); if (ImGui::Checkbox("Draw Vertex Normals", &draw_vert_normals)) { c_mesh->SetDrawVertexNormals(draw_vert_normals); } bool draw_face_normals = c_mesh->GetDrawFaceNormals(); if (ImGui::Checkbox("Draw Face Normals", &draw_face_normals)) { c_mesh->SetDrawFaceNormals(draw_face_normals); } } else { LOG("[ERROR] Could not get the Mesh Component from %s Game Object!", c_mesh->GetOwner()->GetName()); } if (!show) { component_to_delete = c_mesh; show_delete_component_popup = true; } ImGui::Separator(); } } void E_Inspector::DrawMaterialComponent(C_Material* c_material) { bool show = true; if (ImGui::CollapsingHeader("Material", &show, ImGuiTreeNodeFlags_DefaultOpen)) { if (c_material != nullptr) { bool material_is_active = c_material->IsActive(); if (ImGui::Checkbox("Material Is Active", &material_is_active)) { c_material->SetIsActive(material_is_active); } ImGui::Separator(); // --- MATERIAL PATH --- ImGui::Text("File:"); ImGui::SameLine(); ImGui::TextColored(ImVec4(0.0f, 1.0f, 0.0f, 1.0f), "%s", c_material->GetTextureFile()); ImGui::Separator(); // --- MATERIAL COLOR & ALPHA --- ImGui::TextColored(ImVec4(0.0f, 1.0f, 1.0f, 1.0f), "Material Data:"); Color color = c_material->GetMaterialColour(); if (ImGui::ColorEdit3("Diffuse Color", (float*)&color, ImGuiColorEditFlags_NoAlpha)) { c_material->SetMaterialColour(color); } if (ImGui::SliderFloat("Diffuse Alpha", (float*)&color.a, 0.0f, 1.0f, "%.3f")) { c_material->SetMaterialColour(color); } ImGui::Separator(); // --- TEXTURE DATA --- DisplayTextureData(c_material); ImGui::Separator(); // --- MAIN MAPS --- ImGui::TextColored(ImVec4(0.0f, 1.0f, 1.0f, 1.0f), "Main Maps:"); if (ImGui::Combo("Textures(WIP)", &map_to_display, "Diffuse\0Specular\0Ambient\0Height\0Normal\0")) { LOG("[SCENE] Changed to map %d", map_to_display); } bool use_checkered_tex = c_material->UseDefaultTexture(); if (ImGui::Checkbox("Use Default Texture", &use_checkered_tex)) { c_material->SetUseDefaultTexture(use_checkered_tex); } // --- TEXTURE DISPLAY --- TextureDisplay(c_material); } else { LOG("[ERROR] Could not get the Material Component from %s Game Object!", c_material->GetOwner()->GetName()); } if (!show) { component_to_delete = c_material; show_delete_component_popup = true; } ImGui::Separator(); } } void E_Inspector::DrawLightComponent(C_Light* c_light) { bool show = true; if (ImGui::CollapsingHeader("Light", &show, ImGuiTreeNodeFlags_DefaultOpen)) { if (c_light != nullptr) { bool light_is_active = c_light->IsActive(); if (ImGui::Checkbox("Light Is Active", &light_is_active)) { c_light->SetIsActive(light_is_active); } ImGui::Separator(); ImGui::Text("WORK IN PROGRESS"); } if (!show) { component_to_delete = c_light; show_delete_component_popup = true; } ImGui::Separator(); } } void E_Inspector::DrawCameraComponent(C_Camera* c_camera) { bool show = true; if (ImGui::CollapsingHeader("Camera", &show, ImGuiTreeNodeFlags_DefaultOpen)) { if (c_camera != nullptr) { bool camera_is_active = c_camera->IsActive(); if (ImGui::Checkbox("Camera Is Active", &camera_is_active)) { c_camera->SetIsActive(camera_is_active); } ImGui::Separator(); ImGui::TextColored(ImVec4(0.0f, 1.0f, 1.0f, 1.0f), "Camera Flags:"); bool camera_is_culling = c_camera->IsCulling(); if (ImGui::Checkbox("Culling", &camera_is_culling)) { c_camera->SetIsCulling(camera_is_culling); } bool camera_is_orthogonal = c_camera->OrthogonalView(); if (ImGui::Checkbox("Orthogonal", &camera_is_orthogonal)) { c_camera->SetOrthogonalView(camera_is_orthogonal); } bool frustum_is_hidden = c_camera->FrustumIsHidden(); if (ImGui::Checkbox("Hide Frustum", &frustum_is_hidden)) { c_camera->SetFrustumIsHidden(frustum_is_hidden); } ImGui::Separator(); ImGui::TextColored(ImVec4(0.0f, 1.0f, 1.0f, 1.0f), "Frustum Settings:"); float near_plane_distance = c_camera->GetNearPlaneDistance(); if (ImGui::SliderFloat("Near Plane", &near_plane_distance, 0.1f, 1000.0f, "%.3f", 0)) { c_camera->SetNearPlaneDistance(near_plane_distance); } float far_plane_distance = c_camera->GetFarPlaneDistance(); if (ImGui::SliderFloat("Far Plane", &far_plane_distance, 0.1f, 1000.0f, "%.3f", 0)) { c_camera->SetFarPlaneDistance(far_plane_distance); } int fov = (int)c_camera->GetVerticalFOV(); uint min_fov = 0; uint max_fov = 0; c_camera->GetMinMaxFOV(min_fov, max_fov); if (ImGui::SliderInt("FOV", &fov, min_fov, max_fov, "%d")) { c_camera->SetVerticalFOV((float)fov); } ImGui::Separator(); ImGui::TextColored(ImVec4(0.0f, 1.0f, 1.0f, 1.0f), "Camera Selection:"); if (ImGui::Button("Set as Current Camera")) { App->editor->SetCurrentCameraThroughEditor(c_camera); } if (ImGui::Button("Return to Master Camera")) { App->editor->SetMasterCameraThroughEditor(); } } if (!show) { component_to_delete = c_camera; show_delete_component_popup = true; } ImGui::Separator(); } } void E_Inspector::AddComponentCombo(GameObject* selected_game_object) { ImGui::Combo("##", &component_type, "Add Component\0Transform\0Mesh\0Material\0Light\0Camera"); ImGui::SameLine(); if ((ImGui::Button("ADD"))) { if (component_type != (int)COMPONENT_TYPE::NONE) { selected_game_object->CreateComponent((COMPONENT_TYPE)component_type); } } } void E_Inspector::DeleteComponentPopup(GameObject* selected_game_object) { std::string title = "Delete "; // Generating the specific string for the Popup title. title += component_to_delete->GetNameFromType(); // The string will be specific to the component to delete. title += " Component?"; // ------------------------------------------------------- ImGui::OpenPopup(title.c_str()); bool show = true; // Dummy bool to close the popup without having to click the "CONFIRM" or "CANCEL" Buttons. if (ImGui::BeginPopupModal(title.c_str(), &show)) { ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.0f, 1.0f, 0.0f, 0.25f)); if (ImGui::Button("CONFIRM")) // CONFIRM Button. Will delete the component to delete. { selected_game_object->DeleteComponent(component_to_delete); component_to_delete = nullptr; show_delete_component_popup = false; ImGui::CloseCurrentPopup(); } ImGui::PopStyleColor(); ImGui::SameLine(); ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(1.0f, 0.0f, 0.0f, 0.25f)); if (ImGui::Button("CANCEL")) // CANCEL Button. Will close the Popup. { component_to_delete = nullptr; show_delete_component_popup = false; ImGui::CloseCurrentPopup(); } ImGui::PopStyleColor(); if (!show) // Popup cross. Will close the Popup. UX. { component_to_delete = nullptr; show_delete_component_popup = false; ImGui::CloseCurrentPopup(); } ImGui::EndPopup(); } } void E_Inspector::DisplayTextureData(C_Material* c_material) { ImGui::TextColored(ImVec4(0.0f, 1.0f, 1.0f, 1.0f), "Texture Data:"); uint id = 0; uint width = 0; uint height = 0; uint depth = 0; uint bpp = 0; uint size = 0; std::string format = "NONE"; bool compressed = 0; c_material->GetTextureInfo(id, width, height, depth, bpp, size, format, compressed); ImGui::Text("Texture ID:"); ImGui::SameLine(); ImGui::TextColored(ImVec4(1.0f, 1.0f, 0.0f, 1.0f), "%u", id); ImGui::Text("Width:"); ImGui::SameLine(); ImGui::TextColored(ImVec4(1.0f, 1.0f, 0.0f, 1.0f), " %upx", width); ImGui::Text("Height:"); ImGui::SameLine(); ImGui::TextColored(ImVec4(1.0f, 1.0f, 0.0f, 1.0f), " %upx", height); ImGui::Text("Depth:"); ImGui::SameLine(); ImGui::TextColored(ImVec4(1.0f, 1.0f, 0.0f, 1.0f), " %u", depth); ImGui::Text("Bpp:"); ImGui::SameLine(); ImGui::TextColored(ImVec4(1.0f, 1.0f, 0.0f, 1.0f), " %uB", bpp); ImGui::Text("Size:"); ImGui::SameLine(); ImGui::TextColored(ImVec4(1.0f, 1.0f, 0.0f, 1.0f), " %uB", size); ImGui::Text("Format:"); ImGui::SameLine(); ImGui::TextColored(ImVec4(1.0f, 1.0f, 0.0f, 1.0f), " %s", format.c_str()); ImGui::Text("Compressed:"); ImGui::SameLine(); ImGui::TextColored(ImVec4(1.0f, 1.0f, 0.0f, 1.0f), "%s", compressed ? "True" : "False"); } void E_Inspector::TextureDisplay(C_Material* c_material) { ImTextureID tex_id = 0; ImVec2 display_size = { ImGui::GetWindowWidth() * 0.925f , ImGui::GetWindowWidth() * 0.925f }; // Display Size will be 7.5% smaller than the Window Width. ImVec4 tint = { 1.0f, 1.0f, 1.0f, 1.0f }; ImVec4 border_color = { 0.0f, 1.0f, 0.0f, 1.0f }; if (c_material->UseDefaultTexture()) { //tex_id = (ImTextureID)App->renderer->GetDebugTextureID(); tex_id = (ImTextureID)App->renderer->GetSceneRenderTexture(); } else { tex_id = (ImTextureID)c_material->GetTextureID(); } if (tex_id != 0) { ImGui::TextColored(ImVec4(0.0f, 1.0f, 1.0f, 1.0f), "Texture Display:"); ImGui::Spacing(); ImGui::Image(tex_id, display_size, ImVec2(1.0f, 0.0f), ImVec2(0.0f, 1.0f), tint, border_color); // ImGui has access to OpenGL's buffers, so only the Texture Id is required. } }
28.143092
176
0.664952
xsiro
8a5f3971feb316dccd0cd8ae58e8d869d2235c68
317
cpp
C++
shared/test/common/helpers/kernel_binary_helper_hash_value.cpp
mattcarter2017/compute-runtime
1f52802aac02c78c19d5493dd3a2402830bbe438
[ "Intel", "MIT" ]
null
null
null
shared/test/common/helpers/kernel_binary_helper_hash_value.cpp
mattcarter2017/compute-runtime
1f52802aac02c78c19d5493dd3a2402830bbe438
[ "Intel", "MIT" ]
null
null
null
shared/test/common/helpers/kernel_binary_helper_hash_value.cpp
mattcarter2017/compute-runtime
1f52802aac02c78c19d5493dd3a2402830bbe438
[ "Intel", "MIT" ]
null
null
null
/* * Copyright (C) 2020-2022 Intel Corporation * * SPDX-License-Identifier: MIT * */ #include "shared/test/common/helpers/kernel_binary_helper.h" const std::string KernelBinaryHelper::BUILT_INS("7998916142903730155"); const std::string KernelBinaryHelper::BUILT_INS_WITH_IMAGES("16526264370178379440_images");
26.416667
91
0.785489
mattcarter2017
8a63695aa047f3e4cb64fc8067433206277554de
794
cpp
C++
examples/src/vertices.cpp
311Volt/axxegro
61d7a1fb48f9bb581e0f4171d58499cf8c543728
[ "MIT" ]
null
null
null
examples/src/vertices.cpp
311Volt/axxegro
61d7a1fb48f9bb581e0f4171d58499cf8c543728
[ "MIT" ]
null
null
null
examples/src/vertices.cpp
311Volt/axxegro
61d7a1fb48f9bb581e0f4171d58499cf8c543728
[ "MIT" ]
null
null
null
#include <axxegro/axxegro.hpp> /** * @file * * a quick example on how to create custom vertex declarations * and use them to draw primitives */ struct MyVertex { float x,y; float u,v; }; struct MyVertexDecl: public al::CustomVertexDecl<MyVertex> { AXXEGRO_VERTEX_ATTR_BEGIN() AXXEGRO_VERTEX_ATTR(x, ALLEGRO_PRIM_POSITION, ALLEGRO_PRIM_FLOAT_2) AXXEGRO_VERTEX_ATTR(u, ALLEGRO_PRIM_TEX_COORD_PIXEL, ALLEGRO_PRIM_FLOAT_2) }; int main() { al::FullInit(); al::Display disp(800, 600); al::TargetBitmap.clearToColor(al::RGB(100,100,100)); al::Bitmap bg("data/bg.jpg"); std::vector<MyVertex> vtxs{ {1,1, 0,0}, {2,2, 0,1000}, {3,1, 1000,0} }; al::Transform().scale({100, 100}).use(); al::DrawPrim<MyVertexDecl>(vtxs, bg); al::CurrentDisplay.flip(); al::Sleep(2.0); }
19.365854
75
0.695214
311Volt
8a6cd0b1d672f70432c0c2407dca21b59ab7e1e5
1,600
cpp
C++
TxtAdv/StoryPoint.cpp
doc97/TxtAdv
c74163548f5c68202a06d0ad320fbd5b687d6f1a
[ "MIT" ]
null
null
null
TxtAdv/StoryPoint.cpp
doc97/TxtAdv
c74163548f5c68202a06d0ad320fbd5b687d6f1a
[ "MIT" ]
31
2018-12-22T10:30:43.000Z
2019-01-16T11:32:23.000Z
TxtAdv/StoryPoint.cpp
doc97/TxtAdv
c74163548f5c68202a06d0ad320fbd5b687d6f1a
[ "MIT" ]
null
null
null
/********************************************************** * License: The MIT License * https://www.github.com/doc97/TxtAdv/blob/master/LICENSE **********************************************************/ #include "StoryPoint.h" namespace txt { StoryPoint::StoryPoint() : m_name(""), m_text("") { } StoryPoint::StoryPoint(const std::string& name) : m_name(name), m_text("") { } StoryPoint::~StoryPoint() { } void StoryPoint::SetText(const Text& other) { m_text = other; } void StoryPoint::SetTextStr(const std::string& text) { m_text = Text{ text }; } void StoryPoint::SetStyleSheet(const TextStyleSheet style) { m_style = style; } void StoryPoint::SetParser(TextParser* parser) { m_parser = parser; } void StoryPoint::SetMarkup(TextMarkup* markup) { m_markup = markup; } void StoryPoint::SetHandlers(const std::vector<std::shared_ptr<ResponseHandler>>& handlers) { m_handlers = handlers; } std::string StoryPoint::GetName() const { return m_name; } std::string StoryPoint::GetTextStr() const { return GetText().Str(); } Text StoryPoint::GetText() const { Text parsed = m_text; // copy assignment if (m_markup) parsed = m_markup->ParseText(m_parser ? m_parser->ParseText(m_text.Str()) : m_text.Str()); else if (m_parser) parsed = m_parser->ParseText(m_text.Str()); m_style.Apply(parsed); return parsed; } size_t StoryPoint::GetHandlerCount() const { return m_handlers.size(); } std::vector<std::shared_ptr<ResponseHandler>> StoryPoint::GetHandlers() const { return m_handlers; } } // namespace txt
18.181818
98
0.633125
doc97
8a6dd1ec4074c7c08e1cd17ba556ca10795a9efd
1,294
cpp
C++
mwget_0.1.0.orig/src/debug.cpp
ruanhailiang/mwget
9274be70a68baa6ce4bcad96d1b2c09e14efd8b5
[ "MIT" ]
null
null
null
mwget_0.1.0.orig/src/debug.cpp
ruanhailiang/mwget
9274be70a68baa6ce4bcad96d1b2c09e14efd8b5
[ "MIT" ]
null
null
null
mwget_0.1.0.orig/src/debug.cpp
ruanhailiang/mwget
9274be70a68baa6ce4bcad96d1b2c09e14efd8b5
[ "MIT" ]
null
null
null
/* Myget - A download accelerator for GNU/Linux * Homepage: http://myget.sf.net * Copyright (C) 2005- xiaosuo * * 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. */ #include <cassert> #include <cstdarg> #include <cstdio> #include "debug.h" bool global_debug = false; void debug_log(const char *fmt, ...) { va_list vp; const char *end; assert(fmt != NULL); if(!global_debug) return; va_start(vp, fmt); // if the fmt contain somesth. like %c and %d, but the varargs is empty, // the output will be error, so use the function like this debug_log("%s", str); vfprintf(stderr, fmt, vp); va_end(vp); };
30.093023
81
0.710201
ruanhailiang
8a6e329244309279560096772ea5c94eb91d0c85
524
hpp
C++
include/RED4ext/Scripting/Natives/Generated/ink/StreetSignsLayer.hpp
jackhumbert/RED4ext.SDK
2c55eccb83beabbbe02abae7945af8efce638fca
[ "MIT" ]
42
2020-12-25T08:33:00.000Z
2022-03-22T14:47:07.000Z
include/RED4ext/Scripting/Natives/Generated/ink/StreetSignsLayer.hpp
jackhumbert/RED4ext.SDK
2c55eccb83beabbbe02abae7945af8efce638fca
[ "MIT" ]
38
2020-12-28T22:36:06.000Z
2022-02-16T11:25:47.000Z
include/RED4ext/Scripting/Natives/Generated/ink/StreetSignsLayer.hpp
jackhumbert/RED4ext.SDK
2c55eccb83beabbbe02abae7945af8efce638fca
[ "MIT" ]
20
2020-12-28T22:17:38.000Z
2022-03-22T17:19:01.000Z
#pragma once // This file is generated from the Game's Reflection data #include <cstdint> #include <RED4ext/Common.hpp> #include <RED4ext/Scripting/Natives/Generated/ink/WorldFluffLayer.hpp> namespace RED4ext { namespace ink { struct StreetSignsLayer : ink::WorldFluffLayer { static constexpr const char* NAME = "inkStreetSignsLayer"; static constexpr const char* ALIAS = NAME; uint8_t unk1F8[0x250 - 0x1F8]; // 1F8 }; RED4EXT_ASSERT_SIZE(StreetSignsLayer, 0x250); } // namespace ink } // namespace RED4ext
23.818182
70
0.751908
jackhumbert
8a6fdaeb71786e3cca54b63bcf1720eba1fa2378
911
cpp
C++
Cplus/ColoringABorder.cpp
JumHorn/leetcode
1447237ae8fc3920b19f60b30c71a84b088cc200
[ "MIT" ]
1
2018-01-22T12:06:28.000Z
2018-01-22T12:06:28.000Z
Cplus/ColoringABorder.cpp
JumHorn/leetcode
1447237ae8fc3920b19f60b30c71a84b088cc200
[ "MIT" ]
null
null
null
Cplus/ColoringABorder.cpp
JumHorn/leetcode
1447237ae8fc3920b19f60b30c71a84b088cc200
[ "MIT" ]
null
null
null
#include <cmath> #include <vector> using namespace std; class Solution { public: vector<vector<int>> colorBorder(vector<vector<int>> &grid, int r0, int c0, int color) { int M = grid.size(), N = grid[0].size(); vector<vector<int>> seen(M, vector<int>(N)); dfs(grid, r0, c0, grid[r0][c0], color, seen); return grid; } int dfs(vector<vector<int>> &grid, int row, int col, int oldcolor, int color, vector<vector<int>> &seen) { int M = grid.size(), N = grid[0].size(); if (row < 0 || row >= M || col < 0 || col >= N) return 0; if (seen[row][col] != 0) //这个判断必须在这两个判断之间 return 1; if (grid[row][col] != oldcolor) return 0; seen[row][col] = 1; //board dfs direction int path[5] = {-1, 0, 1, 0, -1}; int res = 0; for (int i = 0; i < 4; ++i) res += dfs(grid, row + path[i], col + path[i + 1], oldcolor, color, seen); if (res < 4) grid[row][col] = color; return 1; } };
26.028571
105
0.579583
JumHorn
8a7302d7adb35de5efc2c033185697fdc3d159ff
2,586
hpp
C++
src/SingleLayerOptics/src/BSDFLayerMaker.hpp
bakonyidani/Windows-CalcEngine
afa4c4a9f88199c6206af8bc994a073931fc8b91
[ "BSD-3-Clause-LBNL" ]
null
null
null
src/SingleLayerOptics/src/BSDFLayerMaker.hpp
bakonyidani/Windows-CalcEngine
afa4c4a9f88199c6206af8bc994a073931fc8b91
[ "BSD-3-Clause-LBNL" ]
null
null
null
src/SingleLayerOptics/src/BSDFLayerMaker.hpp
bakonyidani/Windows-CalcEngine
afa4c4a9f88199c6206af8bc994a073931fc8b91
[ "BSD-3-Clause-LBNL" ]
null
null
null
#ifndef BSDFLAYERMAKER_H #define BSDFLAYERMAKER_H #include <memory> namespace SingleLayerOptics { enum class DistributionMethod { UniformDiffuse, DirectionalDiffuse }; class ICellDescription; class CMaterial; class CBSDFHemisphere; class CBSDFLayer; class CBaseCell; // Class to simplify interface for BSDF layer creation class CBSDFLayerMaker { public: static std::shared_ptr<CBSDFLayer> getSpecularLayer(const std::shared_ptr<CMaterial> & t_Material, const CBSDFHemisphere & t_BSDF); static std::shared_ptr<CBSDFLayer> getCircularPerforatedLayer(const std::shared_ptr<CMaterial> & t_Material, const CBSDFHemisphere & t_BSDF, double x, double y, double thickness, double radius); static std::shared_ptr<CBSDFLayer> getRectangularPerforatedLayer(const std::shared_ptr<CMaterial> & t_Material, const CBSDFHemisphere & t_BSDF, double x, double y, double thickness, double xHole, double yHole); static std::shared_ptr<CBSDFLayer> getVenetianLayer(const std::shared_ptr<CMaterial> & t_Material, const CBSDFHemisphere & t_BSDF, double slatWidth, double slatSpacing, double slatTiltAngle, double curvatureRadius, size_t numOfSlatSegments, DistributionMethod method = DistributionMethod::DirectionalDiffuse); static std::shared_ptr<CBSDFLayer> getPerfectlyDiffuseLayer(const std::shared_ptr<CMaterial> & t_Material, const CBSDFHemisphere & t_BSDF); static std::shared_ptr<CBSDFLayer> getWovenLayer(const std::shared_ptr<CMaterial> & t_Material, const CBSDFHemisphere & t_BSDF, double diameter, double spacing); private: std::shared_ptr<CBSDFLayer> m_Layer; std::shared_ptr<CBaseCell> m_Cell; }; } // namespace SingleLayerOptics #endif
35.424658
95
0.518948
bakonyidani
8a779ceb10a4e5ac9f46bd58cdad85d7961cce40
10,324
cpp
C++
emulator/src/mame/video/tecmo_spr.cpp
rjw57/tiw-computer
5ef1c79893165b8622d1114d81cd0cded58910f0
[ "MIT" ]
1
2022-01-15T21:38:38.000Z
2022-01-15T21:38:38.000Z
emulator/src/mame/video/tecmo_spr.cpp
rjw57/tiw-computer
5ef1c79893165b8622d1114d81cd0cded58910f0
[ "MIT" ]
null
null
null
emulator/src/mame/video/tecmo_spr.cpp
rjw57/tiw-computer
5ef1c79893165b8622d1114d81cd0cded58910f0
[ "MIT" ]
null
null
null
// license:BSD-3-Clause // copyright-holders:David Haywood /* Various Tecmo Sprite implementations - the various sprite implementations here are slightly different but can clearly be refactored to use a common base class for the chained drawing even if the position of the attributes etc. varies between PCB / chip. - what chips are involved in implementing these schemes? ttl logic on early ones? customs on later? */ #include "emu.h" #include "tecmo_spr.h" #include "screen.h" DEFINE_DEVICE_TYPE(TECMO_SPRITE, tecmo_spr_device, "tecmo_spr", "Tecmo Chained Sprites") tecmo_spr_device::tecmo_spr_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock) : device_t(mconfig, TECMO_SPRITE, tag, owner, clock) , m_gfxregion(0) , m_bootleg(0) , m_yoffset(0) { } void tecmo_spr_device::device_start() { } void tecmo_spr_device::device_reset() { } static const uint8_t layout[8][8] = { { 0, 1, 4, 5, 16, 17, 20, 21 }, { 2, 3, 6, 7, 18, 19, 22, 23 }, { 8, 9, 12, 13, 24, 25, 28, 29 }, { 10, 11, 14, 15, 26, 27, 30, 31 }, { 32, 33, 36, 37, 48, 49, 52, 53 }, { 34, 35, 38, 39, 50, 51, 54, 55 }, { 40, 41, 44, 45, 56, 57, 60, 61 }, { 42, 43, 46, 47, 58, 59, 62, 63 } }; /* sprite format (gaiden): * * word bit usage * --------+-fedcba9876543210-+---------------- * 0 | ---------------x | flip x * | --------------x- | flip y * | -------------x-- | enable * | ----------x----- | blend * | --------xx------ | sprite-tile priority * 1 | xxxxxxxxxxxxxxxx | number * 2 | --------xxxx---- | palette * | --------------xx | size: 8x8, 16x16, 32x32, 64x64 * 3 | xxxxxxxxxxxxxxxx | y position * 4 | xxxxxxxxxxxxxxxx | x position * 5,6,7| | unused */ #define NUM_SPRITES 256 void tecmo_spr_device::gaiden_draw_sprites(screen_device &screen, gfxdecode_device *gfxdecode, const rectangle &cliprect, uint16_t* spriteram, int sprite_sizey, int spr_offset_y, int flip_screen, bitmap_ind16 &sprite_bitmap) { gfx_element *gfx = gfxdecode->gfx(m_gfxregion); uint16_t *source; int sourceinc; source = spriteram; sourceinc = 8; int count = NUM_SPRITES; int screenwidth = screen.width(); int attributes_word = 0; int tilenumber_word = 1; int colour_word = 2; int yposition_word = 3; int xposition_word = 4; int xmask; if (screenwidth == 512) xmask = 512; else xmask = 256; /* draw all sprites from front to back */ while (count--) { uint32_t attributes = source[attributes_word]; int col, row; int enabled = source[attributes_word] & 0x04; if (enabled) { if (m_bootleg == 1) { // I don't think the galspinbl / hotpinbl bootlegs have blending, instead they use this bit to flicker sprites on/off each frame, so handle it here (we can't handle it in the mixing) // alternatively these sprites could just be disabled like the tiles marked with the 'mix' bit appear to be (they're only used for ball / flipper trails afaik) if (source[attributes_word] & 0x0040) { int frame = screen.frame_number() & 1; if (frame==1) enabled = 0; } } } if (enabled) { uint32_t flipx = (attributes & 1); uint32_t flipy = (attributes & 2); uint32_t color = source[colour_word]; uint32_t sizex = 1 << ((color >> 0) & 3); /* 1,2,4,8 */ uint32_t sizey = 1 << ((color >> sprite_sizey) & 3); /* 1,2,4,8 */ /* raiga & fstarfrc need something like this */ uint32_t number = (source[tilenumber_word]); if (sizex >= 2) number &= ~0x01; if (sizey >= 2) number &= ~0x02; if (sizex >= 4) number &= ~0x04; if (sizey >= 4) number &= ~0x08; if (sizex >= 8) number &= ~0x10; if (sizey >= 8) number &= ~0x20; int ypos = (source[yposition_word] + spr_offset_y) & 0x01ff; int xpos = source[xposition_word] & ((xmask*2)-1); color = (color >> 4) & 0x0f; /* wraparound */ if (xpos >= xmask) xpos -= (xmask*2); if (ypos >= 256) ypos -= 512; if (flip_screen) { flipx = !flipx; flipy = !flipy; xpos = 256 - (8 * sizex) - xpos; ypos = 256 - (8 * sizey) - ypos; if (xpos <= -256) xpos += 512; if (ypos <= -256) ypos += 512; } bitmap_ind16* bitmap; // this contains the blend bit and the priority bits, the spbactn proto uses 0x0300 for priority, spbactn uses 0x0030, others use 0x00c0 color |= (source[attributes_word] & 0x03f0); bitmap = &sprite_bitmap; for (row = 0; row < sizey; row++) { for (col = 0; col < sizex; col++) { int sx = xpos + 8 * (flipx ? (sizex - 1 - col) : col); int sy = ypos + 8 * (flipy ? (sizey - 1 - row) : row); gfx->transpen_raw(*bitmap, cliprect, number + layout[row][col], gfx->colorbase() + color * gfx->granularity(), flipx, flipy, sx, sy, 0); } } } source += sourceinc; } } /* NOT identical to the version above */ /* sprite format (tecmo.c): * * byte bit usage * --------+-76543210-+---------------- 0 | xxxxx--- | bank / upper tile bits | -----x-- | enable | ------x- | flip y | -------x | flip x 1 | xxxxxxxx | tile number (low bits) 2 | ------xx | size 3 | xx-------| priority | --x----- | upper y co-ord | ---x---- | upper x co-ord | ----xxxx | colour 4 | xxxxxxxx | ypos 5 | xxxxxxxx | xpos 6 | -------- | 7 | -------- | */ void tecmo_spr_device::draw_sprites_8bit(screen_device &screen, bitmap_ind16 &bitmap, gfxdecode_device *gfxdecode, const rectangle &cliprect, uint8_t* spriteram, int size, int video_type, int flip_screen) { int offs; for (offs = size-8;offs >= 0;offs -= 8) { int flags = spriteram[offs+3]; int priority = flags>>6; int bank = spriteram[offs+0]; if (bank & 4) { /* visible */ int which = spriteram[offs+1]; int code,xpos,ypos,flipx,flipy,priority_mask,x,y; int size = spriteram[offs + 2] & 3; if (video_type != 0) /* gemini, silkworm */ code = which + ((bank & 0xf8) << 5); else /* rygar */ code = which + ((bank & 0xf0) << 4); code &= ~((1 << (size*2)) - 1); size = 1 << size; xpos = spriteram[offs + 5] - ((flags & 0x10) << 4); ypos = spriteram[offs + 4] - ((flags & 0x20) << 3); flipx = bank & 1; flipy = bank & 2; if (flip_screen) { xpos = 256 - (8 * size) - xpos; ypos = 256 - (8 * size) - ypos; flipx = !flipx; flipy = !flipy; } /* bg: 1; fg:2; text: 4 */ switch (priority) { default: case 0x0: priority_mask = 0; break; case 0x1: priority_mask = 0xf0; break; /* obscured by text layer */ case 0x2: priority_mask = 0xf0|0xcc; break; /* obscured by foreground */ case 0x3: priority_mask = 0xf0|0xcc|0xaa; break; /* obscured by bg and fg */ } for (y = 0;y < size;y++) { for (x = 0;x < size;x++) { int sx = xpos + 8*(flipx?(size-1-x):x); int sy = ypos + 8*(flipy?(size-1-y):y); gfxdecode->gfx(1)->prio_transpen(bitmap,cliprect, code + layout[y][x], flags & 0xf, flipx,flipy, sx,sy, screen.priority(), priority_mask,0); } } } } } /* sprite format (wc90.c): - similar to the 16-bit one * * byte bit usage * --------+-76543210-+---------------- */ void tecmo_spr_device::draw_wc90_sprites(bitmap_ind16 &bitmap, const rectangle &cliprect, gfxdecode_device *gfxdecode, uint8_t* spriteram, int size, int priority ) { int offs, flags, code; /* draw all visible sprites of specified priority */ for (offs = 0;offs < size;offs += 16){ int bank = spriteram[offs+0]; if ( ( bank >> 4 ) == priority ) { if ( bank & 4 ) { /* visible */ code = ( spriteram[offs+2] ) + ( spriteram[offs+3] << 8 ); int xpos = spriteram[offs + 8] + ( (spriteram[offs + 9] & 3 ) << 8 ); int ypos = spriteram[offs + 6] + m_yoffset; ypos &= 0xff; // sprite wrap right on edge (top @ ROT0) of pac90 ypos = ypos - ((spriteram[offs + 7] & 1) << 8); // sprite wrap on top of wc90 if (xpos >= 0x0300) xpos -= 0x0400; flags = spriteram[offs+4]; int sizex = 1 << ((flags >> 0) & 3); int sizey = 1 << ((flags >> 2) & 3); int flipx = bank & 1; int flipy = bank & 2; for (int y = 0;y < sizey;y++) { for (int x = 0;x < sizex;x++) { int sx = xpos + 8*(flipx?(sizex-1-x):x); int sy = ypos + 8*(flipy?(sizey-1-y):y); gfxdecode->gfx(3)->transpen(bitmap,cliprect, code + layout[y][x], (flags>>4) & 0xf, flipx,flipy, sx,sy, 0); } } } } } } void tecmo_spr_device::tbowl_draw_sprites(bitmap_ind16 &bitmap,const rectangle &cliprect, gfxdecode_device *gfxdecode, int xscroll, uint8_t* spriteram) { int offs; for (offs = 0;offs < 0x800;offs += 8) { if (spriteram[offs+0] & 0x80) /* enable */ { int code,color,sizex,sizey,flipx,flipy,xpos,ypos; int x,y;//,priority,priority_mask; code = (spriteram[offs+2])+(spriteram[offs+1]<<8); color = (spriteram[offs+3])&0x1f; sizex = 1 << ((spriteram[offs+0] & 0x03) >> 0); sizey = 1 << ((spriteram[offs+0] & 0x0c) >> 2); flipx = (spriteram[offs+0])&0x20; flipy = 0; xpos = (spriteram[offs+6])+((spriteram[offs+4]&0x03)<<8); ypos = (spriteram[offs+5])+((spriteram[offs+4]&0x10)<<4); /* bg: 1; fg:2; text: 4 */ for (y = 0;y < sizey;y++) { for (x = 0;x < sizex;x++) { int sx = xpos + 8*(flipx?(sizex-1-x):x); int sy = ypos + 8*(flipy?(sizey-1-y):y); sx -= xscroll; gfxdecode->gfx(3)->transpen(bitmap,cliprect, code + layout[y][x], color, flipx,flipy, sx,sy,0 ); /* wraparound */ gfxdecode->gfx(3)->transpen(bitmap,cliprect, code + layout[y][x], color, flipx,flipy, sx,sy-0x200,0 ); /* wraparound */ gfxdecode->gfx(3)->transpen(bitmap,cliprect, code + layout[y][x], color, flipx,flipy, sx-0x400,sy,0 ); /* wraparound */ gfxdecode->gfx(3)->transpen(bitmap,cliprect, code + layout[y][x], color, flipx,flipy, sx-0x400,sy-0x200,0 ); } } } } }
24.698565
224
0.55618
rjw57
8a7b53a2db53c347ac4a3ac26da03579ef490e22
14,405
hpp
C++
src/viewpoint.hpp
alexcoplan/p2proj
4920ce561a05a2977776164f602ac8d0d6a68023
[ "MIT" ]
null
null
null
src/viewpoint.hpp
alexcoplan/p2proj
4920ce561a05a2977776164f602ac8d0d6a68023
[ "MIT" ]
null
null
null
src/viewpoint.hpp
alexcoplan/p2proj
4920ce561a05a2977776164f602ac8d0d6a68023
[ "MIT" ]
null
null
null
#ifndef AJC_HGUARD_VIEWPOINT #define AJC_HGUARD_VIEWPOINT #include "sequence_model.hpp" #include <type_traits> #define DEFAULT_HIST 3 /* Predictor * * The fully abstract interface implemented by all viewpoints */ template<class EventStructure, class T_predict> class Predictor { public: virtual EventDistribution<T_predict> predict(const std::vector<EventStructure> &es) const = 0; virtual void learn(const std::vector<EventStructure> &es) = 0; virtual void learn_from_tail(const std::vector<EventStructure> &es) = 0; virtual void set_history(unsigned int h) = 0; virtual unsigned int get_history() const = 0; virtual void reset() = 0; // undoes any training (useful for short-term models) virtual bool can_predict(const std::vector<EventStructure> &es) const = 0; virtual std::string vp_name() const = 0; virtual Predictor *clone() const = 0; virtual ~Predictor(); }; template<class ES, class T> inline Predictor<ES,T>::~Predictor() {} namespace template_magic { /* IsDerived<T> * * This is a bit of template metaprogramming magic to check if a type has a * static member called `derived_from`. * * The motivation for this is that we want to handle derived types and basic * types differently inside viewpoints. * * Based on this: * https://en.wikibooks.org/wiki/More_C++_Idioms/Member_Detector */ template<typename T> class IsDerived { struct Fallback { int derived_from; }; struct Derived : T, Fallback { }; template<typename U, U> struct Check; typedef char ArrayOfOne[1]; // typedef for an array of size one. typedef char ArrayOfTwo[2]; // typedef for an array of size two. template<typename U> static ArrayOfOne & func(Check<int Fallback::*, &U::derived_from> *); template<typename U> static ArrayOfTwo & func(...); public: typedef IsDerived type; enum { value = sizeof(func<Derived>(0)) == 2 }; }; /* Beware: a bit of template wizardry to lazily-evaluate the surface type of a * type (we want lazy evaluation in case it doesn't have one). */ template<typename T> struct just_T { using type = T; }; template<typename T> struct surface_of_T { using type = typename T::derived_from; }; /* SurfaceType<T> * * If T is a derived type (see above) then SurfaceType<T> is the type that T * is derived from. Otherwise, T is its own surface type. */ template<typename T> using SurfaceType = typename std::conditional<IsDerived<T>::value, surface_of_T<T>, just_T<T>>::type::type; } template<typename T> using SurfaceType = template_magic::SurfaceType<T>; /* Viewpoint * * Abstract base class for any Viewpoint that internally uses a ContextModel * (currently, all of them). Unlike Preditor which is fully abstract, this class * contains the ContextModel and implements some of the methods from Predictor. */ template<class EventStructure, class T_viewpoint, class T_predict> class Viewpoint : public Predictor<EventStructure, T_predict> { protected: SequenceModel<T_viewpoint> model; virtual std::vector<T_viewpoint> lift(const std::vector<EventStructure> &events) const = 0; public: void reset() override { model.clear_model(); } void set_history(unsigned int h) override { model.set_history(h); } unsigned int get_history() const override { return model.get_history(); } void write_latex(std::string filename) const { model.write_latex(filename); } void learn(const std::vector<EventStructure> &events) override { model.learn_sequence(lift(events)); } void learn_from_tail(const std::vector<EventStructure> &events) override { auto lifted = lift(events); if (lifted.size() > 0) model.update_from_tail(lifted); } Viewpoint(unsigned int history) : model(history) {} }; /* GeneralViewpoint * * Concrete but generic implementation of viewpoints that uses type-specific * functionality implemented in EventStructure. * * In order to implement a viewpoint, there are two main bits of functionality * needed. We need to know how to *lift* a sequence of events of type * T_viewpoint form a stream of events of type EventStructure, i.e. * - lift : vec<EventStrcutrue> --> vec<T_viewpoint> * * We can then model sequences of type vec<T_viewpoint> using a sequence model. * Also, we need to be able to predict a distribution over T_surface given a * context (a sequence of EventStructure events) and a distribution over * T_viewpoint. We call this process "reifying" a distribution over the hidden * (viewpoint type). In the MVS formalism this is (roughly) the inverse of the * phi function. In other words: * - reify : vec<EventStructure> x dist<T_viewpoint> --> dist<T_surface> * * With GeneralViewpoints, both `lift` and `reify` are implemented as part of * the EventStructure itself, allowing us to create viewpoints on arbitrary * combinations of basic or derived types. */ template<class EventStructure, class T_vp> using GenVPBase = Viewpoint<EventStructure, T_vp, SurfaceType<T_vp>>; template<class EventStructure, class T_viewpoint> class GeneralViewpoint : public GenVPBase<EventStructure, T_viewpoint> { protected: using T_surface = SurfaceType<T_viewpoint>; using Base = GenVPBase<EventStructure, T_viewpoint>; using PredBase = Predictor<EventStructure, T_surface>; public: std::vector<T_viewpoint> lift(const std::vector<EventStructure> &events) const override { return EventStructure::template lift<T_viewpoint>(events); } EventDistribution<T_surface> predict(const std::vector<EventStructure> &ctx) const override { auto lifted = EventStructure::template lift<T_viewpoint>(ctx); auto hidden_dist = this->model.gen_successor_dist(lifted); return EventStructure::reify(ctx, hidden_dist); } bool can_predict(const std::vector<EventStructure> &) const override { // TODO: once all VPs have been replaced with GeneralViewpoints, this method // can go and we will switch to an exception-based approach to this // // this is just so that we are compatible with the existing Predictor<> // interface for now return true; } std::string vp_name() const override { return T_viewpoint::type_name; } PredBase *clone() const override { return new GeneralViewpoint(*this); } GeneralViewpoint(unsigned int hist) : Base(hist) {} GeneralViewpoint() : Base(DEFAULT_HIST) {} }; template<class EventStructure, class T_h, class T_p> using GenLinkedBase = Viewpoint<EventStructure, EventPair<T_h, T_p>, SurfaceType<T_p>>; template<class EventStructure, class T_hidden, class T_predict> class GeneralLinkedVP : public GenLinkedBase<EventStructure, T_hidden, T_predict> { protected: using T_pair = EventPair<T_hidden, T_predict>; using T_surface = SurfaceType<T_predict>; using Base = GenLinkedBase<EventStructure, T_hidden, T_predict>; using PredBase = Predictor<EventStructure, T_surface>; public: std::vector<T_pair> lift(const std::vector<EventStructure> &events) const override { // TODO: in the future this should be done with streams/iterators for // efficiency, but vectors will do for now. auto left = EventStructure::template lift<T_hidden>(events); auto right = EventStructure::template lift<T_predict>(events); return T_pair::zip_tail(left, right); } EventDistribution<T_surface> predict(const std::vector<EventStructure> &ctx) const override { auto lifted = lift(ctx); auto pair_dist = this->model.gen_successor_dist(lifted); std::array<double, T_predict::cardinality> predict_values{{0.0}}; for (auto e_predict : EventEnumerator<T_predict>()) for (auto e_hidden : EventEnumerator<T_hidden>()) { T_pair pair(e_hidden, e_predict); predict_values[e_predict.encode()] += pair_dist.probability_for(pair); } auto derived_dist = EventDistribution<T_predict>(predict_values); return EventStructure::reify(ctx, derived_dist); } bool can_predict(const std::vector<EventStructure> &) const override { // TODO: eventually remove this from the Predictor<> interface once all VPs // have been properly subsumed by these generalised VPs return true; } std::string vp_name() const override { return T_hidden::type_name + "->" + T_predict::type_name; } PredBase *clone() const override { return new GeneralLinkedVP(*this); } GeneralLinkedVP(unsigned int hist) : Base(hist) {} GeneralLinkedVP() : Base(DEFAULT_HIST) {} }; // template to model a triply-linked type. we use this template rather than // writing out the full expression partly for brevity, but also because it // enforces the same nesting convention everywhere. template<class T_a, class T_b, class T_c> using TripleLink = EventPair<EventPair<T_a, T_b>, T_c>; template<class EventStructure, class T_l, class T_r, class T_p> using TripleLinkedBase = Viewpoint<EventStructure, TripleLink<T_l, T_r, T_p>, SurfaceType<T_p>>; template<class EventStructure, class T_hleft, class T_hright, class T_predict> class TripleLinkedVP : public TripleLinkedBase<EventStructure, T_hleft, T_hright, T_predict> { protected: // set up the relevant types / template aliases using T_hidden = EventPair<T_hleft, T_hright>; using T_model = TripleLink<T_hleft, T_hright, T_predict>; using T_surface = SurfaceType<T_predict>; using Base = TripleLinkedBase<EventStructure, T_hleft, T_hright, T_predict>; using PredBase = Predictor<EventStructure, T_surface>; public: std::vector<T_model> lift(const std::vector<EventStructure> &events) const override { auto h_left = EventStructure::template lift<T_hleft>(events); auto h_right = EventStructure::template lift<T_hright>(events); auto main_es = EventStructure::template lift<T_predict>(events); auto hidden_es = T_hidden::zip_tail(h_left, h_right); return T_model::zip_tail(hidden_es, main_es); } EventDistribution<T_surface> predict(const std::vector<EventStructure> &ctx) const override { auto lifted = lift(ctx); auto triple_dist = this->model.gen_successor_dist(lifted); std::array<double, T_predict::cardinality> summed_out{{0.0}}; for (auto e_predict : EventEnumerator<T_predict>()) for(auto e_hidden : EventEnumerator<T_hidden>()) { T_model pair(e_hidden, e_predict); summed_out[e_predict.encode()] += triple_dist.probability_for(pair); } auto derived_dist = EventDistribution<T_predict>(summed_out); return EventStructure::reify(ctx, derived_dist); } bool can_predict(const std::vector<EventStructure> &) const override { return true; // TODO: see other implementations in this file } std::string vp_name() const override { return "(" + T_hleft::type_name + " x " + T_hright::type_name + ")->" + T_predict::type_name; } PredBase *clone() const override { return new TripleLinkedVP(*this); } TripleLinkedVP(unsigned int hist) : Base(hist) {} TripleLinkedVP() : Base(DEFAULT_HIST) {} }; /************************************************************ * Legacy code below here * * Use GeneralViewpoints as these are the future. ************************************************************/ template<class EventStructure, class T_hidden, class T_predict> class BasicLinkedViewpoint : public Viewpoint<EventStructure, EventPair<T_hidden, T_predict>, T_predict> { using BaseVP = Viewpoint<EventStructure, EventPair<T_hidden, T_predict>, T_predict>; std::vector<EventPair<T_hidden, T_predict>> lift(const std::vector<EventStructure> &events) const override { return EventStructure::template lift<T_hidden, T_predict>(events); } public: EventDistribution<T_predict> predict(const std::vector<EventStructure> &ctx) const override { // generate the joint distribution auto dist = this->model.gen_successor_dist(lift(ctx)); // then marginalise (sum over the hidden type) std::array<double, T_predict::cardinality> values{{0.0}}; for (auto e_predict : EventEnumerator<T_predict>()) for (auto e_hidden : EventEnumerator<T_hidden>()) { EventPair<T_hidden, T_predict> pair(e_hidden, e_predict); values[e_predict.encode()] += dist.probability_for(pair); } return EventDistribution<T_predict>(values); } bool can_predict(const std::vector<EventStructure> &) const override { return true; // basic VPs can always predict } BasicLinkedViewpoint *clone() const override { return new BasicLinkedViewpoint(*this); } std::string vp_name() const override { return "old-(" + T_hidden::type_name + "->" + T_predict::type_name + ")"; } BasicLinkedViewpoint(unsigned int history) : BaseVP(history) {} }; template<class EventStructure, class T_basic> class BasicViewpoint : public Viewpoint<EventStructure, T_basic, T_basic> { using VPBase = Viewpoint<EventStructure, T_basic, T_basic>; std::vector<T_basic> lift(const std::vector<EventStructure> &events) const override; public: EventDistribution<T_basic> predict(const std::vector<EventStructure> &context) const override; bool can_predict(const std::vector<EventStructure> &) const override { // basic viewpoints are essentially just wrapped-up context models, so they // can always predict return true; } VPBase *clone() const override { return new BasicViewpoint(*this); } std::string vp_name() const override { return "old-" + T_basic::type_name; } BasicViewpoint(int history) : VPBase(history) {} }; /* In basic viewpoints, we override `lift` for efficiency, since there is no * need to use the projection function and allocate a load of events on the * heap, we can just return the original sequence! */ template<class ES, class T> std::vector<T> BasicViewpoint<ES,T>::lift(const std::vector<ES> &events) const { return ES::template lift<T>(events); } template<class EventStructure, class T> EventDistribution<T> BasicViewpoint<EventStructure,T>:: predict(const std::vector<EventStructure> &context) const { return this->model.gen_successor_dist(EventStructure::template lift<T>(context)); } struct ViewpointPredictionException : public std::runtime_error { ViewpointPredictionException(std::string msg) : std::runtime_error(msg) {} }; #endif
34.963592
80
0.71378
alexcoplan
8a7fa64f68af68fa23cb3485066944c421347107
4,200
cpp
C++
src/concat_filter.cpp
shotahirama/velodyne_concat_filter
999e4c1ebeef9918a7ae2dc568eda1bee858a502
[ "Apache-2.0" ]
1
2020-01-02T10:49:58.000Z
2020-01-02T10:49:58.000Z
src/concat_filter.cpp
shotahirama/velodyne_concat_filter
999e4c1ebeef9918a7ae2dc568eda1bee858a502
[ "Apache-2.0" ]
null
null
null
src/concat_filter.cpp
shotahirama/velodyne_concat_filter
999e4c1ebeef9918a7ae2dc568eda1bee858a502
[ "Apache-2.0" ]
1
2020-01-02T10:49:31.000Z
2020-01-02T10:49:31.000Z
/* * Copyright 2019 Shota Hirama * * 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 <velodyne_concat_filter/concat_filter.h> namespace velodyne_concat_filter { ConcatFilter::ConcatFilter() : private_nh_("~"), tf_listener_(tf_buffer_), running_(false) {} ConcatFilter::ConcatFilter(ros::NodeHandle &nh, ros::NodeHandle &private_nh) : tf_listener_(tf_buffer_), running_(false) { nh_ = nh; private_nh_ = private_nh; } ConcatFilter::~ConcatFilter() { if (running_) { ROS_INFO("shutting thread"); running_ = false; topic_monitor_thread_->join(); ROS_INFO("thread shutdown"); } } void ConcatFilter::initialize() { if (!private_nh_.getParam("velodyne_topics", topics_)) { topics_ = {"/velodyne_front/velodyne_points", "/velodyne_rear/velodyne_points", "/velodyne_right/velodyne_points", "/velodyne_left/velodyne_points", "/velodyne_top/velodyne_points"}; } assert(topics_.size() > 0); if (!private_nh_.getParam("topic_monitor_rate", topic_monitor_rate_)) { topic_monitor_rate_ = 10; } query_duration_ = ros::Duration(1.0 / topic_monitor_rate_); if (!private_nh_.getParam("target_frame", target_frame_)) { target_frame_ = "base_link"; } concat_point_pub_ = nh_.advertise<sensor_msgs::PointCloud2>("concat_points", 1); pointcloud2_vec_.resize(topics_.size()); callback_stamps_.resize(topics_.size()); for (int i = 0; i < topics_.size(); i++) { pointcloud2_vec_[i].reset(new sensor_msgs::PointCloud2); subs_.emplace_back(nh_.subscribe<sensor_msgs::PointCloud2>(topics_[i], 1, boost::bind(&ConcatFilter::callback, this, _1, i))); } running_ = true; topic_monitor_thread_ = std::make_shared<std::thread>(&ConcatFilter::topic_monitor, this); topic_monitor_thread_->detach(); } void ConcatFilter::callback(const sensor_msgs::PointCloud2ConstPtr &msg, int i) { pointcloud2_vec_[i] = msg; } void ConcatFilter::topic_monitor() { ros::Rate rate(topic_monitor_rate_); while (running_) { PointCloudT::Ptr concat_cloud = boost::make_shared<PointCloudT>(); std::vector<PointCloudT::Ptr> clouds(topics_.size()); try { for (size_t i = 0; i < topics_.size(); i++) { clouds[i] = boost::make_shared<PointCloudT>(); if (!pointcloud2_vec_[i]->data.empty()) { sensor_msgs::PointCloud2 pc = *pointcloud2_vec_[i]; auto diff = ros::Duration(pc.header.stamp.toSec() - old_time_.toSec()) + query_duration_; if (diff.toNSec() > 0) { std::string source_frame = pc.header.frame_id; if (source_frame[0] == '/') { source_frame.erase(source_frame.begin()); } const geometry_msgs::TransformStamped transformStamped = tf_buffer_.lookupTransform(target_frame_, source_frame, ros::Time(0), ros::Duration(0.01)); sensor_msgs::PointCloud2 transform_cloud; pcl_ros::transformPointCloud(tf2::transformToEigen(transformStamped.transform).matrix().cast<float>(), pc, transform_cloud); pcl::fromROSMsg(transform_cloud, *clouds[i]); *concat_cloud += *clouds[i]; } else { ROS_WARN("drop points frame_id: %s", pointcloud2_vec_[i]->header.frame_id.c_str()); } } } } catch (tf2::TransformException &ex) { ROS_ERROR("%s", ex.what()); continue; } if (concat_cloud->points.size() > 0) { sensor_msgs::PointCloud2 pubmsg; pcl::toROSMsg(*concat_cloud, pubmsg); pubmsg.header.stamp = ros::Time::now(); pubmsg.header.frame_id = target_frame_; concat_point_pub_.publish(pubmsg); } old_time_ = ros::Time::now(); rate.sleep(); } } } // namespace velodyne_concat_filter
37.5
186
0.683333
shotahirama
8a820fcfc3bd86b8e71d8ad96dea49c5d181718b
1,638
hpp
C++
jitstmt/StmtMatmul.hpp
cjang/chai
7faba752cc4491d1b30590abef21edc4efffa0f6
[ "Unlicense" ]
11
2015-06-12T19:54:14.000Z
2021-11-26T10:45:18.000Z
jitstmt/StmtMatmul.hpp
cjang/chai
7faba752cc4491d1b30590abef21edc4efffa0f6
[ "Unlicense" ]
null
null
null
jitstmt/StmtMatmul.hpp
cjang/chai
7faba752cc4491d1b30590abef21edc4efffa0f6
[ "Unlicense" ]
null
null
null
// Copyright 2012 Chris Jang (fastkor@gmail.com) under The Artistic License 2.0 #ifndef _CHAI_STMT_MATMUL_HPP_ #define _CHAI_STMT_MATMUL_HPP_ #include "VisitAst.hpp" #include "StmtMatmulBase.hpp" namespace chai_internal { //////////////////////////////////////// // matrix multiplication // (all cases except outer product) class StmtMatmul : public StmtMatmulBase, public VisitAst { // RHS AstMatmulMM* _rhsMatmulMM; AstMatmulMV* _rhsMatmulMV; AstMatmulVM* _rhsMatmulVM; // recursive visiting down AST tree void descendAst(BaseAst&); public: StmtMatmul(AstVariable* lhs, AstMatmulMM* rhs); StmtMatmul(AstVariable* lhs, AstMatmulMV* rhs); StmtMatmul(AstVariable* lhs, AstMatmulVM* rhs); void accept(VisitStmt&); AstMatmulMM* matmulPtr(void) const; AstMatmulMV* matvecPtr(void) const; AstMatmulVM* vecmatPtr(void) const; void visit(AstAccum&); void visit(AstArrayMem&); void visit(AstCond&); void visit(AstConvert&); void visit(AstDotprod&); void visit(AstExtension&); void visit(AstFun1&); void visit(AstFun2&); void visit(AstFun3&); void visit(AstGather&); void visit(AstIdxdata&); void visit(AstLitdata&); void visit(AstMakedata&); void visit(AstMatmulMM&); void visit(AstMatmulMV&); void visit(AstMatmulVM&); void visit(AstMatmulVV&); void visit(AstOpenCL&); void visit(AstReadout&); void visit(AstRNGnormal&); void visit(AstRNGuniform&); void visit(AstScalar&); void visit(AstTranspose&); void visit(AstVariable&); }; }; // namespace chai_internal #endif
24.818182
79
0.675214
cjang