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
43c9455f11e2c26bdf0142d75de2de6ec763c2fd
9,613
cpp
C++
math3d/Line3D.cpp
smeng9/KrisLibrary
4bd1aa4d9a2d5e40954f5d0b8e3e8a9f19c32add
[ "BSD-3-Clause" ]
57
2015-05-07T18:07:11.000Z
2022-03-18T18:44:39.000Z
math3d/Line3D.cpp
smeng9/KrisLibrary
4bd1aa4d9a2d5e40954f5d0b8e3e8a9f19c32add
[ "BSD-3-Clause" ]
7
2018-12-10T21:46:52.000Z
2022-01-20T19:49:11.000Z
math3d/Line3D.cpp
smeng9/KrisLibrary
4bd1aa4d9a2d5e40954f5d0b8e3e8a9f19c32add
[ "BSD-3-Clause" ]
36
2015-01-10T18:36:45.000Z
2022-01-20T19:49:24.000Z
#include <KrisLibrary/Logger.h> #include "Line3D.h" #include "Segment3D.h" #include "clip.h" #include "misc.h" #include "errors.h" #include <iostream> using namespace Math3D; using namespace std; bool Line3D::Read(File& f) { if(!source.Read(f)) return false; if(!direction.Read(f)) return false; return true; } bool Line3D::Write(File& f) const { if(!source.Write(f)) return false; if(!direction.Write(f)) return false; return true; } void Line3D::setPoints(const Point3D& a, const Point3D& b) { source = a; direction.sub(b,a); } void Line3D::setSegment(const Segment3D& s) { source = s.a; direction.sub(s.b,s.a); } void Line3D::setTransformed(const Line3D& l, const Matrix4& xform) { xform.mulPoint(l.source,source); xform.mulVector(l.direction,direction); } void Line3D::eval(Real t, Point3D& out) const { out = source; out.madd(direction,t); } Real Line3D::closestPointParameter(const Point3D& in) const { Real denom = dot(direction,direction); if(denom == Zero) return Zero; return dot(in-source,direction)/denom; } Real Line3D::closestPoint(const Point3D& in, Point3D& out) const { Real t=closestPointParameter(in); eval(t,out); return t; } Real Line3D::closestPoint(const Point3D& in, Point3D& out, Real tmin, Real tmax) const { Real denom = dot(direction,direction); Real numer = dot(in-source,direction); //t = numer/denom with denom >= 0 Real t; if(numer<=tmin*denom) t=tmin; else if(numer>=tmax*denom) t=tmax; else t = numer/denom; eval(t,out); return t; } Real Line3D::distance(const Point3D& pt) const { Point3D closest; closestPoint(pt,closest); return (pt-closest).norm(); } //a generalized line test for rays a + t*as, b + u*bs bool Line3D::intersects(const Line3D& l, Real* t, Real* u, Real epsilon) const { //take the vector normal to both lines, project their offsets onto the lines //if they are coplanar, do some more checking Vector3 n = cross(direction,l.direction); Vector3 local = l.source - source; if(n.isZero()) //a,b parallel { //project l onto this line (in local coords) Real projDist = dot(local,direction)/dot(direction,direction); if (DistanceLEQ(local,projDist*direction,epsilon)) { if(t) *t=projDist; if(u) *u=0; return true; } return false; } if(Abs(dot(n, local))<=epsilon) { //get the coordinates of "shift" on the plane //an orthogonal basis is B={a.slope, n*a.slope} //get bslope' and boffset' in B coordinates //bslope' = B = (b1,b2) = (dot(bslope,aslope)/dot(aslope,aslope), dot(bslope,na)/dot(na,na)) //boffset' = A = (a1,a2) = (dot(bofs,aslope)/dot(aslope,aslope), dot(bofs,na)/dot(na,na)) //get an equation R = A + Bt //get the t value of the intersection point with the x axis (x,0), 0 = a2 + b2*t, t = -a2/b2 = dot(bofs,na)/dot(bslope,na) Vector3 na = cross(n,direction); Real myt = -dot(local,na)/dot(l.direction,na); if(t) { *t = myt; } if(u) { Real al2=Inv(dot(direction,direction)); Real a1,b1; a1 = dot(local,direction)*al2; b1 = dot(l.direction,direction)*al2; *u = a1 + b1*myt; } return true; } return false; } void Line3D::closestPoint(const Line3D& l, Real& t, Real& u) const { //take the vector normal to both lines, project their offsets onto the lines //if they are coplanar, do some more checking Vector3 n = cross(direction,l.direction); Vector3 local = l.source - source; if(n.isZero()) { //a,b parallel //project l onto this line (in local coords) t = dot(local,direction)/dot(direction,direction); u = 0; return; } //get the coordinates of "shift" on the plane //an orthogonal basis is B={a.slope, n*a.slope} //get bslope' and boffset' in B coordinates //bslope' = B = (b1,b2) = (dot(bslope,aslope)/dot(aslope,aslope), dot(bslope,na)/dot(na,na)) //boffset' = A = (a1,a2) = (dot(bofs,aslope)/dot(aslope,aslope), dot(bofs,na)/dot(na,na)) //get an equation R = A + Bt //get the t value of the intersection point with the x axis (x,0), 0 = a2 + b2*t, t = -a2/b2 = dot(bofs,na)/dot(bslope,na) //THIS IS MESSED UP /* Vector3 na = cross(n,direction); t = -dot(local,na)/dot(l.direction,na); Real al2=Inv(dot(direction,direction)); Real a1,b1; a1 = dot(local,direction)*al2; b1 = dot(l.direction,direction)*al2; u = a1 + b1*t; */ Matrix2 AtA,AtAinv; AtA(0,0) = dot(direction,direction); AtA(1,0) = -dot(l.direction,direction); AtA(0,1) = -dot(l.direction,direction); AtA(1,1) = dot(l.direction,l.direction); bool res=AtA.getInverse(AtAinv); if(!res) { LOG4CXX_ERROR(KrisLibrary::logger(),"Warning, Line3D closest points matrix inverse failed\n"); t=u=0; return; } Vector2 tu = AtAinv*Vector2(dot(direction,local),-dot(l.direction,local)); t = tu.x; u = tu.y; } void Line3D::getAABB(AABB3D& bb,Real tmin,Real tmax) const { Point3D a,b; eval(tmin,a); eval(tmax,b); bb.setPoint(a); bb.expand(b); } bool Line3D::lineIntersects(const AABB3D& bb) const { Real u1=-Inf,u2=Inf; return intersects(bb,u1,u2); } bool Line3D::rayIntersects(const AABB3D& bb) const { Real u1=0,u2=Inf; return intersects(bb,u1,u2); } bool Line3D::intersects(const AABB3D& bb, Real& u1, Real& u2) const { return ClipLine(source, direction, bb, u1,u2); } Real Line3D::distance(const AABB3D& bb) const { Real tclosest; Vector3 bbclosest; return distance(bb,tclosest,bbclosest); } Real Line3D::distance(const AABB3D& bb, Real& tclosest, Vector3& bbclosest) const { Real tmin=-Inf,tmax=Inf; if(intersects(bb,tmin,tmax)) { tclosest = tmin; eval(tmin,bbclosest); return 0; } //recompute matrices to get distances between axis-aligned segments to this Matrix2 AtA,Ax,Ay,Az; AtA(0,0) = dot(direction,direction); AtA(0,1) = AtA(1,0) = -direction.x; AtA(1,1) = 1; bool res=AtA.getInverse(Ax); if(!res) Ax.setZero(); AtA(0,1) = AtA(1,0) = -direction.y; res=AtA.getInverse(Ay); if(!res) Ay.setZero(); AtA(0,1) = AtA(1,0) = -direction.z; res=AtA.getInverse(Az); if(!res) Az.setZero(); Vector3 bmin = bb.bmin - source, bmax = bb.bmax - source; //for an x-aligned segment, (t,u)^T = Ax*(direction^T x,-bmin.x)^T gives the //parameter on this segment t and the x value of the point bmin.x+u Real dxmin=direction.x*bmin.x,dxmax=direction.x*bmax.x; Real dymin=direction.y*bmin.y,dymax=direction.y*bmax.y; Real dzmin=direction.z*bmin.z,dzmax=direction.z*bmax.z; Real dps [8] = {dzmin+dymin+dxmin, dzmin+dymin+dxmax, dzmin+dymax+dxmin, dzmin+dymax+dxmax, dzmax+dymin+dxmin, dzmax+dymin+dxmax, dzmax+dymax+dxmin, dzmax+dymax+dxmax}; Real bxt = -Ax(0,1)*bmin.x; Real bxu = -Ax(1,1)*bmin.x; Real byt = -Ay(0,1)*bmin.y; Real byu = -Ay(1,1)*bmin.y; Real bzt = -Az(0,1)*bmin.z; Real bzu = -Az(1,1)*bmin.z; Real tx[4] ={ Ax(0,0)*dps[0]+bxt, Ax(0,0)*dps[2]+bxt, Ax(0,0)*dps[4]+bxt, Ax(0,0)*dps[6]+bxt}; Real ux[4] ={ Ax(1,0)*dps[0]+bxu, Ax(1,0)*dps[2]+bxu, Ax(1,0)*dps[4]+bxu, Ax(1,0)*dps[6]+bxu}; Real ty[4] ={ Ay(0,0)*dps[0]+byt, Ay(0,0)*dps[1]+byt, Ay(0,0)*dps[4]+byt, Ay(0,0)*dps[5]+byt}; Real uy[4] ={ Ay(1,0)*dps[0]+byu, Ay(1,0)*dps[1]+byu, Ay(1,0)*dps[4]+byu, Ay(1,0)*dps[5]+byu}; Real tz[4] ={ Az(0,0)*dps[0]+bzt, Az(0,0)*dps[1]+bzt, Az(0,0)*dps[2]+bzt, Az(0,0)*dps[3]+bzt}; Real uz[4] ={ Az(1,0)*dps[0]+bzu, Az(1,0)*dps[1]+bzu, Az(1,0)*dps[2]+bzu, Az(1,0)*dps[3]+bzu}; bool testcorners [8] = {0,0,0,0,0,0,0,0}; Vector3 bbtemp,ltemp; Real dmin = Inf; //check the x's for(int i=0;i<4;i++) { if(ux[i] < 0) testcorners[i] = true; else if(ux[i] > (bmax.x-bmin.x)) testcorners[i+1] = true; else { Vector3 diff = (-tx[i])*direction; diff.x += ux[i] + bmin.x; diff.y += (i&1? bmax.y : bmin.y); diff.z += (i&2? bmax.z : bmin.z); Real d2 = diff.normSquared(); if(d2 < dmin) { tclosest = tx[i]; eval(tclosest,ltemp); dmin = bb.distanceSquared(ltemp,bbclosest); } } } //check the y's for(int i=0;i<4;i++) { if(uy[i] < 0) testcorners[i] = true; else if(uy[i] > (bmax.y-bmin.y)) testcorners[i+2] = true; else { Vector3 diff = (-ty[i])*direction; diff.y += uy[i] + bmin.y; diff.x += (i&1? bmax.x : bmin.x); diff.z += (i&2? bmax.z : bmin.z); Real d2 = diff.normSquared(); if(d2 < dmin) { tclosest = ty[i]; eval(tclosest,ltemp); dmin = bb.distanceSquared(ltemp,bbclosest); } } } //check the z's for(int i=0;i<4;i++) { if(uz[i] < 0) testcorners[i] = true; else if(uz[i] > (bmax.z-bmin.z)) testcorners[i+4] = true; else { Vector3 diff = (-tz[i])*direction; diff.z += uz[i] + bmin.z; diff.x += (i&1 ? bmax.x : bmin.x); diff.y += (i&2 ? bmax.y : bmin.y); Real d2 = diff.normSquared(); if(d2 < dmin) { tclosest = tz[i]; eval(tclosest,ltemp); dmin = bb.distanceSquared(ltemp,bbclosest); } } } //check the corners for(int i=0;i<8;i++) { if(testcorners[i]) { Vector3 pt; pt.x = (i & 1 ? bb.bmax.x : bb.bmin.x); pt.y = (i & 2 ? bb.bmax.y : bb.bmin.y); pt.z = (i & 4 ? bb.bmax.z : bb.bmin.z); Real ttemp = closestPoint(pt,ltemp); Real d2 = pt.distanceSquared(ltemp); if(d2 < dmin) { dmin = d2; tclosest = ttemp; bbclosest = pt; } } } return Sqrt(dmin); } namespace Math3D { ostream& operator << (ostream& out,const Line3D& line) { out<<line.source<<" "<<line.direction; return out; } istream& operator >> (istream& in,Line3D& line) { in>>line.source>>line.direction; return in; } }
25.911051
124
0.62145
smeng9
43c9832fa4279dca6320e6cb26f3e698239fb70d
1,996
cc
C++
pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcraster_model_engine/calc_MemoryExchangeItemString.cc
quanpands/wflow
b454a55e4a63556eaac3fbabd97f8a0b80901e5a
[ "MIT" ]
null
null
null
pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcraster_model_engine/calc_MemoryExchangeItemString.cc
quanpands/wflow
b454a55e4a63556eaac3fbabd97f8a0b80901e5a
[ "MIT" ]
null
null
null
pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcraster_model_engine/calc_MemoryExchangeItemString.cc
quanpands/wflow
b454a55e4a63556eaac3fbabd97f8a0b80901e5a
[ "MIT" ]
null
null
null
#ifndef INCLUDED_STDDEFX #include "stddefx.h" #define INCLUDED_STDDEFX #endif #ifndef INCLUDED_CALC_MEMORYEXCHANGEITEMSTRING #include "calc_MemoryExchangeItemString.h" #define INCLUDED_CALC_MEMORYEXCHANGEITEMSTRING #endif // External headers. #ifndef INCLUDED_CSTRING #include <cstring> #define INCLUDED_CSTRING #endif // Project headers. // Module headers. /*! \file This file contains the implementation of the MemoryExchangeItemString class. */ namespace calc { // Code that is private to this module. namespace detail { } // namespace detail //------------------------------------------------------------------------------ // DEFINITION OF STATIC MEMORYEXCHANGEITEMSTRING MEMBERS //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // DEFINITION OF MEMORYEXCHANGEITEMSTRING MEMBERS //------------------------------------------------------------------------------ MemoryExchangeItemString::MemoryExchangeItemString() { } MemoryExchangeItemString::MemoryExchangeItemString( std::string const& name, size_t memoryId, std::string const& value): MemoryExchangeItem(name,memoryId), d_value(value) { } MemoryExchangeItemString::~MemoryExchangeItemString() { } void* MemoryExchangeItemString::rawValue() const { return (void *)d_value.c_str(); } //! copy c_str() representation of value into dest. void MemoryExchangeItemString::beMemCpySrc(void *dest) const { const char *src = d_value.c_str(); std::strcpy((char *)dest, src); } //------------------------------------------------------------------------------ // DEFINITION OF FREE OPERATORS //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // DEFINITION OF FREE FUNCTIONS //------------------------------------------------------------------------------ } // namespace calc
21.934066
80
0.516533
quanpands
43cb34aed7b12129866c93ee433fbf8af463367c
731
cpp
C++
alg_two.cpp
Francenzo/face_auth
fa25ce3d5ea6ce35005f8facf1e5b578fadf11fc
[ "MIT" ]
null
null
null
alg_two.cpp
Francenzo/face_auth
fa25ce3d5ea6ce35005f8facf1e5b578fadf11fc
[ "MIT" ]
null
null
null
alg_two.cpp
Francenzo/face_auth
fa25ce3d5ea6ce35005f8facf1e5b578fadf11fc
[ "MIT" ]
2
2018-04-12T01:17:15.000Z
2018-04-14T01:27:27.000Z
/* * * Second Algorithm to test image * against known dataset * */ #include "alg_two.hpp" Algorithm_Two::Algorithm_Two(vector<Mat> users, vector<int> labels) { model = createFisherFaceRecognizer(); model->train(users, labels); } int Algorithm_Two::compare(Mat face) { int predictedLabel = -1; double confidence = 0.0; model->predict(face, predictedLabel, confidence); // string result_message = format("Predicted class = %d | confidence = %f", predictedLabel, confidence); // cout << result_message << endl; if (confidence < ACCEPTANCE_THRESHOLD) { // cout << "accepted" << endl; return predictedLabel; } else { return -1; } }
20.885714
110
0.618331
Francenzo
43d01fdfd98517507c45093712bf95151fd533da
723
cpp
C++
external_codes/mpi_wrapper/mpi3/test/type_commit.cpp
djstaros/qmcpack
280f67e638bae280448b47fa618f05b848c530d2
[ "NCSA" ]
null
null
null
external_codes/mpi_wrapper/mpi3/test/type_commit.cpp
djstaros/qmcpack
280f67e638bae280448b47fa618f05b848c530d2
[ "NCSA" ]
11
2020-05-09T20:57:21.000Z
2020-06-10T00:00:17.000Z
external_codes/mpi_wrapper/mpi3/test/type_commit.cpp
djstaros/qmcpack
280f67e638bae280448b47fa618f05b848c530d2
[ "NCSA" ]
null
null
null
#if COMPILATION_INSTRUCTIONS mpicxx -O3 -std=c++14 -Wall -Wfatal-errors $0 -o $0x.x && time mpirun -np 4s $0x.x $@ && rm -f $0x.x; exit #endif #define BOOST_MPI3_DISALLOW_AUTOMATIC_POD_COMMUNICATION #include "alf/boost/mpi3/main.hpp" #include "alf/boost/mpi3/communicator.hpp" namespace mpi3 = boost::mpi3; using std::cout; int mpi3::main(int argc, char* argv[], mpi3::communicator& world){ mpi3::type t = mpi3::type::int_[100]; // mpi3::type::int_.contiguous(100); t.commit_as<std::array<int, 100>>(); t.commit_as<int[100]>(); // std::array<int, 100> buffer; int buffer[100]; if(world.rank() == 0) world.send_n(&buffer, 1, 1, 123); else if(world.rank() == 1) world.receive_n(&buffer, 1, 0, 123); return 0; }
27.807692
106
0.677732
djstaros
43d2167bc0f921d659a6171bad2ac8567736b563
6,801
hpp
C++
packages/monte_carlo/collision/neutron/src/MonteCarlo_DecoupledPhotonProductionReactionACEFactory.hpp
bam241/FRENSIE
e1760cd792928699c84f2bdce70ff54228e88094
[ "BSD-3-Clause" ]
10
2019-11-14T19:58:30.000Z
2021-04-04T17:44:09.000Z
packages/monte_carlo/collision/neutron/src/MonteCarlo_DecoupledPhotonProductionReactionACEFactory.hpp
bam241/FRENSIE
e1760cd792928699c84f2bdce70ff54228e88094
[ "BSD-3-Clause" ]
43
2020-03-03T19:59:20.000Z
2021-09-08T03:36:08.000Z
packages/monte_carlo/collision/neutron/src/MonteCarlo_DecoupledPhotonProductionReactionACEFactory.hpp
bam241/FRENSIE
e1760cd792928699c84f2bdce70ff54228e88094
[ "BSD-3-Clause" ]
6
2020-02-12T17:37:07.000Z
2020-09-08T18:59:51.000Z
//---------------------------------------------------------------------------// //! //! \file MonteCarlo_DecoupledPhotonProductionReactionACEFactory.hpp //! \author Eli Moll //! \brief Decoupled photon production reaction factory class declaration //! //---------------------------------------------------------------------------// #ifndef MONTE_CARLO_DECOUPLED_PHOTON_PRODUCTION_REACTION_ACE_FACTORY_HPP #define MONTE_CARLO_DECOUPLED_PHOTON_PRODUCTION_REACTION_ACE_FACTORY_HPP // Standard Includes #include <memory> #include <unordered_map> #include <unordered_set> // FRENSIE Includes #include "MonteCarlo_DecoupledPhotonProductionReaction.hpp" #include "MonteCarlo_PhotonProductionNuclearScatteringDistributionACEFactory.hpp" #include "MonteCarlo_NeutronNuclearReactionACEFactory.hpp" #include "MonteCarlo_NuclearReactionType.hpp" #include "Utility_UnivariateDistribution.hpp" #include "Utility_HashBasedGridSearcher.hpp" #include "Utility_ArrayView.hpp" #include "Utility_Vector.hpp" namespace MonteCarlo{ /*! The decoupled photon production reaction factory class * \details This factory class stores all of the data blocks found in the * ACE tables that describe specific reactions (except for fission reactions). * The array parameters used in the class constructor have the same name as * the corresponding ACE data block. */ class DecoupledPhotonProductionReactionACEFactory : public NeutronNuclearReactionACEFactory { public: //! Constructor DecoupledPhotonProductionReactionACEFactory( const std::string& table_name, const double atomic_weight_ratio, const double temperature, const std::shared_ptr<const std::vector<double> >& energy_grid, const std::shared_ptr<const Utility::HashBasedGridSearcher<double> >& grid_searcher, const SimulationProperties& properties, const Data::XSSNeutronDataExtractor& raw_nuclide_data ); //! Destructor ~DecoupledPhotonProductionReactionACEFactory() { /* ... */ } //! Create the yield based photon production reactions void createPhotonProductionReactions( std::unordered_map<unsigned,std::shared_ptr<const DecoupledPhotonProductionReaction> >& yield_based_photon_production_reactions ) const; protected: //! Create the reaction type ordering map static void createReactionOrderingMap( const Utility::ArrayView<const double>& mtrp_block, std::unordered_map<unsigned,unsigned>& reaction_ordering ); //! Create the total reaction void createTotalReaction( const Utility::ArrayView<const double>& total_xs_block, const std::shared_ptr<const std::vector<double> >& energy_grid, const std::shared_ptr<const Utility::HashBasedGridSearcher<double> >& grid_searcher, const double temperature ); //! Parse the SIGP Block static void parseSIGP( const std::string& table_name, const size_t energy_grid_size, const Utility::ArrayView<const double>& lsigp_block, const Utility::ArrayView<const double>& sigp_block, const std::unordered_map<unsigned,unsigned>& reaction_ordering, std::unordered_map<unsigned,Utility::ArrayView<const double> >& yield_energy_map, std::unordered_map<unsigned,Utility::ArrayView<const double> >& yield_values_map, std::unordered_map<unsigned,std::shared_ptr<std::vector<double> > >& xs_based_map, std::unordered_map<unsigned,unsigned>& threshold_energy_map, std::unordered_map<unsigned,NuclearReactionType>& base_reaction_type_map ); //! Construct the base reaction map void constructBaseReactionMap( std::unordered_map<unsigned,NuclearReactionType>& base_reaction_type_map, std::unordered_map<NuclearReactionType,std::shared_ptr<const NeutronNuclearReaction> >& base_reaction_map, std::unordered_map<unsigned,Utility::ArrayView<const double> >& yield_energy_map ); // Construct a map of photon MT numbers to yield distributions void constructMTPYieldDistributions( const std::unordered_map<unsigned,Utility::ArrayView<const double> >& yield_energy_map, const std::unordered_map<unsigned,Utility::ArrayView<const double> >& yield_values_map ); // Construct a map of base reaction types to yield distribution arrays void constructMTYieldArrays( const std::unordered_map<unsigned,NuclearReactionType>& base_reaction_type_map, const std::unordered_map<unsigned,Utility::ArrayView<const double> >& yield_energy_map ); private: // Initialize the yield based photon production reactions void initializeYieldBasedPhotonProductionReactions( const std::unordered_map<unsigned,NuclearReactionType>& base_reaction_type_map, const double temperature, const std::unordered_map<unsigned,Utility::ArrayView<const double> >& yield_energy_map, const std::unordered_map<NuclearReactionType,std::shared_ptr<const NeutronNuclearReaction> >& base_reaction_map, const SimulationProperties& properties, PhotonProductionNuclearScatteringDistributionACEFactory& photon_production_dist_factory ); // Initialize the yield based photon production reactions void initializeCrossSectionBasedPhotonProductionReactions( const std::unordered_map<unsigned,NuclearReactionType>& base_reaction_type_map, const double temperature, const std::unordered_map<unsigned,unsigned>& threshold_energy_map, const std::unordered_map<unsigned,std::shared_ptr<std::vector<double> > >& xs_based_map, const std::shared_ptr<const std::vector<double> >& energy_grid, const std::shared_ptr<const Utility::HashBasedGridSearcher<double> >& grid_searcher, const SimulationProperties& properties, PhotonProductionNuclearScatteringDistributionACEFactory& photon_production_dist_factory ); // A map of the photon production reactions std::unordered_map<unsigned,std::shared_ptr<const DecoupledPhotonProductionReaction> > d_photon_production_reactions; // A map of the nuclear reaction type to associated array of TabularDistributions std::unordered_map<NuclearReactionType,std::vector<std::shared_ptr<const Utility::UnivariateDistribution> > > d_mt_yield_distributions; // A map of photon production reaction MT numbers to shared pointers of // Tabular distributions std::unordered_map<unsigned,std::shared_ptr<const Utility::UnivariateDistribution> > d_mtp_yield_distributions_map; // Total reaction std::shared_ptr<const NeutronNuclearReaction> d_total_reaction; }; } // end MonteCarlo namespace #endif // end MONTE_CARLONUCLEAR_REACTION_ACE_FACTORY_HPP //---------------------------------------------------------------------------// // end MonteCarlo_NeutronNuclearReactionACEFactory.hpp //---------------------------------------------------------------------------//
45.039735
119
0.745185
bam241
43d581eedb237f13a56a3f01cdf5ade8d4fa393a
440
cpp
C++
src/GraphicsLib/Graphics/GPUResource/ShaderResource/TextureSampler/Components/TextureSamplerDescriptor.cpp
Sushiwave/graphics-lib
c303e9fb9f11276230a09b45581cdbefa8d2a356
[ "MIT" ]
1
2020-07-13T18:10:33.000Z
2020-07-13T18:10:33.000Z
src/GraphicsLib/Graphics/GPUResource/ShaderResource/TextureSampler/Components/TextureSamplerDescriptor.cpp
Sushiwave/graphics-lib
c303e9fb9f11276230a09b45581cdbefa8d2a356
[ "MIT" ]
null
null
null
src/GraphicsLib/Graphics/GPUResource/ShaderResource/TextureSampler/Components/TextureSamplerDescriptor.cpp
Sushiwave/graphics-lib
c303e9fb9f11276230a09b45581cdbefa8d2a356
[ "MIT" ]
null
null
null
#include <GraphicsLib/Graphics/GPUResource/ShaderResource/TextureSampler/Components/TextureSamplerDescriptor.hpp> namespace cg { TextureSamplerDescriptor::TextureSamplerDescriptor() noexcept { filter = TextureFilter::point; addressU = TextureAddressMode::clamp; addressV = TextureAddressMode::clamp; addressW = TextureAddressMode::clamp; maxAnisotropy = 0; borderColor = cpp::Vector4D<float>(0.0f, 0.0f, 0.0f, 0.0f); } }
24.444444
113
0.770455
Sushiwave
43db75cb28f0a9bddbdcb24e46d3c6745e9c8ef6
2,907
cpp
C++
src/player/player_lib/Common/RegionData.cpp
inteltiger/Immersive-Video-Sample
e61a0f93a6b82315b4eccdcfa7b78ce1fb0de92f
[ "BSD-3-Clause" ]
null
null
null
src/player/player_lib/Common/RegionData.cpp
inteltiger/Immersive-Video-Sample
e61a0f93a6b82315b4eccdcfa7b78ce1fb0de92f
[ "BSD-3-Clause" ]
null
null
null
src/player/player_lib/Common/RegionData.cpp
inteltiger/Immersive-Video-Sample
e61a0f93a6b82315b4eccdcfa7b78ce1fb0de92f
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2019, Intel Corporation * 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ //! //! \file: RegionData.cpp //! \brief: the class for Region Info //! \detail: it's class to describe region info //! //! Created on May 21, 2020, 1:18 PM //! #include "RegionData.h" #include <string.h> #include "Common.h" VCD_NS_BEGIN RegionData::RegionData(RegionWisePacking* rwpk, uint32_t sourceNumber, SourceResolution* qtyRes) { m_sourceInRegion = sourceNumber; m_regionWisePacking = new RegionWisePacking; *m_regionWisePacking = *rwpk; m_regionWisePacking->rectRegionPacking = new RectangularRegionWisePacking[rwpk->numRegions]; memcpy_s(m_regionWisePacking->rectRegionPacking, rwpk->numRegions * sizeof(RectangularRegionWisePacking), rwpk->rectRegionPacking, rwpk->numRegions * sizeof(RectangularRegionWisePacking)); m_sourceInfo = new SourceResolution[sourceNumber]; for (uint32_t i = 0; i < sourceNumber; i++) { m_sourceInfo[i].qualityRanking = qtyRes[i].qualityRanking; m_sourceInfo[i].left = qtyRes[i].left; m_sourceInfo[i].top = qtyRes[i].top; m_sourceInfo[i].width = qtyRes[i].width; m_sourceInfo[i].height = qtyRes[i].height; } } RegionData::~RegionData() { m_sourceInRegion = 0; if (m_regionWisePacking != NULL) { if (m_regionWisePacking->rectRegionPacking != NULL) { delete[] m_regionWisePacking->rectRegionPacking; m_regionWisePacking->rectRegionPacking = NULL; } delete m_regionWisePacking; m_regionWisePacking = NULL; } if (m_sourceInfo != NULL) { delete[] m_sourceInfo; m_sourceInfo = NULL; } } VCD_NS_END
36.797468
107
0.743034
inteltiger
43dc5f3f1f4fdac3d376ff7218facb2d849b9c5b
23,958
cpp
C++
src/genavr/algorithm_wage.cpp
sebastien-riou/lightweight-crypto
fed4ddf1523f35734413f115ec3f8d13a1a15d29
[ "MIT" ]
48
2020-03-04T19:00:01.000Z
2021-11-14T20:01:48.000Z
src/genavr/algorithm_wage.cpp
sebastien-riou/lightweight-crypto
fed4ddf1523f35734413f115ec3f8d13a1a15d29
[ "MIT" ]
null
null
null
src/genavr/algorithm_wage.cpp
sebastien-riou/lightweight-crypto
fed4ddf1523f35734413f115ec3f8d13a1a15d29
[ "MIT" ]
8
2020-05-23T09:25:07.000Z
2021-12-19T19:21:15.000Z
/* * Copyright (C) 2020 Southern Storm Software, Pty Ltd. * * 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 "gen.h" #include <cstring> // Size of the WAGE state in bytes. #define WAGE_STATE_SIZE 37 // Number of rounds for the WAGE permutation. #define WAGE_NUM_ROUNDS 111 // Table numbers. #define WAGE_TABLE_WGP_SBOX 0 #define WAGE_TABLE_RC 1 // RC0 and RC1 round constants for WAGE, interleaved with each other. static unsigned char const wage_rc[WAGE_NUM_ROUNDS * 2] = { 0x7f, 0x3f, 0x1f, 0x0f, 0x07, 0x03, 0x01, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x41, 0x60, 0x30, 0x18, 0x0c, 0x06, 0x43, 0x21, 0x50, 0x28, 0x14, 0x0a, 0x45, 0x62, 0x71, 0x78, 0x3c, 0x1e, 0x4f, 0x27, 0x13, 0x09, 0x44, 0x22, 0x51, 0x68, 0x34, 0x1a, 0x4d, 0x66, 0x73, 0x39, 0x5c, 0x2e, 0x57, 0x2b, 0x15, 0x4a, 0x65, 0x72, 0x79, 0x7c, 0x3e, 0x5f, 0x2f, 0x17, 0x0b, 0x05, 0x42, 0x61, 0x70, 0x38, 0x1c, 0x0e, 0x47, 0x23, 0x11, 0x48, 0x24, 0x12, 0x49, 0x64, 0x32, 0x59, 0x6c, 0x36, 0x5b, 0x2d, 0x56, 0x6b, 0x35, 0x5a, 0x6d, 0x76, 0x7b, 0x3d, 0x5e, 0x6f, 0x37, 0x1b, 0x0d, 0x46, 0x63, 0x31, 0x58, 0x2c, 0x16, 0x4b, 0x25, 0x52, 0x69, 0x74, 0x3a, 0x5d, 0x6e, 0x77, 0x3b, 0x1d, 0x4e, 0x67, 0x33, 0x19, 0x4c, 0x26, 0x53, 0x29, 0x54, 0x2a, 0x55, 0x6a, 0x75, 0x7a, 0x7d, 0x7e, 0x7f, 0x3f, 0x1f, 0x0f, 0x07, 0x03, 0x01, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x41, 0x60, 0x30, 0x18, 0x0c, 0x06, 0x43, 0x21, 0x50, 0x28, 0x14, 0x0a, 0x45, 0x62, 0x71, 0x78, 0x3c, 0x1e, 0x4f, 0x27, 0x13, 0x09, 0x44, 0x22, 0x51, 0x68, 0x34, 0x1a, 0x4d, 0x66, 0x73, 0x39, 0x5c, 0x2e, 0x57, 0x2b, 0x15, 0x4a, 0x65, 0x72, 0x79, 0x7c, 0x3e, 0x5f, 0x2f, 0x17, 0x0b, 0x05, 0x42, 0x61, 0x70, 0x38, 0x1c, 0x0e, 0x47, 0x23, 0x11, 0x48, 0x24, 0x12, 0x49, 0x64, 0x32, 0x59, 0x6c, 0x36, 0x5b, 0x2d, 0x56, 0x6b, 0x35, 0x5a, 0x6d, 0x76, 0x7b, 0x3d, 0x5e, 0x6f, 0x37, 0x1b, 0x0d, 0x46 }; // WGP and S-box combined into a single 256 byte table. static unsigned char const wage_wgp_sbox[256] = { // S-box 0x2e, 0x1c, 0x6d, 0x2b, 0x35, 0x07, 0x7f, 0x3b, 0x28, 0x08, 0x0b, 0x5f, 0x31, 0x11, 0x1b, 0x4d, 0x6e, 0x54, 0x0d, 0x09, 0x1f, 0x45, 0x75, 0x53, 0x6a, 0x5d, 0x61, 0x00, 0x04, 0x78, 0x06, 0x1e, 0x37, 0x6f, 0x2f, 0x49, 0x64, 0x34, 0x7d, 0x19, 0x39, 0x33, 0x43, 0x57, 0x60, 0x62, 0x13, 0x05, 0x77, 0x47, 0x4f, 0x4b, 0x1d, 0x2d, 0x24, 0x48, 0x74, 0x58, 0x25, 0x5e, 0x5a, 0x76, 0x41, 0x42, 0x27, 0x3e, 0x6c, 0x01, 0x2c, 0x3c, 0x4e, 0x1a, 0x21, 0x2a, 0x0a, 0x55, 0x3a, 0x38, 0x18, 0x7e, 0x0c, 0x63, 0x67, 0x56, 0x50, 0x7c, 0x32, 0x7a, 0x68, 0x02, 0x6b, 0x17, 0x7b, 0x59, 0x71, 0x0f, 0x30, 0x10, 0x22, 0x3d, 0x40, 0x69, 0x52, 0x14, 0x36, 0x44, 0x46, 0x03, 0x16, 0x65, 0x66, 0x72, 0x12, 0x0e, 0x29, 0x4a, 0x4c, 0x70, 0x15, 0x26, 0x79, 0x51, 0x23, 0x3f, 0x73, 0x5b, 0x20, 0x5c, // WGP 0x00, 0x12, 0x0a, 0x4b, 0x66, 0x0c, 0x48, 0x73, 0x79, 0x3e, 0x61, 0x51, 0x01, 0x15, 0x17, 0x0e, 0x7e, 0x33, 0x68, 0x36, 0x42, 0x35, 0x37, 0x5e, 0x53, 0x4c, 0x3f, 0x54, 0x58, 0x6e, 0x56, 0x2a, 0x1d, 0x25, 0x6d, 0x65, 0x5b, 0x71, 0x2f, 0x20, 0x06, 0x18, 0x29, 0x3a, 0x0d, 0x7a, 0x6c, 0x1b, 0x19, 0x43, 0x70, 0x41, 0x49, 0x22, 0x77, 0x60, 0x4f, 0x45, 0x55, 0x02, 0x63, 0x47, 0x75, 0x2d, 0x40, 0x46, 0x7d, 0x5c, 0x7c, 0x59, 0x26, 0x0b, 0x09, 0x03, 0x57, 0x5d, 0x27, 0x78, 0x30, 0x2e, 0x44, 0x52, 0x3b, 0x08, 0x67, 0x2c, 0x05, 0x6b, 0x2b, 0x1a, 0x21, 0x38, 0x07, 0x0f, 0x4a, 0x11, 0x50, 0x6a, 0x28, 0x31, 0x10, 0x4d, 0x5f, 0x72, 0x39, 0x16, 0x5a, 0x13, 0x04, 0x3c, 0x34, 0x1f, 0x76, 0x1e, 0x14, 0x23, 0x1c, 0x32, 0x4e, 0x7b, 0x24, 0x74, 0x7f, 0x3d, 0x69, 0x64, 0x62, 0x6f }; Sbox get_wage_round_constants(int num) { if (num == WAGE_TABLE_RC) return Sbox(wage_rc, sizeof(wage_rc)); else return Sbox(wage_wgp_sbox, sizeof(wage_wgp_sbox)); } struct WageState { Code *code; Reg s[WAGE_STATE_SIZE]; Reg fb[3]; Reg temp; unsigned char modified[WAGE_STATE_SIZE]; int last_used[WAGE_STATE_SIZE]; int time; WageState(Code &c) : code(&c), time(1) { memset(modified, 0, sizeof(modified)); memset(last_used, 0, sizeof(last_used)); temp = code->allocateHighReg(1); } // Load a byte from the state into a register if not already in one. // Return the existing register if the value is still in a register. // If we have run out of registers, spill the oldest one. Reg reg(int num); // Mark a byte as having been used to keep the register fresh. // This will avoid a spill on a value we know we'll need again // soon in the upcoming code. void used(int num); // Mark a byte as dirty. Register contents have been modified. void dirty(int num); // Spill a register back to the stack if the value has been modified. // Then release the register back to the allocation pool. void spill(int num); // Spill the oldest unmodified value that is in a high register. void spillHigh(); // Spill the oldest unmodified value that is in any register. void spillAny(); // Determine if a state byte is active in a register or if it is // still on the stack. bool isActive(int num); // Copy a value into the stack and release the original register. void copy(int to, int from); }; Reg WageState::reg(int num) { if (s[num].size() != 0) { last_used[num] = time++; return s[num]; } s[num] = code->allocateOptionalReg(1); if (s[num].size() == 0) { // We have run out of registers so find the oldest value // that is not modified and reuse that register. We should // be able to find something. int age = 0x7FFFFFFF; int oldest = -1; for (int index = 0; index < WAGE_STATE_SIZE; ++index) { if (s[index].size() != 0 && !modified[index]) { if (last_used[index] < age) { age = last_used[index]; oldest = index; } } } if (oldest == -1) { // Try again but this time find the oldest modified register. int age = 0x7FFFFFFF; int oldest = -1; for (int index = 0; index < WAGE_STATE_SIZE; ++index) { if (s[index].size() != 0 && modified[index]) { if (last_used[index] < age) { age = last_used[index]; oldest = index; } } } if (oldest == -1) throw std::invalid_argument("not enough registers for wage"); } spill(oldest); s[num] = code->allocateReg(1); } code->ldlocal(s[num], num); last_used[num] = time++; modified[num] = 0; return s[num]; } void WageState::used(int num) { last_used[num] = time++; } void WageState::dirty(int num) { modified[num] = 1; last_used[num] = time++; } void WageState::spill(int num) { if (s[num].size() == 0) { // Register not currently in use. return; } if (modified[num]) code->stlocal(s[num], num); code->releaseReg(s[num]); s[num] = Reg(); } void WageState::spillHigh() { int age = 0x7FFFFFFF; int oldest = -1; for (int index = 0; index < WAGE_STATE_SIZE; ++index) { if (s[index].size() != 0 && !modified[index]) { if (s[index].reg(0) >= 16 && last_used[index] < age) { age = last_used[index]; oldest = index; } } } if (oldest == -1) throw std::invalid_argument("cannot find a high register to spill"); spill(oldest); } void WageState::spillAny() { int age = 0x7FFFFFFF; int oldest = -1; for (int index = 0; index < WAGE_STATE_SIZE; ++index) { if (s[index].size() != 0 && !modified[index]) { if (last_used[index] < age) { age = last_used[index]; oldest = index; } } } if (oldest == -1) throw std::invalid_argument("cannot find a register to spill"); spill(oldest); } bool WageState::isActive(int num) { return s[num].size() != 0; } void WageState::copy(int to, int from) { if (s[from].size() != 0) { // The source value is already in a register. code->stlocal(s[from], to); code->releaseReg(s[from]); s[from] = Reg(); } else { // The source value is still on the stack, so copy via a temporary. code->ldlocal(temp, from); code->stlocal(temp, to); } } void gen_wage_permutation(Code &code) { int index; // Set up the function prologue with 37 bytes of local variable storage. // Z points to the permutation state on input and output. code.prologue_permutation("wage_permute", 37); // Allocate temporary registers and the state object. WageState s(code); Reg round = code.allocateHighReg(1); Reg fb = code.allocateReg(3); Reg fb0 = Reg(fb, 0, 1); Reg fb1 = Reg(fb, 1, 1); Reg fb2 = Reg(fb, 2, 1); #define S(num) (s.reg((num))) // Copy the input to local variables because we need Z to point // at the S-box, WGP, and RC tables. for (index = 0; index < 36; index += 3) { code.ldz(fb, index); code.stlocal(fb, index); } code.ldz(fb0, 36); code.stlocal(fb0, 36); // Save Z on the stack and set it up to point at the WGP/S-box table. code.push(Reg::z_ptr()); code.sbox_setup (WAGE_TABLE_WGP_SBOX, get_wage_round_constants(WAGE_TABLE_WGP_SBOX)); // Perform all rounds 3 at a time. unsigned char top_label = 0; code.move(round, 0); code.label(top_label); // Calculate the feedback value for the LFSR. // // fb = omega(s[0]) ^ s[6] ^ s[8] ^ s[12] ^ s[13] ^ s[19] ^ // s[24] ^ s[26] ^ s[30] ^ s[31] ^ WGP(s[36]) ^ RC1[round] // // where omega(x) is (x >> 1) if the low bit of x is zero and // (x >> 1) ^ 0x78 if the low bit of x is one. // // fb0 = (s[0] >> 1) ^ (0x78 & -(s[0] & 0x01)); code.ldlocal(fb0, 0); code.tworeg(Insn::MOV, s.temp.reg(0), ZERO_REG); code.lsr(fb0, 1); code.tworeg(Insn::SBC, s.temp.reg(0), ZERO_REG); code.logand(s.temp, 0x78); code.logxor(fb0, s.temp); // fb0 ^= s[6] ^ s[8] ^ s[12] ^ s[13] ^ s[19] ^ // s[24] ^ s[26] ^ s[30] ^ s[31] ^ rc[1]; code.logxor(fb0, S(6)); code.logxor(fb0, S(8)); code.logxor(fb0, S(12)); code.logxor(fb0, S(13)); code.logxor(fb0, S(19)); code.logxor(fb0, S(24)); code.logxor(fb0, S(26)); code.logxor(fb0, S(30)); code.logxor(fb0, S(31)); // fb1 = (s[1] >> 1) ^ (0x78 & -(s[1] & 0x01)); code.ldlocal(fb1, 1); code.tworeg(Insn::MOV, s.temp.reg(0), ZERO_REG); code.lsr(fb1, 1); code.tworeg(Insn::SBC, s.temp.reg(0), ZERO_REG); code.logand(s.temp, 0x78); code.logxor(fb1, s.temp); // fb1 ^= s[7] ^ s[9] ^ s[13] ^ s[14] ^ s[20] ^ // s[25] ^ s[27] ^ s[31] ^ s[32] ^ rc[3]; code.logxor(fb1, S(7)); code.logxor(fb1, S(9)); code.logxor(fb1, S(13)); code.logxor(fb1, S(14)); code.logxor(fb1, S(20)); code.logxor(fb1, S(25)); code.logxor(fb1, S(27)); code.logxor(fb1, S(31)); code.logxor(fb1, S(32)); // fb2 = (s[2] >> 1) ^ (0x78 & -(s[2] & 0x01)); code.ldlocal(fb2, 2); code.tworeg(Insn::MOV, s.temp.reg(0), ZERO_REG); code.lsr(fb2, 1); code.tworeg(Insn::SBC, s.temp.reg(0), ZERO_REG); code.logand(s.temp, 0x78); code.logxor(fb2, s.temp); // fb2 ^= s[8] ^ s[10] ^ s[14] ^ s[15] ^ s[21] ^ // s[26] ^ s[28] ^ s[32] ^ s[33] ^ rc[5]; code.logxor(fb2, S(8)); code.logxor(fb2, S(10)); code.logxor(fb2, S(14)); code.logxor(fb2, S(15)); code.logxor(fb2, S(21)); code.logxor(fb2, S(26)); code.logxor(fb2, S(28)); code.logxor(fb2, S(32)); code.logxor(fb2, S(33)); // Apply the S-box and WGP permutation to certain components. // s[5] ^= wage_sbox[s[8]]; code.sbox_lookup(s.temp, S(8)); code.logxor(S(5), s.temp); s.dirty(5); // s[6] ^= wage_sbox[s[9]]; code.sbox_lookup(s.temp, S(9)); code.logxor(S(6), s.temp); s.dirty(6); // s[7] ^= wage_sbox[s[10]]; code.sbox_lookup(s.temp, S(10)); code.logxor(S(7), s.temp); s.dirty(7); // s[11] ^= wage_sbox[s[15]]; code.sbox_lookup(s.temp, S(15)); code.logxor(S(11), s.temp); s.dirty(11); // s[12] ^= wage_sbox[s[16]]; code.sbox_lookup(s.temp, S(16)); code.logxor(S(12), s.temp); s.dirty(12); // s[13] ^= wage_sbox[s[17]]; code.sbox_lookup(s.temp, S(17)); code.logxor(S(13), s.temp); s.dirty(13); // s[24] ^= wage_sbox[s[27]]; code.sbox_lookup(s.temp, S(27)); code.logxor(S(24), s.temp); s.dirty(24); // s[25] ^= wage_sbox[s[28]]; code.sbox_lookup(s.temp, S(28)); code.logxor(S(25), s.temp); s.dirty(25); // s[26] ^= wage_sbox[s[29]]; code.sbox_lookup(s.temp, S(29)); code.logxor(S(26), s.temp); s.dirty(26); // s[30] ^= wage_sbox[s[34]]; code.sbox_lookup(s.temp, S(34)); code.logxor(S(30), s.temp); s.dirty(30); // s[31] ^= wage_sbox[s[35]]; code.sbox_lookup(s.temp, S(35)); code.logxor(S(31), s.temp); s.dirty(31); // s[32] ^= wage_sbox[s[36]]; code.sbox_lookup(s.temp, S(36)); code.logxor(S(32), s.temp); s.dirty(32); // Prepare to load round constants rc[0], rc[2], rc[4] for later. s.spillHigh(); // Need a spare high register for sbox_switch(). s.spillAny(); // Need some other spare registers for the round constants. s.spillAny(); code.sbox_switch(WAGE_TABLE_RC, get_wage_round_constants(WAGE_TABLE_RC)); Reg rc0 = code.allocateReg(1); Reg rc2 = code.allocateReg(1); Reg rc4 = code.allocateReg(1); // Load rc[0]; code.sbox_lookup(rc0, round); code.inc(round); // fb0 ^= rc[1]; code.sbox_lookup(s.temp, round); code.logxor(fb0, s.temp); code.inc(round); // Load rc[2]; code.sbox_lookup(rc2, round); code.inc(round); // fb1 ^= rc[3]; code.sbox_lookup(s.temp, round); code.logxor(fb1, s.temp); code.inc(round); // Load rc[4]; code.sbox_lookup(rc4, round); code.inc(round); // fb2 ^= rc[5]; code.sbox_lookup(s.temp, round); code.logxor(fb2, s.temp); code.inc(round); // s[19] ^= wage_wgp[s[18]] ^ rc[0]; Reg zlow = Reg(Reg::z_ptr(), 0, 1); s.spillHigh(); // Need a spare high register for sbox_switch(). code.sbox_switch (WAGE_TABLE_WGP_SBOX, get_wage_round_constants(WAGE_TABLE_WGP_SBOX)); code.move(zlow, S(18)); code.logor(zlow, 0x80); code.sbox_lookup(s.temp, zlow); code.logxor(S(19), s.temp); code.logxor(S(19), rc0); code.releaseReg(rc0); s.dirty(19); // s[20] ^= wage_wgp[s[19]] ^ rc[2]; code.move(zlow, S(19)); code.logor(zlow, 0x80); code.sbox_lookup(s.temp, zlow); code.logxor(S(20), s.temp); code.logxor(S(20), rc2); code.releaseReg(rc2); s.dirty(20); // s[21] ^= wage_wgp[s[20]] ^ rc[4]; code.move(zlow, S(20)); code.logor(zlow, 0x80); code.sbox_lookup(s.temp, zlow); code.logxor(S(21), s.temp); code.logxor(S(21), rc4); code.releaseReg(rc4); s.dirty(21); // fb0 ^= wage_wgp[s[36]]; code.move(zlow, S(36)); code.logor(zlow, 0x80); code.sbox_lookup(s.temp, zlow); code.logxor(fb0, s.temp); // fb1 ^= wage_wgp[fb0]; code.move(zlow, fb0); code.logor(zlow, 0x80); code.sbox_lookup(s.temp, zlow); code.logxor(fb1, s.temp); // fb2 ^= wage_wgp[fb1]; code.move(zlow, fb1); code.logor(zlow, 0x80); code.sbox_lookup(s.temp, zlow); code.logxor(fb2, s.temp); // Rotate the components of the state by 3 positions. for (index = 0; index < 34; ++index) s.copy(index, index + 3); code.stlocal(fb0, 34); code.stlocal(fb1, 35); code.stlocal(fb2, 36); // Bottom of the round loop. code.compare_and_loop(round, WAGE_NUM_ROUNDS * 2, top_label); // Restore Z and copy the local variables back to the state. code.sbox_cleanup(); code.pop(Reg::z_ptr()); for (index = 0; index < 36; index += 3) { code.ldlocal(fb, index); code.stz(fb, index); } code.ldlocal(fb0, 36); code.stz(fb0, 36); } // 7-bit components for the rate. static unsigned char wage_rate_bytes[10] = { 8, 9, 15, 16, 18, 27, 28, 34, 35, 36 }; void gen_wage_absorb(Code &code) { // Set up the function prologue with 0 bytes of local variable storage. code.prologue_setup_key("wage_absorb", 0); code.setFlag(Code::NoLocals); // Load the first 32 bits of the block to be absorbed. Reg temp = code.allocateReg(5); code.ldx(Reg(temp, 1, 4).reversed(), POST_INC); code.move(Reg(temp, 0, 1), 0); // Absorb the first 32-bits into the state pointed to by Z, // after breaking it up into 7-bit components. code.lsr(temp, 1); code.ldz_xor_in(Reg(temp, 4, 1), wage_rate_bytes[0]); Reg tnext = Reg(temp, 0, 4); code.lsr(tnext, 1); code.ldz_xor_in(Reg(tnext, 3, 1), wage_rate_bytes[1]); tnext = Reg(temp, 0, 3); code.lsr(tnext, 1); code.ldz_xor_in(Reg(tnext, 2, 1), wage_rate_bytes[2]); tnext = Reg(temp, 0, 2); code.lsr(tnext, 1); code.ldz_xor_in(Reg(tnext, 1, 1), wage_rate_bytes[3]); tnext = Reg(temp, 0, 1); code.lsr(tnext, 1); code.ldz_xor_in(tnext, wage_rate_bytes[4]); // Load the next 32 bits of the block to be absorbed. code.releaseReg(temp); temp = code.allocateReg(6); code.ldx(Reg(temp, 1, 4).reversed(), POST_INC); code.move(Reg(temp, 5, 1), 0); code.move(Reg(temp, 0, 1), 0); // Absorb the next 32-bits into the state pointed to by Z, // after breaking it up into 7-bit components. code.lsl(Reg(temp, 1, 5), 3); code.ldz_xor_in(Reg(temp, 5, 1), wage_rate_bytes[4]); tnext = Reg(temp, 1, 4); code.lsr(tnext, 1); code.ldz_xor_in(Reg(tnext, 3, 1), wage_rate_bytes[5]); tnext = Reg(temp, 1, 3); code.lsr(tnext, 1); code.ldz_xor_in(Reg(tnext, 2, 1), wage_rate_bytes[6]); tnext = Reg(temp, 1, 2); code.lsr(tnext, 1); code.ldz_xor_in(Reg(tnext, 1, 1), wage_rate_bytes[7]); tnext = Reg(temp, 0, 2); code.lsr(tnext, 1); code.ldz_xor_in(Reg(tnext, 1, 1), wage_rate_bytes[8]); tnext = Reg(temp, 0, 1); code.lsr(tnext, 1); code.ldz_xor_in(tnext, wage_rate_bytes[9]); } void gen_wage_get_rate(Code &code) { // Set up the function prologue with 0 bytes of local variable storage. code.prologue_setup_key("wage_get_rate", 0); code.setFlag(Code::NoLocals); // Combine the components for the first 32-bit word. Reg temp = code.allocateReg(4); code.ldz(Reg(temp, 3, 1), wage_rate_bytes[0]); code.ldz(Reg(temp, 2, 1), wage_rate_bytes[1]); code.ldz(Reg(temp, 1, 1), wage_rate_bytes[2]); code.ldz(Reg(temp, 0, 1), wage_rate_bytes[3]); code.lsl(Reg(temp, 0, 1), 1); code.lsl(Reg(temp, 0, 2), 1); code.lsl(Reg(temp, 0, 3), 1); code.lsl(Reg(temp, 0, 4), 1); Reg temp2 = code.allocateReg(1); code.ldz(temp2, wage_rate_bytes[4]); code.lsr(temp2, 3); code.logor(Reg(temp, 0, 1), temp2); code.stx(temp.reversed(), POST_INC); // Combine the components for the second 32-bit word. code.ldz(Reg(temp, 3, 1), wage_rate_bytes[4]); code.ldz(Reg(temp, 2, 1), wage_rate_bytes[5]); code.ldz(Reg(temp, 1, 1), wage_rate_bytes[6]); code.ldz(Reg(temp, 0, 1), wage_rate_bytes[7]); code.lsl(Reg(temp, 0, 1), 1); code.lsl(Reg(temp, 0, 2), 1); code.lsl(Reg(temp, 0, 3), 1); code.lsr(Reg(temp, 0, 4), 3); code.stx(Reg(temp, 0, 3).reversed(), POST_INC); code.ldz(Reg(temp, 1, 1), wage_rate_bytes[8]); code.ldz(Reg(temp, 0, 1), wage_rate_bytes[9]); code.lsl(Reg(temp, 0, 1), 1); code.lsl(Reg(temp, 0, 2), 1); code.stx(Reg(temp, 1, 1), POST_INC); } void gen_wage_set_rate(Code &code) { // Set up the function prologue with 0 bytes of local variable storage. code.prologue_setup_key("wage_set_rate", 0); code.setFlag(Code::NoLocals); // Load the first 32 bits of the block to be set. Reg temp = code.allocateReg(5); code.ldx(Reg(temp, 1, 4).reversed(), POST_INC); code.move(Reg(temp, 0, 1), 0); // Set the first 32-bits into the state pointed to by Z, // after breaking it up into 7-bit components. code.lsr(temp, 1); code.stz(Reg(temp, 4, 1), wage_rate_bytes[0]); Reg tnext = Reg(temp, 0, 4); code.lsr(tnext, 1); code.stz(Reg(tnext, 3, 1), wage_rate_bytes[1]); tnext = Reg(temp, 0, 3); code.lsr(tnext, 1); code.stz(Reg(tnext, 2, 1), wage_rate_bytes[2]); tnext = Reg(temp, 0, 2); code.lsr(tnext, 1); code.stz(Reg(tnext, 1, 1), wage_rate_bytes[3]); tnext = Reg(temp, 0, 1); code.lsr(tnext, 1); code.stz(tnext, wage_rate_bytes[4]); // Load the next 32 bits of the block to be set. code.releaseReg(temp); temp = code.allocateReg(6); code.ldx(Reg(temp, 1, 4).reversed(), POST_INC); code.move(Reg(temp, 5, 1), 0); code.move(Reg(temp, 0, 1), 0); // Set the next 32-bits into the state pointed to by Z, // after breaking it up into 7-bit components. code.lsl(Reg(temp, 1, 5), 3); code.ldz_xor_in(Reg(temp, 5, 1), wage_rate_bytes[4]); tnext = Reg(temp, 1, 4); code.lsr(tnext, 1); code.stz(Reg(tnext, 3, 1), wage_rate_bytes[5]); tnext = Reg(temp, 1, 3); code.lsr(tnext, 1); code.stz(Reg(tnext, 2, 1), wage_rate_bytes[6]); tnext = Reg(temp, 1, 2); code.lsr(tnext, 1); code.stz(Reg(tnext, 1, 1), wage_rate_bytes[7]); tnext = Reg(temp, 0, 2); code.lsr(tnext, 1); code.stz(Reg(tnext, 1, 1), wage_rate_bytes[8]); tnext = Reg(temp, 0, 1); code.lsr(tnext, 1); Reg tprev = code.allocateHighReg(1); code.ldz(tprev, wage_rate_bytes[9]); code.logand(tprev, 0x3F); code.logxor(tprev, tnext); code.stz(tprev, wage_rate_bytes[9]); } bool test_wage_permutation(Code &code) { static unsigned char const wage_input[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24 }; static unsigned char const wage_output[] = { 0x44, 0x78, 0x43, 0x21, 0x25, 0x6f, 0x30, 0x64, 0x00, 0x27, 0x00, 0x76, 0x27, 0x4b, 0x73, 0x25, 0x33, 0x43, 0x6c, 0x0e, 0x76, 0x17, 0x35, 0x49, 0x0a, 0x16, 0x69, 0x23, 0x1d, 0x39, 0x64, 0x36, 0x5f, 0x72, 0x18, 0x61, 0x01 }; unsigned char state[37]; memcpy(state, wage_input, 37); code.exec_permutation(state, 37); return !memcmp(wage_output, state, 37); }
33.367688
78
0.595083
sebastien-riou
43dd80bb7315231d74bd0a20d5a6db7da9791dce
966
cpp
C++
src/prod/src/Common/TraceKeywords.cpp
gridgentoo/ServiceFabricAzure
c3e7a07617e852322d73e6cc9819d266146866a4
[ "MIT" ]
2,542
2018-03-14T21:56:12.000Z
2019-05-06T01:18:20.000Z
src/prod/src/Common/TraceKeywords.cpp
gridgentoo/ServiceFabricAzure
c3e7a07617e852322d73e6cc9819d266146866a4
[ "MIT" ]
994
2019-05-07T02:39:30.000Z
2022-03-31T13:23:04.000Z
src/prod/src/Common/TraceKeywords.cpp
gridgentoo/ServiceFabricAzure
c3e7a07617e852322d73e6cc9819d266146866a4
[ "MIT" ]
300
2018-03-14T21:57:17.000Z
2019-05-06T20:07:00.000Z
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #include "stdafx.h" using namespace std; using namespace Common; ULONGLONG TraceKeywords::ParseTestKeyword(wstring const& testKeyword) { if (Common::StringUtility::AreEqualCaseInsensitive(testKeyword, L"Test0")) { return TraceKeywords::Test0; } if (Common::StringUtility::AreEqualCaseInsensitive(testKeyword, L"Test1")) { return TraceKeywords::Test1; } if (Common::StringUtility::AreEqualCaseInsensitive(testKeyword, L"Test2")) { return TraceKeywords::Test2; } if (Common::StringUtility::AreEqualCaseInsensitive(testKeyword, L"Test3")) { return TraceKeywords::Test3; } else return 0; }
27.6
98
0.606625
gridgentoo
43dd8c2153e9cb1f79aa7f53189a726a9d6789c0
1,131
cpp
C++
Lab03/src/Surface.cpp
ZhiquanW/CS590-Generative-Methods-in-Computer-Graphics
9bf0954ff1a8353e1abafb0b9d034ad9e0651dbe
[ "Apache-2.0" ]
null
null
null
Lab03/src/Surface.cpp
ZhiquanW/CS590-Generative-Methods-in-Computer-Graphics
9bf0954ff1a8353e1abafb0b9d034ad9e0651dbe
[ "Apache-2.0" ]
null
null
null
Lab03/src/Surface.cpp
ZhiquanW/CS590-Generative-Methods-in-Computer-Graphics
9bf0954ff1a8353e1abafb0b9d034ad9e0651dbe
[ "Apache-2.0" ]
null
null
null
// // @Author: Zhiquan Wang // @Date: 2/29/20. // Copyright (c) 2020 Zhiquan Wang. All rights reserved. // #include <Surface.h> #include "Surface.h" #include <iostream> GLuint Surface::counter = 0; Surface::Surface():id(counter++) { } Surface::Surface(glm::vec4 ids):id(counter++),indices(ids){ } bool Surface::is_contain_point(GLuint pid) { for(int i =0 ;i < 4;++ i){ if(pid == this->indices[i]){ return true; } } return false; } void Surface::set_center_pt(glm::vec3 c){ this->center_pt = c; } glm::vec2 Surface::get_edges_by_p(GLuint in_id){ GLuint tmp_id = -1; for(int i =0 ;i < 4;++ i){ if(in_id == this->indices[i]){ tmp_id = i; break; } } return glm::vec2(this->indices[(tmp_id+1)%4],this->indices[(tmp_id+3)%4]); } bool Surface::contain_edge(std::vector<GLuint> edge){ bool b0 = false; bool b1 = false; for(int i =0 ;i < 4;++ i){ if(float(edge[0]) ==indices[i]){ b0 = true; }else if(float(edge[1])==indices[i]){ b1 = true; } } return b0 && b1; }
20.563636
78
0.545535
ZhiquanW
43e17202b3aeb80911d8381f074a4a1bfe0c371f
2,948
cpp
C++
sigpack/demo_c++/sp_demo_107_1.cpp
mjeronimo/carma-utils
f39ae9b52e43e3d38f938d2327d786808c9819b5
[ "Apache-2.0" ]
1
2021-12-19T08:18:08.000Z
2021-12-19T08:18:08.000Z
sigpack/demo_c++/sp_demo_107_1.cpp
mjeronimo/carma-utils
f39ae9b52e43e3d38f938d2327d786808c9819b5
[ "Apache-2.0" ]
57
2020-05-07T20:34:02.000Z
2022-03-31T20:04:50.000Z
sigpack/demo_c++/sp_demo_107_1.cpp
mjeronimo/carma-utils
f39ae9b52e43e3d38f938d2327d786808c9819b5
[ "Apache-2.0" ]
4
2021-05-25T22:38:41.000Z
2022-03-09T04:35:47.000Z
#include <sigpack.h> using namespace arma; using namespace sp; int main() { int r=480, c=640; mat x(r,c); cx_mat X(r,c); clock_t tic; FFTW X_2d(r,c, FFTW_MEASURE); x.randn(); #if 1 // X_2d.export_wisdom_fft("wisd_fft.txt"); // X_2d.import_wisdom_file("wisd_fft.txt"); std::string str_fft = "\ (fftw-3.3.5 fftw_wisdom #x4be12fff #x7b2df9b2 #xa5975329 #x385b0041 \ (fftw_codelet_hc2cf_32 0 #x11048 #x11048 #x0 #x882273a3 #x56a533d6 #xc6c3347e #xd190e241) \ (fftw_dft_vrank_geq1_register 0 #x10048 #x10048 #x0 #x099817e7 #xc596b28c #xe506412c #x581cf2d0) \ (fftw_rdft2_rank_geq2_register 0 #x11048 #x11048 #x0 #xed40bad3 #x93c23437 #xaf3711ed #x603ee510) \ (fftw_rdft2_vrank_geq1_register 0 #x11048 #x11048 #x0 #x1a6357c6 #x413f903b #x74fe70f1 #xfccb5c54) \ (fftw_rdft_rank0_register 3 #x11048 #x11048 #x0 #x02d4eca5 #x884a04c6 #x3f0ad214 #xda717200) \ (fftw_dft_buffered_register 0 #x11048 #x11048 #x0 #x6196ea82 #x099f9b85 #x08198834 #xe7593275) \ (fftw_codelet_t1_10 0 #x10048 #x10048 #x0 #xba1708ce #x154e0e87 #x86aebd39 #xcb9e43fe) \ (fftw_rdft_vrank_geq1_register 1 #x11048 #x11048 #x0 #x081f12db #xc5b1275f #x5907e52d #x646a8914) \ (fftw_dft_r2hc_register 0 #x11048 #x11048 #x0 #x514942d9 #xe0534dce #x7d1dcd63 #xde881c5a) \ (fftw_codelet_n1_64 0 #x10048 #x10048 #x0 #x9dcd7b03 #xdf2d4251 #x0230d342 #xde1fe96d) \ (fftw_dft_r2hc_register 0 #x11048 #x11048 #x0 #x43917e3e #x5c1ab09e #xdc26854f #x352833a8) \ (fftw_codelet_r2cf_15 0 #x11048 #x11048 #x0 #x251274f4 #x219f0dbb #x0c38f4e4 #xf19e1c79) \ (fftw_dft_nop_register 0 #x11048 #x11048 #x0 #xc1cc28d6 #x5c67e01b #x280816eb #x7ee0ce02) \ (fftw_codelet_r2cf_32 2 #x11048 #x11048 #x0 #xc267a0b3 #xc28de71d #x550f0573 #x959c40e7) \ (fftw_codelet_n1_64 0 #x10048 #x10048 #x0 #x101f223c #xcff4353b #xd4a553bb #xe3ff9319) \ (fftw_dft_buffered_register 0 #x11048 #x11048 #x0 #x9973ff81 #x0b0fdaf1 #xfd5496b5 #xfe9c4fba) \ (fftw_codelet_t1_10 0 #x10048 #x10048 #x0 #x47334bf5 #x898f072c #x86c99502 #xe82acf7f) \ (fftw_rdft_rank0_register 2 #x11048 #x11048 #x0 #x5c2cc86a #x3d86b0c3 #xe3aeadc0 #xdc7e28da) \ (fftw_rdft2_nop_register 0 #x11048 #x11048 #x0 #xf80d9535 #x1b15b669 #x8ee1f97f #x42fa82cd))"; X_2d.import_wisdom_string(str_fft); tic = clock(); X = fft2(x); cout << "FFT Time using arma::fft2()= " << (clock() - tic) / double(CLOCKS_PER_SEC) << endl; tic = clock(); X = X_2d.fft2(x); cout << "FFTW Time using Wisdom= " << (clock() - tic) / double(CLOCKS_PER_SEC) << endl; #else tic = clock(); X = fft2(x); cout << "FFT Time using arma::fft2()= " << (clock() - tic) / double(CLOCKS_PER_SEC) << endl; tic = clock(); X = X_2d.fft2(x); cout << "FFTW Time without Wisdom= " << (clock() - tic) / double(CLOCKS_PER_SEC) << endl; #endif return 0; }
46.793651
107
0.678087
mjeronimo
43eb9f718f235af0cb1021283999590d89344d39
3,883
cpp
C++
cpp/dpf_pir/bench.cpp
dkales/certificate-transparency
439d41314032f58cd15731b22f5f3a07def7ae9e
[ "Apache-2.0" ]
1
2019-04-09T14:13:21.000Z
2019-04-09T14:13:21.000Z
cpp/dpf_pir/bench.cpp
dkales/certificate-transparency
439d41314032f58cd15731b22f5f3a07def7ae9e
[ "Apache-2.0" ]
null
null
null
cpp/dpf_pir/bench.cpp
dkales/certificate-transparency
439d41314032f58cd15731b22f5f3a07def7ae9e
[ "Apache-2.0" ]
null
null
null
#include "dpf.h" #include "hashdatastore.h" #include <chrono> #include <iostream> void benchEvalFull(size_t N, size_t iter) { std::chrono::duration<double> buildT, evalT, answerT; buildT = evalT = answerT = std::chrono::duration<double>::zero(); std::cout << "EvalFull, " << iter << " iterations" << std::endl; auto time1 = std::chrono::high_resolution_clock::now(); auto keys = DPF::Gen(0, N); auto a = keys.first; auto time2 = std::chrono::high_resolution_clock::now(); for(size_t i = 0; i < iter; i++) { std::vector<uint8_t> aaaa = DPF::EvalFull(a, N); } auto time3 = std::chrono::high_resolution_clock::now(); buildT += time2 - time1; evalT += time3 - time2; std::cout << buildT.count() << "sec" << std::endl; std::cout << evalT.count() << "sec" << std::endl; } void benchEvalFull8(size_t N, size_t iter) { std::chrono::duration<double> buildT, evalT, answerT; buildT = evalT = answerT = std::chrono::duration<double>::zero(); std::cout << "EvalFull8, " << iter << " iterations" << std::endl; auto time1 = std::chrono::high_resolution_clock::now(); auto keys = DPF::Gen(0, N); auto a = keys.first; auto time2 = std::chrono::high_resolution_clock::now(); for(size_t i = 0; i < iter; i++) { std::vector<uint8_t> aaaa = DPF::EvalFull8(a, N); } auto time3 = std::chrono::high_resolution_clock::now(); buildT += time2 - time1; evalT += time3 - time2; std::cout << buildT.count() << "sec" << std::endl; std::cout << evalT.count() << "sec" << std::endl; } void benchAnswerPIR(size_t N, size_t iter) { std::array<std::chrono::duration<double>,6> answerT = {std::chrono::duration<double>::zero(), }; std::cout << "AnswerPIR, " << iter << " iterations" << std::endl; auto keys = DPF::Gen(0, N); auto a = keys.first; hashdatastore store; store.reserve(1ULL << N); for (size_t i = 0; i < (1ULL << N); i++) { store.push_back(_mm256_set_epi64x(i, i, i, i)); } std::vector<uint8_t> aaaa = DPF::EvalFull8(a, N); for(size_t i = 0; i < iter; i++) { auto time0 = std::chrono::high_resolution_clock::now(); hashdatastore::hash_type answer0 = store.answer_pir_idea_speed_comparison(aaaa); auto time1 = std::chrono::high_resolution_clock::now(); hashdatastore::hash_type answer1 = store.answer_pir1(aaaa); auto time2 = std::chrono::high_resolution_clock::now(); hashdatastore::hash_type answer2 = store.answer_pir2(aaaa); auto time3 = std::chrono::high_resolution_clock::now(); hashdatastore::hash_type answer3 = store.answer_pir3(aaaa); auto time4 = std::chrono::high_resolution_clock::now(); hashdatastore::hash_type answer4 = store.answer_pir4(aaaa); auto time5 = std::chrono::high_resolution_clock::now(); hashdatastore::hash_type answer5 = store.answer_pir5(aaaa); auto time6 = std::chrono::high_resolution_clock::now(); answerT[0] += time1-time0; answerT[1] += time2-time1; answerT[2] += time3-time2; answerT[3] += time4-time3; answerT[4] += time5-time4; answerT[5] += time6-time5; } std::cout << "AnswerPIR ideal " << answerT[0].count() << "sec" << std::endl; std::cout << "AnswerPIR1 " << answerT[1].count() << "sec" << std::endl; std::cout << "AnswerPIR2 " << answerT[2].count() << "sec" << std::endl; std::cout << "AnswerPIR3 " << answerT[3].count() << "sec" << std::endl; std::cout << "AnswerPIR4 " << answerT[4].count() << "sec" << std::endl; std::cout << "AnswerPIR5 " << answerT[5].count() << "sec" << std::endl; } int main(int argc, char** argv) { size_t N = 27; size_t iter = 100; benchEvalFull(N, iter); benchEvalFull8(N, iter); //benchAnswerPIR(25,100); return 0; }
39.622449
100
0.601082
dkales
43ee8cbca82e5d6bb34e91814d8ad6c93019e28a
3,400
cpp
C++
resources/cros_testbed/src/std_msgs_listener.cpp
ProfFan/cros
25a0721bcd30c1dd3c02ada08c4bd067ceb4142d
[ "BSD-3-Clause" ]
35
2016-03-08T18:15:55.000Z
2021-11-20T11:13:27.000Z
resources/cros_testbed/src/std_msgs_listener.cpp
ProfFan/cros
25a0721bcd30c1dd3c02ada08c4bd067ceb4142d
[ "BSD-3-Clause" ]
11
2016-03-03T10:31:18.000Z
2020-05-05T15:36:59.000Z
resources/cros_testbed/src/std_msgs_listener.cpp
ProfFan/cros
25a0721bcd30c1dd3c02ada08c4bd067ceb4142d
[ "BSD-3-Clause" ]
25
2016-03-08T15:54:23.000Z
2021-11-23T09:50:11.000Z
#include <ros/ros.h> #include <std_msgs/Bool.h> #include <std_msgs/Byte.h> #include <std_msgs/Char.h> #include <std_msgs/Duration.h> #include <std_msgs/Time.h> #include <std_msgs/Int16.h> #include <std_msgs/Int32.h> #include <std_msgs/Int64.h> #include <std_msgs/Int8.h> #include <std_msgs/Header.h> #include <std_msgs/UInt16.h> #include <std_msgs/UInt32.h> #include <std_msgs/UInt64.h> #include <std_msgs/UInt8.h> #include <std_msgs/Float32.h> #include <std_msgs/Float64.h> void chatter1(const std_msgs::Bool::ConstPtr& msg) { ROS_INFO("I heard: [%s]", msg->data ? "true" : "false"); } void chatter2(const std_msgs::Byte::ConstPtr& msg) { ROS_INFO("I heard: [%i]", msg->data); } void chatter3(const std_msgs::Char::ConstPtr& msg) { ROS_INFO("I heard: [%i]", msg->data); } void chatter4(const std_msgs::Duration::ConstPtr& msg) { ROS_INFO("I heard: sec=[%i] nsec=[%i]", msg->data.sec, msg->data.nsec); } void chatter5(const std_msgs::Header::ConstPtr& msg) { ROS_INFO("I heard: seq = [%i], time = [%i, %i], frame_id = [%s]", msg->seq, msg->stamp.sec, msg->stamp.nsec, msg->frame_id.c_str()); } void chatter6(const std_msgs::Int16::ConstPtr& msg) { ROS_INFO("I heard: [%i]", msg->data); } void chatter7(const std_msgs::Int32::ConstPtr& msg) { ROS_INFO("I heard: [%i]", msg->data); } void chatter8(const std_msgs::Int64::ConstPtr& msg) { ROS_INFO("I heard: [%lli]", msg->data); } void chatter9(const std_msgs::Int8::ConstPtr& msg) { ROS_INFO("I heard: [%i]", msg->data); } void chatter10(const std_msgs::Time::ConstPtr& msg) { ROS_INFO("I heard: sec=[%i] nsec=[%i]", msg->data.sec, msg->data.nsec); } void chatter11(const std_msgs::UInt16::ConstPtr& msg) { ROS_INFO("I heard: [%i]", msg->data); } void chatter12(const std_msgs::UInt32::ConstPtr& msg) { ROS_INFO("I heard: [%i]", msg->data); } void chatter13(const std_msgs::UInt64::ConstPtr& msg) { ROS_INFO("I heard: [%lli]", msg->data); } void chatter14(const std_msgs::UInt8::ConstPtr& msg) { ROS_INFO("I heard: [%i]", msg->data); } void chatter15(const std_msgs::Float32::ConstPtr& msg) { ROS_INFO("I heard: [%f]", msg->data); } void chatter16(const std_msgs::Float64::ConstPtr& msg) { ROS_INFO("I heard: [%f]", msg->data); } int main(int argc, char **argv) { ros::init(argc, argv, "std_msgs_listener"); ros::NodeHandle n; ros::Subscriber sub1 = n.subscribe("bool", 1000, chatter1); ros::Subscriber sub2 = n.subscribe("byte", 1000, chatter2); ros::Subscriber sub3 = n.subscribe("char", 1000, chatter3); ros::Subscriber sub4 = n.subscribe("duration", 1000, chatter4); ros::Subscriber sub5 = n.subscribe("header", 1000, chatter5); ros::Subscriber sub6 = n.subscribe("/int16", 1000, chatter6); ros::Subscriber sub7 = n.subscribe("/int32", 1000, chatter7); ros::Subscriber sub8 = n.subscribe("/int64", 1000, chatter8); ros::Subscriber sub9 = n.subscribe("/int8", 1000, chatter9); ros::Subscriber sub10 = n.subscribe("/time", 1000, chatter10); ros::Subscriber sub11 = n.subscribe("/uint16", 1000, chatter11); ros::Subscriber sub12 = n.subscribe("/uint32", 1000, chatter12); ros::Subscriber sub13 = n.subscribe("/uint64", 1000, chatter13); ros::Subscriber sub14 = n.subscribe("/uint8", 1000, chatter14); ros::Subscriber sub15 = n.subscribe("/float32", 1000, chatter15); ros::Subscriber sub16 = n.subscribe("/float64", 1000, chatter16); ros::spin(); return 0; }
26.984127
134
0.675294
ProfFan
43f228ff12c45e305fb11f696dfa17b8d21919fa
28,271
cc
C++
chrome/browser/ui/passwords/manage_passwords_state_unittest.cc
mghgroup/Glide-Browser
6a4c1eaa6632ec55014fee87781c6bbbb92a2af5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/ui/passwords/manage_passwords_state_unittest.cc
mghgroup/Glide-Browser
6a4c1eaa6632ec55014fee87781c6bbbb92a2af5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/ui/passwords/manage_passwords_state_unittest.cc
mghgroup/Glide-Browser
6a4c1eaa6632ec55014fee87781c6bbbb92a2af5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2021-01-05T23:43:46.000Z
2021-01-07T23:36:34.000Z
// Copyright 2015 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/browser/ui/passwords/manage_passwords_state.h" #include <iterator> #include <memory> #include <utility> #include <vector> #include "base/bind.h" #include "base/memory/ptr_util.h" #include "base/strings/utf_string_conversions.h" #include "base/test/mock_callback.h" #include "components/password_manager/core/browser/mock_password_form_manager_for_ui.h" #include "components/password_manager/core/browser/stub_password_manager_client.h" #include "components/password_manager/core/common/password_manager_ui.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/gurl.h" #include "url/origin.h" using autofill::PasswordForm; using base::ASCIIToUTF16; using password_manager::MockPasswordFormManagerForUI; using password_manager::PasswordStoreChange; using password_manager::PasswordStoreChangeList; using ::testing::_; using ::testing::Contains; using ::testing::ElementsAre; using ::testing::IsEmpty; using ::testing::Mock; using ::testing::Not; using ::testing::Pointee; using ::testing::Return; using ::testing::UnorderedElementsAre; namespace { constexpr char kTestOrigin[] = "http://example.com/"; constexpr char kTestPSLOrigin[] = "http://1.example.com/"; std::vector<const PasswordForm*> GetRawPointers( const std::vector<std::unique_ptr<PasswordForm>>& forms) { std::vector<const PasswordForm*> result; std::transform( forms.begin(), forms.end(), std::back_inserter(result), [](const std::unique_ptr<PasswordForm>& form) { return form.get(); }); return result; } class MockPasswordManagerClient : public password_manager::StubPasswordManagerClient { public: MOCK_METHOD0(UpdateFormManagers, void()); }; class ManagePasswordsStateTest : public testing::Test { public: void SetUp() override { saved_match_.url = GURL(kTestOrigin); saved_match_.signon_realm = kTestOrigin; saved_match_.username_value = base::ASCIIToUTF16("username"); saved_match_.username_element = base::ASCIIToUTF16("username_element"); saved_match_.password_value = base::ASCIIToUTF16("12345"); saved_match_.password_element = base::ASCIIToUTF16("password_element"); psl_match_ = saved_match_; psl_match_.url = GURL(kTestPSLOrigin); psl_match_.signon_realm = kTestPSLOrigin; psl_match_.username_value = base::ASCIIToUTF16("username_psl"); psl_match_.is_public_suffix_match = true; local_federated_form_ = saved_match_; local_federated_form_.federation_origin = url::Origin::Create(GURL("https://idp.com")); local_federated_form_.password_value.clear(); local_federated_form_.signon_realm = "federation://example.com/accounts.com"; passwords_data_.set_client(&mock_client_); } PasswordForm& saved_match() { return saved_match_; } PasswordForm& psl_match() { return psl_match_; } PasswordForm& local_federated_form() { return local_federated_form_; } ManagePasswordsState& passwords_data() { return passwords_data_; } // Returns a mock PasswordFormManager containing |best_matches| and // |federated_matches|. std::unique_ptr<MockPasswordFormManagerForUI> CreateFormManager( std::vector<const PasswordForm*>* best_matches, const std::vector<const PasswordForm*>& federated_matches); // Pushes irrelevant updates to |passwords_data_| and checks that they don't // affect the state. void TestNoisyUpdates(); // Pushes both relevant and irrelevant updates to |passwords_data_|. void TestAllUpdates(); // Pushes a blocklisted form and checks that it doesn't affect the state. void TestBlocklistedUpdates(); private: MockPasswordManagerClient mock_client_; ManagePasswordsState passwords_data_; PasswordForm saved_match_; PasswordForm psl_match_; PasswordForm local_federated_form_; }; std::unique_ptr<MockPasswordFormManagerForUI> ManagePasswordsStateTest::CreateFormManager( std::vector<const PasswordForm*>* best_matches, const std::vector<const PasswordForm*>& federated_matches) { auto form_manager = std::make_unique<MockPasswordFormManagerForUI>(); EXPECT_CALL(*form_manager, GetBestMatches()) .WillOnce(testing::ReturnRef(*best_matches)); EXPECT_CALL(*form_manager, GetFederatedMatches()) .WillOnce(Return(federated_matches)); EXPECT_CALL(*form_manager, GetURL()) .WillOnce(testing::ReturnRef(saved_match_.url)); return form_manager; } void ManagePasswordsStateTest::TestNoisyUpdates() { const std::vector<const PasswordForm*> forms = GetRawPointers(passwords_data_.GetCurrentForms()); const password_manager::ui::State state = passwords_data_.state(); const url::Origin origin = passwords_data_.origin(); // Push "Add". PasswordForm form; form.url = GURL("http://3rdparty.com"); form.username_value = base::ASCIIToUTF16("username"); form.password_value = base::ASCIIToUTF16("12345"); PasswordStoreChange change(PasswordStoreChange::ADD, form); PasswordStoreChangeList list(1, change); passwords_data().ProcessLoginsChanged(list); EXPECT_EQ(forms, GetRawPointers(passwords_data().GetCurrentForms())); EXPECT_EQ(state, passwords_data().state()); EXPECT_EQ(origin, passwords_data().origin()); // Update the form. form.password_value = base::ASCIIToUTF16("password"); list[0] = PasswordStoreChange(PasswordStoreChange::UPDATE, form); passwords_data().ProcessLoginsChanged(list); EXPECT_EQ(forms, GetRawPointers(passwords_data().GetCurrentForms())); EXPECT_EQ(state, passwords_data().state()); EXPECT_EQ(origin, passwords_data().origin()); // Delete the form. list[0] = PasswordStoreChange(PasswordStoreChange::REMOVE, form); passwords_data().ProcessLoginsChanged(list); EXPECT_EQ(forms, GetRawPointers(passwords_data().GetCurrentForms())); EXPECT_EQ(state, passwords_data().state()); EXPECT_EQ(origin, passwords_data().origin()); } void ManagePasswordsStateTest::TestAllUpdates() { const std::vector<const PasswordForm*> forms = GetRawPointers(passwords_data_.GetCurrentForms()); const password_manager::ui::State state = passwords_data_.state(); const url::Origin origin = passwords_data_.origin(); EXPECT_NE(url::Origin(), origin); // Push "Add". PasswordForm form; GURL::Replacements replace_path; replace_path.SetPathStr("absolutely_different_path"); form.url = origin.GetURL().ReplaceComponents(replace_path); form.signon_realm = form.url.GetOrigin().spec(); form.username_value = base::ASCIIToUTF16("user15"); form.password_value = base::ASCIIToUTF16("12345"); PasswordStoreChange change(PasswordStoreChange::ADD, form); PasswordStoreChangeList list(1, change); EXPECT_CALL(mock_client_, UpdateFormManagers()).Times(0); passwords_data().ProcessLoginsChanged(list); EXPECT_THAT(passwords_data().GetCurrentForms(), Contains(Pointee(form))); EXPECT_EQ(state, passwords_data().state()); EXPECT_EQ(origin, passwords_data().origin()); Mock::VerifyAndClearExpectations(&mock_client_); // Remove and Add form. list[0] = PasswordStoreChange(PasswordStoreChange::REMOVE, form); form.username_value = base::ASCIIToUTF16("user15"); list.push_back(PasswordStoreChange(PasswordStoreChange::ADD, form)); EXPECT_CALL(mock_client_, UpdateFormManagers()).Times(0); passwords_data().ProcessLoginsChanged(list); EXPECT_EQ(state, passwords_data().state()); EXPECT_EQ(origin, passwords_data().origin()); Mock::VerifyAndClearExpectations(&mock_client_); list.erase(++list.begin()); // Update the form. form.password_value = base::ASCIIToUTF16("password"); list[0] = PasswordStoreChange(PasswordStoreChange::UPDATE, form); EXPECT_CALL(mock_client_, UpdateFormManagers()).Times(0); passwords_data().ProcessLoginsChanged(list); EXPECT_THAT(passwords_data().GetCurrentForms(), Contains(Pointee(form))); EXPECT_EQ(state, passwords_data().state()); EXPECT_EQ(origin, passwords_data().origin()); Mock::VerifyAndClearExpectations(&mock_client_); // Delete the form. list[0] = PasswordStoreChange(PasswordStoreChange::REMOVE, form); EXPECT_CALL(mock_client_, UpdateFormManagers()); passwords_data().ProcessLoginsChanged(list); EXPECT_EQ(forms, GetRawPointers(passwords_data().GetCurrentForms())); EXPECT_EQ(state, passwords_data().state()); EXPECT_EQ(origin, passwords_data().origin()); Mock::VerifyAndClearExpectations(&mock_client_); TestNoisyUpdates(); } void ManagePasswordsStateTest::TestBlocklistedUpdates() { const std::vector<const PasswordForm*> forms = GetRawPointers(passwords_data_.GetCurrentForms()); const password_manager::ui::State state = passwords_data_.state(); const url::Origin origin = passwords_data_.origin(); EXPECT_FALSE(origin.opaque()); // Process the blocked form. PasswordForm blocked_form; blocked_form.blocked_by_user = true; blocked_form.url = origin.GetURL(); PasswordStoreChangeList list; list.push_back(PasswordStoreChange(PasswordStoreChange::ADD, blocked_form)); passwords_data().ProcessLoginsChanged(list); EXPECT_EQ(forms, GetRawPointers(passwords_data().GetCurrentForms())); EXPECT_EQ(state, passwords_data().state()); EXPECT_EQ(origin, passwords_data().origin()); // Delete the blocked form. list[0] = PasswordStoreChange(PasswordStoreChange::REMOVE, blocked_form); passwords_data().ProcessLoginsChanged(list); EXPECT_EQ(forms, GetRawPointers(passwords_data().GetCurrentForms())); EXPECT_EQ(state, passwords_data().state()); EXPECT_EQ(origin, passwords_data().origin()); } TEST_F(ManagePasswordsStateTest, DefaultState) { EXPECT_THAT(passwords_data().GetCurrentForms(), IsEmpty()); EXPECT_EQ(password_manager::ui::INACTIVE_STATE, passwords_data().state()); EXPECT_TRUE(passwords_data().origin().opaque()); EXPECT_FALSE(passwords_data().form_manager()); TestNoisyUpdates(); } TEST_F(ManagePasswordsStateTest, PasswordSubmitted) { std::vector<const PasswordForm*> best_matches = {&saved_match(), &psl_match()}; std::unique_ptr<MockPasswordFormManagerForUI> test_form_manager( CreateFormManager(&best_matches, {})); passwords_data().OnPendingPassword(std::move(test_form_manager)); EXPECT_THAT(passwords_data().GetCurrentForms(), ElementsAre(Pointee(saved_match()))); EXPECT_EQ(password_manager::ui::PENDING_PASSWORD_STATE, passwords_data().state()); EXPECT_EQ(url::Origin::Create(GURL(kTestOrigin)), passwords_data().origin()); ASSERT_TRUE(passwords_data().form_manager()); TestAllUpdates(); } TEST_F(ManagePasswordsStateTest, PasswordSaved) { std::vector<const PasswordForm*> best_matches = {&saved_match()}; std::unique_ptr<MockPasswordFormManagerForUI> test_form_manager( CreateFormManager(&best_matches, {})); passwords_data().OnPendingPassword(std::move(test_form_manager)); EXPECT_EQ(password_manager::ui::PENDING_PASSWORD_STATE, passwords_data().state()); passwords_data().TransitionToState(password_manager::ui::MANAGE_STATE); EXPECT_THAT(passwords_data().GetCurrentForms(), ElementsAre(Pointee(saved_match()))); EXPECT_EQ(password_manager::ui::MANAGE_STATE, passwords_data().state()); EXPECT_EQ(url::Origin::Create(GURL(kTestOrigin)), passwords_data().origin()); TestAllUpdates(); } TEST_F(ManagePasswordsStateTest, PasswordSubmittedFederationsPresent) { std::vector<const PasswordForm*> best_matches; std::unique_ptr<MockPasswordFormManagerForUI> test_form_manager( CreateFormManager(&best_matches, {&local_federated_form()})); passwords_data().OnPendingPassword(std::move(test_form_manager)); EXPECT_THAT(passwords_data().GetCurrentForms(), ElementsAre(Pointee(local_federated_form()))); } TEST_F(ManagePasswordsStateTest, OnRequestCredentials) { std::vector<std::unique_ptr<PasswordForm>> local_credentials; local_credentials.emplace_back(new PasswordForm(saved_match())); const url::Origin origin = url::Origin::Create(saved_match().url); passwords_data().OnRequestCredentials(std::move(local_credentials), origin); base::MockCallback<ManagePasswordsState::CredentialsCallback> callback; passwords_data().set_credentials_callback(callback.Get()); EXPECT_THAT(passwords_data().GetCurrentForms(), ElementsAre(Pointee(saved_match()))); EXPECT_EQ(password_manager::ui::CREDENTIAL_REQUEST_STATE, passwords_data().state()); EXPECT_EQ(origin, passwords_data().origin()); TestAllUpdates(); EXPECT_CALL(callback, Run(nullptr)); passwords_data().TransitionToState(password_manager::ui::MANAGE_STATE); EXPECT_TRUE(passwords_data().credentials_callback().is_null()); EXPECT_THAT(passwords_data().GetCurrentForms(), ElementsAre(Pointee(saved_match()))); EXPECT_EQ(password_manager::ui::MANAGE_STATE, passwords_data().state()); EXPECT_EQ(origin, passwords_data().origin()); TestAllUpdates(); } TEST_F(ManagePasswordsStateTest, AutoSignin) { std::vector<std::unique_ptr<PasswordForm>> local_credentials; local_credentials.emplace_back(new PasswordForm(saved_match())); passwords_data().OnAutoSignin(std::move(local_credentials), url::Origin::Create(saved_match().url)); EXPECT_THAT(passwords_data().GetCurrentForms(), ElementsAre(Pointee(saved_match()))); EXPECT_EQ(password_manager::ui::AUTO_SIGNIN_STATE, passwords_data().state()); EXPECT_EQ(url::Origin::Create(saved_match().url), passwords_data().origin()); TestAllUpdates(); passwords_data().TransitionToState(password_manager::ui::MANAGE_STATE); EXPECT_THAT(passwords_data().GetCurrentForms(), ElementsAre(Pointee(saved_match()))); EXPECT_EQ(password_manager::ui::MANAGE_STATE, passwords_data().state()); EXPECT_EQ(url::Origin::Create(saved_match().url), passwords_data().origin()); TestAllUpdates(); } TEST_F(ManagePasswordsStateTest, AutomaticPasswordSave) { std::vector<const PasswordForm*> best_matches = {&saved_match(), &psl_match()}; std::unique_ptr<MockPasswordFormManagerForUI> test_form_manager( CreateFormManager(&best_matches, {})); passwords_data().OnAutomaticPasswordSave(std::move(test_form_manager)); EXPECT_EQ(password_manager::ui::CONFIRMATION_STATE, passwords_data().state()); EXPECT_EQ(url::Origin::Create(GURL(kTestOrigin)), passwords_data().origin()); ASSERT_TRUE(passwords_data().form_manager()); TestAllUpdates(); passwords_data().TransitionToState(password_manager::ui::MANAGE_STATE); EXPECT_THAT(passwords_data().GetCurrentForms(), ElementsAre(Pointee(saved_match()))); EXPECT_EQ(password_manager::ui::MANAGE_STATE, passwords_data().state()); EXPECT_EQ(url::Origin::Create(GURL(kTestOrigin)), passwords_data().origin()); TestAllUpdates(); } TEST_F(ManagePasswordsStateTest, AutomaticPasswordSaveWithFederations) { std::vector<const PasswordForm*> best_matches = {&saved_match()}; std::unique_ptr<MockPasswordFormManagerForUI> test_form_manager( CreateFormManager(&best_matches, {&local_federated_form()})); passwords_data().OnAutomaticPasswordSave(std::move(test_form_manager)); EXPECT_THAT(passwords_data().GetCurrentForms(), UnorderedElementsAre(Pointee(saved_match()), Pointee(local_federated_form()))); } TEST_F(ManagePasswordsStateTest, PasswordAutofilled) { std::vector<const PasswordForm*> password_forms; password_forms.push_back(&saved_match()); const url::Origin origin = url::Origin::Create(GURL(kTestOrigin)); passwords_data().OnPasswordAutofilled(password_forms, origin, nullptr); EXPECT_THAT(passwords_data().GetCurrentForms(), ElementsAre(Pointee(saved_match()))); EXPECT_EQ(password_manager::ui::MANAGE_STATE, passwords_data().state()); EXPECT_EQ(origin, passwords_data().origin()); TestAllUpdates(); } TEST_F(ManagePasswordsStateTest, PasswordAutofillWithSavedFederations) { std::vector<const PasswordForm*> password_forms; password_forms.push_back(&saved_match()); const url::Origin origin = url::Origin::Create(GURL(kTestOrigin)); std::vector<const PasswordForm*> federated; federated.push_back(&local_federated_form()); passwords_data().OnPasswordAutofilled(password_forms, origin, &federated); // |federated| represents the locally saved federations. These are bundled in // the "current forms". EXPECT_THAT(passwords_data().GetCurrentForms(), UnorderedElementsAre(Pointee(saved_match()), Pointee(local_federated_form()))); // |federated_credentials_forms()| do not refer to the saved federations. EXPECT_EQ(password_manager::ui::MANAGE_STATE, passwords_data().state()); } TEST_F(ManagePasswordsStateTest, PasswordAutofillWithOnlyFederations) { std::vector<const PasswordForm*> password_forms; const url::Origin origin = url::Origin::Create(GURL(kTestOrigin)); std::vector<const PasswordForm*> federated; federated.push_back(&local_federated_form()); passwords_data().OnPasswordAutofilled(password_forms, origin, &federated); EXPECT_THAT(passwords_data().GetCurrentForms(), ElementsAre(Pointee(local_federated_form()))); EXPECT_EQ(password_manager::ui::MANAGE_STATE, passwords_data().state()); } TEST_F(ManagePasswordsStateTest, ActiveOnMixedPSLAndNonPSLMatched) { std::vector<const PasswordForm*> password_forms; password_forms.push_back(&saved_match()); password_forms.push_back(&psl_match()); const url::Origin origin = url::Origin::Create(GURL(kTestOrigin)); passwords_data().OnPasswordAutofilled(password_forms, origin, nullptr); EXPECT_THAT(passwords_data().GetCurrentForms(), ElementsAre(Pointee(saved_match()))); EXPECT_EQ(password_manager::ui::MANAGE_STATE, passwords_data().state()); EXPECT_EQ(origin, passwords_data().origin()); TestAllUpdates(); } TEST_F(ManagePasswordsStateTest, InactiveOnPSLMatched) { std::vector<const PasswordForm*> password_forms; password_forms.push_back(&psl_match()); passwords_data().OnPasswordAutofilled( password_forms, url::Origin::Create(GURL(kTestOrigin)), nullptr); EXPECT_THAT(passwords_data().GetCurrentForms(), IsEmpty()); EXPECT_EQ(password_manager::ui::INACTIVE_STATE, passwords_data().state()); EXPECT_TRUE(passwords_data().origin().opaque()); EXPECT_FALSE(passwords_data().form_manager()); } TEST_F(ManagePasswordsStateTest, OnInactive) { std::vector<const PasswordForm*> best_matches; std::unique_ptr<MockPasswordFormManagerForUI> test_form_manager( CreateFormManager(&best_matches, {})); passwords_data().OnPendingPassword(std::move(test_form_manager)); EXPECT_EQ(password_manager::ui::PENDING_PASSWORD_STATE, passwords_data().state()); passwords_data().OnInactive(); EXPECT_THAT(passwords_data().GetCurrentForms(), IsEmpty()); EXPECT_EQ(password_manager::ui::INACTIVE_STATE, passwords_data().state()); EXPECT_TRUE(passwords_data().origin().opaque()); EXPECT_FALSE(passwords_data().form_manager()); TestNoisyUpdates(); } TEST_F(ManagePasswordsStateTest, PendingPasswordAddBlacklisted) { std::vector<const PasswordForm*> best_matches; std::unique_ptr<MockPasswordFormManagerForUI> test_form_manager( CreateFormManager(&best_matches, {})); passwords_data().OnPendingPassword(std::move(test_form_manager)); EXPECT_EQ(password_manager::ui::PENDING_PASSWORD_STATE, passwords_data().state()); TestBlocklistedUpdates(); } TEST_F(ManagePasswordsStateTest, RequestCredentialsAddBlacklisted) { std::vector<std::unique_ptr<PasswordForm>> local_credentials; local_credentials.emplace_back(new PasswordForm(saved_match())); const url::Origin origin = url::Origin::Create(saved_match().url); passwords_data().OnRequestCredentials(std::move(local_credentials), origin); base::MockCallback<ManagePasswordsState::CredentialsCallback> callback; passwords_data().set_credentials_callback(callback.Get()); EXPECT_EQ(password_manager::ui::CREDENTIAL_REQUEST_STATE, passwords_data().state()); TestBlocklistedUpdates(); } TEST_F(ManagePasswordsStateTest, AutoSigninAddBlacklisted) { std::vector<std::unique_ptr<PasswordForm>> local_credentials; local_credentials.emplace_back(new PasswordForm(saved_match())); passwords_data().OnAutoSignin(std::move(local_credentials), url::Origin::Create(saved_match().url)); EXPECT_EQ(password_manager::ui::AUTO_SIGNIN_STATE, passwords_data().state()); TestBlocklistedUpdates(); } TEST_F(ManagePasswordsStateTest, AutomaticPasswordSaveAddBlacklisted) { std::vector<const PasswordForm*> best_matches; std::unique_ptr<MockPasswordFormManagerForUI> test_form_manager( CreateFormManager(&best_matches, {})); passwords_data().OnAutomaticPasswordSave(std::move(test_form_manager)); EXPECT_EQ(password_manager::ui::CONFIRMATION_STATE, passwords_data().state()); TestBlocklistedUpdates(); } TEST_F(ManagePasswordsStateTest, BackgroundAutofilledAddBlacklisted) { std::vector<const PasswordForm*> password_forms; password_forms.push_back(&saved_match()); passwords_data().OnPasswordAutofilled( password_forms, url::Origin::Create(password_forms.front()->url), nullptr); EXPECT_EQ(password_manager::ui::MANAGE_STATE, passwords_data().state()); TestBlocklistedUpdates(); } TEST_F(ManagePasswordsStateTest, PasswordUpdateAddBlacklisted) { std::vector<const PasswordForm*> best_matches = {&saved_match()}; std::unique_ptr<MockPasswordFormManagerForUI> test_form_manager( CreateFormManager(&best_matches, {})); passwords_data().OnUpdatePassword(std::move(test_form_manager)); EXPECT_EQ(password_manager::ui::PENDING_PASSWORD_UPDATE_STATE, passwords_data().state()); TestBlocklistedUpdates(); } TEST_F(ManagePasswordsStateTest, PasswordUpdateSubmitted) { std::vector<const PasswordForm*> best_matches = {&saved_match(), &psl_match()}; std::unique_ptr<MockPasswordFormManagerForUI> test_form_manager( CreateFormManager(&best_matches, {})); passwords_data().OnUpdatePassword(std::move(test_form_manager)); EXPECT_THAT(passwords_data().GetCurrentForms(), ElementsAre(Pointee(saved_match()))); EXPECT_EQ(password_manager::ui::PENDING_PASSWORD_UPDATE_STATE, passwords_data().state()); EXPECT_EQ(url::Origin::Create(GURL(kTestOrigin)), passwords_data().origin()); ASSERT_TRUE(passwords_data().form_manager()); TestAllUpdates(); } TEST_F(ManagePasswordsStateTest, AndroidPasswordUpdateSubmitted) { PasswordForm android_form; android_form.signon_realm = "android://dHJhc2g=@com.example.android/"; android_form.url = GURL(android_form.signon_realm); android_form.username_value = base::ASCIIToUTF16("username"); android_form.password_value = base::ASCIIToUTF16("old pass"); std::vector<const PasswordForm*> best_matches = {&android_form}; std::unique_ptr<MockPasswordFormManagerForUI> test_form_manager( CreateFormManager(&best_matches, {})); passwords_data().OnUpdatePassword(std::move(test_form_manager)); EXPECT_THAT(passwords_data().GetCurrentForms(), ElementsAre(Pointee(android_form))); EXPECT_EQ(password_manager::ui::PENDING_PASSWORD_UPDATE_STATE, passwords_data().state()); EXPECT_EQ(url::Origin::Create(GURL(kTestOrigin)), passwords_data().origin()); ASSERT_TRUE(passwords_data().form_manager()); TestAllUpdates(); } TEST_F(ManagePasswordsStateTest, PasswordUpdateSubmittedWithFederations) { std::vector<const PasswordForm*> best_matches = {&saved_match()}; std::unique_ptr<MockPasswordFormManagerForUI> test_form_manager( CreateFormManager(&best_matches, {&local_federated_form()})); passwords_data().OnUpdatePassword(std::move(test_form_manager)); EXPECT_THAT(passwords_data().GetCurrentForms(), UnorderedElementsAre(Pointee(saved_match()), Pointee(local_federated_form()))); } TEST_F(ManagePasswordsStateTest, ChooseCredentialLocal) { passwords_data().OnRequestCredentials( std::vector<std::unique_ptr<PasswordForm>>(), url::Origin::Create(saved_match().url)); base::MockCallback<ManagePasswordsState::CredentialsCallback> callback; passwords_data().set_credentials_callback(callback.Get()); EXPECT_CALL(callback, Run(&saved_match())); passwords_data().ChooseCredential(&saved_match()); } TEST_F(ManagePasswordsStateTest, ChooseCredentialEmpty) { passwords_data().OnRequestCredentials( std::vector<std::unique_ptr<PasswordForm>>(), url::Origin::Create(saved_match().url)); base::MockCallback<ManagePasswordsState::CredentialsCallback> callback; passwords_data().set_credentials_callback(callback.Get()); EXPECT_CALL(callback, Run(nullptr)); passwords_data().ChooseCredential(nullptr); } TEST_F(ManagePasswordsStateTest, ChooseCredentialLocalWithNonEmptyFederation) { passwords_data().OnRequestCredentials( std::vector<std::unique_ptr<PasswordForm>>(), url::Origin::Create(saved_match().url)); base::MockCallback<ManagePasswordsState::CredentialsCallback> callback; passwords_data().set_credentials_callback(callback.Get()); EXPECT_CALL(callback, Run(&local_federated_form())); passwords_data().ChooseCredential(&local_federated_form()); } TEST_F(ManagePasswordsStateTest, AutofillCausedByInternalFormManager) { struct OwningPasswordFormManagerForUI : public MockPasswordFormManagerForUI { GURL url; std::vector<const autofill::PasswordForm*> best_matches; std::vector<const autofill::PasswordForm*> federated_matches; const GURL& GetURL() const override { return url; } const std::vector<const autofill::PasswordForm*>& GetBestMatches() const override { return best_matches; } std::vector<const autofill::PasswordForm*> GetFederatedMatches() const override { return federated_matches; } }; auto test_form_manager = std::make_unique<OwningPasswordFormManagerForUI>(); auto* weak_manager = test_form_manager.get(); test_form_manager->url = saved_match().url; test_form_manager->best_matches = {&saved_match()}; test_form_manager->federated_matches = {&local_federated_form()}; passwords_data().OnPendingPassword(std::move(test_form_manager)); // Force autofill with the parameters coming from the object to be destroyed. passwords_data().OnPasswordAutofilled(weak_manager->best_matches, url::Origin::Create(weak_manager->url), &weak_manager->federated_matches); EXPECT_THAT(passwords_data().GetCurrentForms(), UnorderedElementsAre(Pointee(local_federated_form()), Pointee(saved_match()))); EXPECT_EQ(url::Origin::Create(saved_match().url), passwords_data().origin()); } TEST_F(ManagePasswordsStateTest, ProcessUnsyncedCredentialsWillBeDeleted) { std::vector<PasswordForm> unsynced_credentials(1); unsynced_credentials[0].username_value = ASCIIToUTF16("user"); unsynced_credentials[0].password_value = ASCIIToUTF16("password"); passwords_data().ProcessUnsyncedCredentialsWillBeDeleted( unsynced_credentials); EXPECT_EQ(passwords_data().state(), password_manager::ui::WILL_DELETE_UNSYNCED_ACCOUNT_PASSWORDS_STATE); EXPECT_EQ(passwords_data().unsynced_credentials(), unsynced_credentials); } TEST_F(ManagePasswordsStateTest, OnMovablePasswordSubmitted) { std::vector<const PasswordForm*> password_forms = {&saved_match()}; std::vector<const PasswordForm*> federated_matches = { &local_federated_form()}; passwords_data().OnPasswordMovable( CreateFormManager(&password_forms, federated_matches)); EXPECT_THAT( passwords_data().GetCurrentForms(), ElementsAre(Pointee(saved_match()), Pointee(local_federated_form()))); EXPECT_EQ(passwords_data().state(), password_manager::ui::CAN_MOVE_PASSWORD_TO_ACCOUNT_STATE); EXPECT_EQ(passwords_data().origin(), url::Origin::Create(GURL(kTestOrigin))); TestAllUpdates(); } } // namespace
42.448949
87
0.752396
mghgroup
43f310264c59322eaeed705c11dc3de70a8bcb0d
924
hpp
C++
include/Nazara/Utility/TriangleIterator.hpp
gogo2464/NazaraEngine
f1a00c36cb27d9f07d1b7db03313e0038d9a7d00
[ "BSD-3-Clause-Clear", "Apache-2.0", "MIT" ]
376
2015-01-09T03:14:48.000Z
2022-03-26T17:59:18.000Z
include/Nazara/Utility/TriangleIterator.hpp
gogo2464/NazaraEngine
f1a00c36cb27d9f07d1b7db03313e0038d9a7d00
[ "BSD-3-Clause-Clear", "Apache-2.0", "MIT" ]
252
2015-01-21T17:34:39.000Z
2022-03-20T16:15:50.000Z
include/Nazara/Utility/TriangleIterator.hpp
gogo2464/NazaraEngine
f1a00c36cb27d9f07d1b7db03313e0038d9a7d00
[ "BSD-3-Clause-Clear", "Apache-2.0", "MIT" ]
104
2015-01-18T11:03:41.000Z
2022-03-11T05:40:47.000Z
// Copyright (C) 2020 Jérôme Leclercq // This file is part of the "Nazara Engine - Utility module" // For conditions of distribution and use, see copyright notice in Config.hpp #pragma once #ifndef NAZARA_TRIANGLEITERATOR_HPP #define NAZARA_TRIANGLEITERATOR_HPP #include <Nazara/Prerequisites.hpp> #include <Nazara/Utility/Enums.hpp> #include <Nazara/Utility/IndexMapper.hpp> namespace Nz { class SubMesh; class NAZARA_UTILITY_API TriangleIterator { public: TriangleIterator(PrimitiveMode primitiveMode, const IndexBuffer& indexBuffer); TriangleIterator(const SubMesh& subMesh); ~TriangleIterator() = default; bool Advance(); UInt32 operator[](std::size_t i) const; void Unmap(); private: PrimitiveMode m_primitiveMode; UInt32 m_triangleIndices[3]; IndexMapper m_indexMapper; std::size_t m_currentIndex; std::size_t m_indexCount; }; } #endif // NAZARA_TRIANGLEITERATOR_HPP
22.536585
81
0.761905
gogo2464
43f37017bf19f7c47471858ce21d560b6ff281c5
3,728
cpp
C++
src/example/linear-algebra/Tines_EigenvalueSchur.cpp
sandialabs/Tines
4485ec9293ea55641020a6a683d64da66d02fea2
[ "BSD-2-Clause" ]
3
2021-02-10T03:18:49.000Z
2021-11-24T08:57:01.000Z
src/example/linear-algebra/Tines_EigenvalueSchur.cpp
sandialabs/Tines
4485ec9293ea55641020a6a683d64da66d02fea2
[ "BSD-2-Clause" ]
1
2021-02-24T22:21:05.000Z
2021-03-04T18:56:14.000Z
src/example/linear-algebra/Tines_EigenvalueSchur.cpp
sandialabs/Tines
4485ec9293ea55641020a6a683d64da66d02fea2
[ "BSD-2-Clause" ]
3
2021-02-18T18:47:37.000Z
2021-06-20T05:29:01.000Z
/*---------------------------------------------------------------------------------- Tines - Time Integrator, Newton and Eigen Solver - version 1.0 Copyright (2021) NTESS https://github.com/sandialabs/Tines Copyright 2021 National Technology & Engineering Solutions of Sandia, LLC (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S. Government retains certain rights in this software. This file is part of Tines. Tines is open-source software: you can redistribute it and/or modify it under the terms of BSD 2-Clause License (https://opensource.org/licenses/BSD-2-Clause). A copy of the license is also provided under the main directory Questions? Kyungjoo Kim <kyukim@sandia.gov>, or Oscar Diaz-Ibarra at <odiazib@sandia.gov>, or Cosmin Safta at <csafta@sandia.gov>, or Habib Najm at <hnnajm@sandia.gov> Sandia National Laboratories, New Mexico, USA ----------------------------------------------------------------------------------*/ #include "Tines.hpp" #include "Tines_TestUtils.hpp" int main(int argc, char **argv) { Kokkos::initialize(argc, argv); { printTestInfo info("EigenvalueSchur"); using ats = Tines::ats<real_type>; using Side = Tines::Side; using Trans = Tines::Trans; using Uplo = Tines::Uplo; using Diag = Tines::Diag; std::string filename; ordinal_type m = 12; Kokkos::View<real_type **, Kokkos::LayoutRight, host_device_type> A("A", m, m); if (argc == 2) { filename = argv[1]; Tines::readMatrix(filename, A); m = A.extent(0); } Kokkos::View<real_type **, Kokkos::LayoutRight, host_device_type> B("B", m, m); Kokkos::View<real_type **, Kokkos::LayoutRight, host_device_type> Q("Q", m, m); Kokkos::View<real_type **, Kokkos::LayoutRight, host_device_type> eig("eig", m, 2); Kokkos::View<ordinal_type *, Kokkos::LayoutRight, host_device_type> b("b", m); Kokkos::View<real_type *, Kokkos::LayoutRight, host_device_type> t("t", m); Kokkos::View<real_type *, Kokkos::LayoutRight, host_device_type> w("w", m); const real_type /* one(1), */ zero(0); const auto member = Tines::HostSerialTeamMember(); if (filename.empty()) { Kokkos::Random_XorShift64_Pool<host_device_type> random(13718); Kokkos::fill_random(A, random, real_type(1.0)); } bool is_valid(false); Tines::CheckNanInf::invoke(member, A, is_valid); std::cout << "Random matrix created " << (is_valid ? "is valid" : "is NOT valid") << "\n\n"; Tines::showMatrix("A (original)", A); Tines::Copy::invoke(member, A, B); Tines::Hessenberg::invoke(member, A, t, w); Tines::SetTriangularMatrix<Uplo::Lower>::invoke(member, 2, zero, A); Tines::showMatrix("A (after Hess)", A); /// A = Q T Q^H auto er = Kokkos::subview(eig, Kokkos::ALL(), 0); auto ei = Kokkos::subview(eig, Kokkos::ALL(), 1); const ordinal_type r_val = Tines::Schur::invoke(member, A, Q, er, ei, b); if (r_val == 0) { Tines::showMatrix("A (after Schur)", A); /// Compute Eigenvalues from Schur Tines::showMatrix("eig", eig); if (!filename.empty()) { std::string filenameEig = filename + ".eig"; printf("save file %s \n", filenameEig.c_str()); Tines::writeMatrix(filenameEig, eig); } } else { printf("Schur decomposition does not converge at a row %d\n", -r_val); } } Kokkos::finalize(); return 0; }
39.242105
84
0.572693
sandialabs
43f4b888eb585a1e6c8e170a34860d08500e8372
979
cc
C++
2016/1a/A.cc
golmansax/google-code-jam
4486db353b19a5d61512aee8d6350aca75a5ab56
[ "MIT" ]
null
null
null
2016/1a/A.cc
golmansax/google-code-jam
4486db353b19a5d61512aee8d6350aca75a5ab56
[ "MIT" ]
null
null
null
2016/1a/A.cc
golmansax/google-code-jam
4486db353b19a5d61512aee8d6350aca75a5ab56
[ "MIT" ]
null
null
null
#include <iostream> #include <cstdio> #include <cmath> #include <string> #include <deque> using namespace std; int main() { int n_cases; cin >> n_cases; for (int i_case = 0; i_case < n_cases; i_case++) { string s; cin >> s; deque<char> d; d.push_front(s[0]); for (int i = 1; i < s.size(); i++) { // Compare the two deques deque<char> front(d); front.push_front(s[i]); deque<char> back(d); back.push_back(s[i]); bool yay_front = true; for (int j = 0; j < front.size(); j++) { if ((int)back[j] > (int)front[j]) { yay_front = false; break; } else if ((int)back[j] < (int)front[j]) { yay_front = true; break; } } if (yay_front) { d.push_front(s[i]); } else { d.push_back(s[i]); } } printf("Case #%d: ", i_case + 1); for (int i = 0; i < d.size(); i++) { cout << d[i]; } cout << endl; } return 0; }
20.395833
52
0.489275
golmansax
43f514a3acda8fcf155cee5cbe556503c8fc131f
709
cpp
C++
Dynamic Programming/Minimizing Coins.cpp
DecSP/cses-downloader
12a8f37665a33f6f790bd2c355f84dea8a0e332c
[ "MIT" ]
2
2022-02-12T12:30:13.000Z
2022-02-12T13:59:20.000Z
Dynamic Programming/Minimizing Coins.cpp
DecSP/cses-downloader
12a8f37665a33f6f790bd2c355f84dea8a0e332c
[ "MIT" ]
2
2022-02-12T11:09:41.000Z
2022-02-12T11:55:49.000Z
Dynamic Programming/Minimizing Coins.cpp
DecSP/cses-downloader
12a8f37665a33f6f790bd2c355f84dea8a0e332c
[ "MIT" ]
null
null
null
# include <bits/stdc++.h> # define ll long long # define all(x) x.begin(), x.end() # define fastio ios_base::sync_with_stdio(false); cin.tie(NULL) # define ten6 (1e6+1.5) using namespace std; ll dp [(int)ten6]{0}; vector <int> c; ll solve (int x){ if (x==0) return 0; if (dp[x]) return dp[x]; ll re=ten6; for (auto v:c) { if (v>x) continue; re=min(re,1+solve(x-v)); } return dp[x]=re; } int main() { fastio; int n,x; cin>>n>>x; c.assign(n,0); for (auto &v:c){ cin>>v; dp[v]=1; } ll re=solve(x); if (re<(ll)(ten6)) cout<<solve(x)<<'\n'; else cout<<-1<<'\n'; return 0; }
19.694444
64
0.48519
DecSP
43f6e016e33e25ba99f7b91e68ce3337e2adcf36
5,225
hpp
C++
src/mlpack/methods/softmax_regression/softmax_regression_impl.hpp
vj-ug/Contribution-to-mlpack
0ddb5ed463861f459ff2829712bdc59ba9d810b0
[ "BSD-3-Clause" ]
null
null
null
src/mlpack/methods/softmax_regression/softmax_regression_impl.hpp
vj-ug/Contribution-to-mlpack
0ddb5ed463861f459ff2829712bdc59ba9d810b0
[ "BSD-3-Clause" ]
null
null
null
src/mlpack/methods/softmax_regression/softmax_regression_impl.hpp
vj-ug/Contribution-to-mlpack
0ddb5ed463861f459ff2829712bdc59ba9d810b0
[ "BSD-3-Clause" ]
null
null
null
/** * @file softmax_regression_impl.hpp * @author Siddharth Agrawal * * Implementation of softmax regression. */ #ifndef __MLPACK_METHODS_SOFTMAX_REGRESSION_SOFTMAX_REGRESSION_IMPL_HPP #define __MLPACK_METHODS_SOFTMAX_REGRESSION_SOFTMAX_REGRESSION_IMPL_HPP // In case it hasn't been included yet. #include "softmax_regression.hpp" namespace mlpack { namespace regression { template<template<typename> class OptimizerType> SoftmaxRegression<OptimizerType>:: SoftmaxRegression(const size_t inputSize, const size_t numClasses, const bool fitIntercept) : numClasses(numClasses), lambda(0.0001), fitIntercept(fitIntercept) { SoftmaxRegressionFunction::InitializeWeights(parameters, inputSize, numClasses, fitIntercept); } template<template<typename> class OptimizerType> SoftmaxRegression<OptimizerType>::SoftmaxRegression(const arma::mat& data, const arma::Row<size_t>& labels, const size_t numClasses, const double lambda, const bool fitIntercept) : numClasses(numClasses), lambda(lambda), fitIntercept(fitIntercept) { SoftmaxRegressionFunction regressor(data, labels, numClasses, lambda, fitIntercept); OptimizerType<SoftmaxRegressionFunction> optimizer(regressor); parameters = regressor.GetInitialPoint(); Train(optimizer); } template<template<typename> class OptimizerType> SoftmaxRegression<OptimizerType>::SoftmaxRegression( OptimizerType<SoftmaxRegressionFunction>& optimizer) : parameters(optimizer.Function().GetInitialPoint()), numClasses(optimizer.Function().NumClasses()), lambda(optimizer.Function().Lambda()), fitIntercept(optimizer.Function().FitIntercept()) { Train(optimizer); } template<template<typename> class OptimizerType> void SoftmaxRegression<OptimizerType>::Predict(const arma::mat& testData, arma::vec& predictions) { // Calculate the probabilities for each test input. arma::mat hypothesis, probabilities; if (fitIntercept) { // In order to add the intercept term, we should compute following matrix: // [1; data] = arma::join_cols(ones(1, data.n_cols), data) // hypothesis = arma::exp(parameters * [1; data]). // // Since the cost of join maybe high due to the copy of original data, // split the hypothesis computation to two components. hypothesis = arma::exp( arma::repmat(parameters.col(0), 1, testData.n_cols) + parameters.cols(1, parameters.n_cols - 1) * testData); } else { hypothesis = arma::exp(parameters * testData); } probabilities = hypothesis / arma::repmat(arma::sum(hypothesis, 0), numClasses, 1); // Prepare necessary data. predictions.zeros(testData.n_cols); double maxProbability = 0; // For each test input. for(size_t i = 0; i < testData.n_cols; i++) { // For each class. for(size_t j = 0; j < numClasses; j++) { // If a higher class probability is encountered, change prediction. if(probabilities(j, i) > maxProbability) { maxProbability = probabilities(j, i); predictions(i) = static_cast<double>(j); } } // Set maximum probability to zero for the next input. maxProbability = 0; } } template<template<typename> class OptimizerType> double SoftmaxRegression<OptimizerType>::ComputeAccuracy( const arma::mat& testData, const arma::Row<size_t>& labels) { arma::vec predictions; // Get predictions for the provided data. Predict(testData, predictions); // Increment count for every correctly predicted label. size_t count = 0; for (size_t i = 0; i < predictions.n_elem; i++) if (predictions(i) == labels(i)) count++; // Return percentage accuracy. return (count * 100.0) / predictions.n_elem; } template<template<typename> class OptimizerType> double SoftmaxRegression<OptimizerType>::Train( OptimizerType<SoftmaxRegressionFunction>& optimizer) { // Train the model. Timer::Start("softmax_regression_optimization"); const double out = optimizer.Optimize(parameters); Timer::Stop("softmax_regression_optimization"); Log::Info << "SoftmaxRegression::SoftmaxRegression(): final objective of " << "trained model is " << out << "." << std::endl; return out; } template<template<typename> class OptimizerType> double SoftmaxRegression<OptimizerType>::Train(const arma::mat& data, const arma::Row<size_t>& labels, const size_t numClasses) { SoftmaxRegressionFunction regressor(data, labels, numClasses, lambda, fitIntercept); OptimizerType<SoftmaxRegressionFunction> optimizer(regressor); return Train(optimizer); } } // namespace regression } // namespace mlpack #endif
32.861635
84
0.644211
vj-ug
43f7d4b830694638d7cee7d2dafd2b98a45abdac
136
cpp
C++
src/DynSLAM/InstRecLib/InstanceView.cpp
Frozenheart1998/DynSLAM
2de2c58c6eadbc037a19d393951b0f9d15191eab
[ "BSD-3-Clause" ]
530
2017-06-24T16:51:23.000Z
2022-03-30T23:13:03.000Z
src/DynSLAM/InstRecLib/InstanceView.cpp
38100514/DynSLAM
5fa4374872af63192e0c6b367a5577548ffd6b87
[ "BSD-3-Clause" ]
65
2017-06-14T11:43:20.000Z
2021-11-25T01:25:03.000Z
src/DynSLAM/InstRecLib/InstanceView.cpp
38100514/DynSLAM
5fa4374872af63192e0c6b367a5577548ffd6b87
[ "BSD-3-Clause" ]
166
2017-06-02T06:41:31.000Z
2022-03-08T11:10:02.000Z
#include "InstanceView.h" namespace instreclib { namespace reconstruction {} // namespace reconstruction } // namespace instreclib
17
56
0.764706
Frozenheart1998
43f975660133bcabcc35d58ed924ba166cb3332e
602
cc
C++
components/sync/base/invalidation_helper.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
components/sync/base/invalidation_helper.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
components/sync/base/invalidation_helper.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2021-01-05T23:43:46.000Z
2021-01-07T23:36:34.000Z
// Copyright 2014 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 "components/sync/base/invalidation_helper.h" #include <string> namespace syncer { TopicSet ModelTypeSetToTopicSet(ModelTypeSet model_types) { TopicSet topics; for (ModelType type : model_types) { Topic topic; if (!RealModelTypeToNotificationType(type, &topic)) { DLOG(WARNING) << "Invalid model type " << type; continue; } topics.insert(topic); } return topics; } } // namespace syncer
24.08
73
0.709302
sarang-apps
43fa4106cdfea0aa3735d711b5ccbbf1338bb963
7,546
cpp
C++
Jarvis_March/Jarvis_March/Visualization.cpp
bernhardrieder/Convex-Hull-Jarvis-March
95029708402086702d031730fad888ce25378b43
[ "Unlicense" ]
null
null
null
Jarvis_March/Jarvis_March/Visualization.cpp
bernhardrieder/Convex-Hull-Jarvis-March
95029708402086702d031730fad888ce25378b43
[ "Unlicense" ]
null
null
null
Jarvis_March/Jarvis_March/Visualization.cpp
bernhardrieder/Convex-Hull-Jarvis-March
95029708402086702d031730fad888ce25378b43
[ "Unlicense" ]
null
null
null
#include "Visualization.h" #include <SFML/Graphics/CircleShape.hpp> #include <SFML/Window/Event.hpp> #include <memory> #include <thread> #define GREEN sf::Color(0,200,0,255); Visualization::Visualization(const sf::Vector2f & preferedWindowSize, const sf::Vector2f & minCoord, const sf::Vector2f & maxCoord, const std::vector<sf::Vector2f>& vectorData, const float & pointSize, const long long& millisecondPause) : m_vectors(vectorData), m_pointSize(pointSize), m_millisecondPause(millisecondPause) { //get the adjusted windowsize sf::Vector2i windowSize = calculateWindowSize(preferedWindowSize, minCoord, maxCoord, .2f); m_renderWindow = new sf::RenderWindow(sf::VideoMode(windowSize.x,windowSize.y), "Convex Hull Comparison"); //add lines for the axis sf::VertexArray* horizontalAxis = new sf::VertexArray(sf::LinesStrip, 2); (*horizontalAxis)[0].position = sf::Vector2f(0, m_origin.y); (*horizontalAxis)[0].color = sf::Color(0, 0, 0, 100); (*horizontalAxis)[1].position = sf::Vector2f(static_cast<float>(windowSize.x), m_origin.y); (*horizontalAxis)[1].color = sf::Color(0, 0, 0, 100); sf::VertexArray* verticalAxis = new sf::VertexArray(*horizontalAxis); (*verticalAxis)[0].position = sf::Vector2f(m_origin.x, 0); (*verticalAxis)[1].position = sf::Vector2f(m_origin.x, static_cast<float>(windowSize.y)); m_drawableVectors.push_back(horizontalAxis); m_drawableVectors.push_back(verticalAxis); for (auto& pos : m_vectors) { //create a new circle for every point sf::CircleShape* shape = new sf::CircleShape(m_pointSize); //configure circle shape->setOrigin(shape->getRadius(), shape->getRadius()); shape->setPosition(pos*m_zoomFactor + m_origin); //setup circle visuals shape->setFillColor(sf::Color::Transparent); shape->setOutlineColor(sf::Color::Black); shape->setOutlineThickness(2.f); //store the circles in a list m_drawableVectors.push_back(shape); } //create and configure lines m_checkline = new sf::VertexArray(sf::LinesStrip, 2); (*m_checkline)[0].color = GREEN; (*m_checkline)[1].color = GREEN; m_candidateLine = new sf::VertexArray(sf::LinesStrip, 2); (*m_candidateLine)[0].color = sf::Color::Black; (*m_candidateLine)[1].color = sf::Color::Black; } Visualization::~Visualization() { for (int i = 0; i < m_drawableVectors.size(); ++i) { delete m_drawableVectors[i]; } delete m_renderWindow; delete m_candidateLine; delete m_checkline; delete m_currentAnchor; delete m_hull; } // Renders the hull with a red line from hullpoints[0], hullpoints[1] .. hullpoints[n] // and renders the last point of the hull with a blue circle void Visualization::RenderPartialHull(const std::vector<sf::Vector2f>& hullPoints) { //override the existing hull m_hull = new sf::VertexArray(sf::LinesStrip, hullPoints.size()); //save all positions for (unsigned int i = 0; i < hullPoints.size(); ++i) { (*m_hull)[i].position = hullPoints[i] * m_zoomFactor + m_origin; (*m_hull)[i].color = sf::Color::Red; } if (m_currentAnchor == nullptr) { //create new circle for the current anchor m_currentAnchor = new sf::CircleShape(m_pointSize); m_currentAnchor->setOrigin(m_currentAnchor->getRadius(), m_currentAnchor->getRadius()); m_currentAnchor->setFillColor(sf::Color::Blue); } //set the current anchor to the position of the last point m_currentAnchor->setPosition(*(hullPoints.end() - 1)*m_zoomFactor + m_origin); //reset the check- and candidate line (*m_checkline)[0].position = m_currentAnchor->getPosition(); (*m_checkline)[1].position = m_currentAnchor->getPosition(); (*m_candidateLine)[0].position = m_currentAnchor->getPosition(); (*m_candidateLine)[1].position = m_currentAnchor->getPosition(); draw(); } void Visualization::RenderCompleteHull(const std::vector<sf::Vector2f>& hullPoints) { //override the current hull m_hull = new sf::VertexArray(sf::LinesStrip, hullPoints.size()+1); //save all positions for (unsigned int i = 0; i < hullPoints.size(); ++i) { (*m_hull)[i].position = hullPoints[i] * m_zoomFactor + m_origin; (*m_hull)[i].color = sf::Color::Red; } //set last point to be connected to the first one (*m_hull)[hullPoints.size()].position = hullPoints[0] * m_zoomFactor + m_origin; (*m_hull)[hullPoints.size()].color = sf::Color::Red; //delete shapes and explicitly set them to nullpointer delete m_currentAnchor; m_currentAnchor = nullptr; delete m_checkline; m_checkline = nullptr; delete m_candidateLine; m_candidateLine = nullptr; draw(); } // Renders a green line between the current anchor and the checkPoint void Visualization::RenderCheckLine(const sf::Vector2f & checkPoint) { (*m_checkline)[0].position = m_currentAnchor->getPosition(); (*m_checkline)[1].position = checkPoint * m_zoomFactor + m_origin; draw(); } // Renders a black line between the current anchor and the candidatePoint void Visualization::RenderHullCandidateLine(const sf::Vector2f & candidatePoint) { (*m_checkline)[0].position = m_currentAnchor->getPosition(); (*m_checkline)[1].position = candidatePoint * m_zoomFactor + m_origin; (*m_candidateLine)[0].position = m_currentAnchor->getPosition(); (*m_candidateLine)[1].position = candidatePoint * m_zoomFactor + m_origin; draw(); } bool Visualization::ShouldClose() { handleEvents(); return !m_renderWindow->isOpen(); } // Calculates a proper windowsize to fit all the points into the prefered window size. // The window size will not exceed the prefered window size. // The border percent determins the distance to the outer edge of the window sf::Vector2i Visualization::calculateWindowSize(const sf::Vector2f & preferedWindowSize, const sf::Vector2f & minCoord, const sf::Vector2f & maxCoord, const float& borderPercent) { //create a vector2 that defines the whole area sf::Vector2f extends = maxCoord - minCoord; //calculate the aspectratio float aspectRatio = extends.x / extends.y; if (aspectRatio > 1) //take the wide side to calculate the necessary zoom m_zoomFactor = (preferedWindowSize.x) / extends.x; else //take the tall side... m_zoomFactor = (preferedWindowSize.y) / extends.y; //calculate the actual windowsize sf::Vector2i windowSize(static_cast<int>(extends.x*m_zoomFactor), static_cast<int>(extends.y*m_zoomFactor)); //add a border float borderFactor = 1 + borderPercent; sf::Vector2f border = extends*m_zoomFactor / borderFactor - extends*m_zoomFactor; //zoom a away to make room for the border m_zoomFactor /= borderFactor; //create a vector that defines the origin m_origin = -minCoord * m_zoomFactor; //move the origin half of the border size away m_origin -= border*0.5f; return windowSize; } // Renders all the points and lines void Visualization::draw() const { if (m_renderWindow->isOpen()) { handleEvents(); m_renderWindow->clear(sf::Color::White); for(int i = 0; i < m_drawableVectors.size(); ++i) m_renderWindow->draw(*m_drawableVectors[i]); if (m_currentAnchor != nullptr) m_renderWindow->draw(*m_currentAnchor); if (m_hull != nullptr) m_renderWindow->draw(*m_hull); if (m_checkline != nullptr) m_renderWindow->draw(*m_checkline); if (m_candidateLine != nullptr) m_renderWindow->draw(*m_candidateLine); m_renderWindow->display(); if(m_millisecondPause > 0) std::this_thread::sleep_for(std::chrono::milliseconds(m_millisecondPause)); } } // Handles the SFML Events void Visualization::handleEvents() const { sf::Event event; while (m_renderWindow->pollEvent(event)) { if (event.type == sf::Event::Closed) m_renderWindow->close(); } }
32.525862
121
0.733104
bernhardrieder
43fb1e9f1b9f4c1560d666d1986900bae6100f60
2,813
cpp
C++
scpp/src/SC_sim.cpp
Zentrik/SCpp
92176e57747ff5629a4ab3eeb3a86b3de21aaa48
[ "MIT" ]
110
2019-01-30T05:39:31.000Z
2022-02-22T11:31:27.000Z
scpp/src/SC_sim.cpp
Zentrik/SCpp
92176e57747ff5629a4ab3eeb3a86b3de21aaa48
[ "MIT" ]
6
2019-04-02T09:46:26.000Z
2021-07-16T13:03:16.000Z
scpp/src/SC_sim.cpp
Zentrik/SCpp
92176e57747ff5629a4ab3eeb3a86b3de21aaa48
[ "MIT" ]
32
2019-07-11T06:58:16.000Z
2022-03-30T08:05:48.000Z
#include <experimental/filesystem> #include "SCAlgorithm.hpp" #include "simulation.hpp" #include "timing.hpp" #include "commonFunctions.hpp" using fmt::format; using fmt::print; namespace fs = std::experimental::filesystem; fs::path getOutputPath() { return fs::path("..") / "output" / Model::getModelName(); } /** * @brief Simulates a trajectory with the SC controller. * * */ int main() { auto model = std::make_shared<Model>(); model->loadParameters(); scpp::SCAlgorithm solver(model); solver.initialize(); const double time_step = 0.05; const size_t max_steps = 100; trajectory_data_t td; Model::state_vector_v_t X_sim; Model::input_vector_v_t U_sim; Model::state_vector_t &x = model->p.x_init; double timer_run = tic(); size_t sim_step = 0; while (sim_step < max_steps) { print("\n{:*^{}}\n\n", format("<SIMULATION STEP {}>", sim_step), 60); const bool warm_start = sim_step > 0; solver.solve(warm_start); solver.getSolution(td); const Model::input_vector_t u0 = td.U.at(0); const bool first_order_hold = td.interpolatedInput(); const Model::input_vector_t u1 = scpp::interpolatedInput(td.U, time_step, td.t, first_order_hold); scpp::simulate(model, time_step, u0, u1, x); X_sim.push_back(x); U_sim.push_back(u0); bool reached_end = (x - model->p.x_final).norm() < 0.02 or td.t < 0.25; if (reached_end) { break; } sim_step++; } print("\n"); print("{:<{}}{:.2f}ms\n", fmt::format("Time, {} steps:", sim_step), 50, toc(timer_run)); const double freq = double(sim_step) / (0.001 * toc(timer_run)); print("{:<{}}{:.2f}Hz\n", "Average frequency:", 50, freq); print("\n"); // write solution to files double timer = tic(); fs::path outputPath = getOutputPath() / "SC_sim" / scpp::getTimeString() / std::to_string(0); if (not fs::exists(outputPath) and not fs::create_directories(outputPath)) { throw std::runtime_error("Could not create output directory!"); } const Eigen::IOFormat CSVFormat(Eigen::StreamPrecision, Eigen::DontAlignCols, ", ", "\n"); { std::ofstream f(outputPath / "X.txt"); for (auto &state : X_sim) { f << state.transpose().format(CSVFormat) << "\n"; } } { std::ofstream f(outputPath / "U.txt"); for (auto &input : U_sim) { f << input.transpose().format(CSVFormat) << "\n"; } } { std::ofstream f(outputPath / "t.txt"); f << sim_step * time_step; } print("{:<{}}{:.2f}ms\n", "Time, solution files:", 50, toc(timer)); }
27.048077
106
0.570921
Zentrik
43fba0f41939cc626830e4a083c7fd8e648316df
589
cpp
C++
tests/example.cpp
Bjoe/tinyrefl
b7296be55e75024289fe11e2d696d4227fc09f0b
[ "MIT" ]
241
2018-05-10T14:27:04.000Z
2022-03-26T10:38:04.000Z
tests/example.cpp
Bjoe/tinyrefl
b7296be55e75024289fe11e2d696d4227fc09f0b
[ "MIT" ]
1
2019-08-03T17:40:28.000Z
2019-08-20T13:08:54.000Z
tests/example.cpp
Bjoe/tinyrefl
b7296be55e75024289fe11e2d696d4227fc09f0b
[ "MIT" ]
15
2018-05-10T17:34:24.000Z
2022-01-20T23:02:44.000Z
#include "example.hpp" #include <tinyrefl/api.hpp> #include "example.hpp.tinyrefl" namespace my_namespace { std::ostream& operator<<(std::ostream& os, const MyClass::Enum value) { switch(value) { case MyClass::Enum::A: return os << "A"; case MyClass::Enum::B: return os << "B"; case MyClass::Enum::C: return os << "C"; case MyClass::Enum::D: return os << "D"; } return os << "WTF"; } bool operator==(const MyClass& lhs, const MyClass& rhs) { return tinyrefl::memberwise_equal(lhs, rhs); } } // namespace my_namespace
19.633333
69
0.604414
Bjoe
43fd8c38177b2f223ea6b1d552b4d31d3f94c918
7,001
cxx
C++
Widgets/vtkAngleRepresentation.cxx
garyc618/GitTagBug
0b1cdbf5a6f6b9b23fa03ff1d9f4a84953831864
[ "BSD-3-Clause" ]
1
2019-05-31T06:45:40.000Z
2019-05-31T06:45:40.000Z
Widgets/vtkAngleRepresentation.cxx
garyc618/GitTagBug
0b1cdbf5a6f6b9b23fa03ff1d9f4a84953831864
[ "BSD-3-Clause" ]
null
null
null
Widgets/vtkAngleRepresentation.cxx
garyc618/GitTagBug
0b1cdbf5a6f6b9b23fa03ff1d9f4a84953831864
[ "BSD-3-Clause" ]
null
null
null
/*========================================================================= Program: Visualization Toolkit Module: vtkAngleRepresentation.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. =========================================================================*/ #include "vtkAngleRepresentation.h" #include "vtkHandleRepresentation.h" #include "vtkActor2D.h" #include "vtkPolyDataMapper2D.h" #include "vtkProperty2D.h" #include "vtkCoordinate.h" #include "vtkRenderer.h" #include "vtkObjectFactory.h" #include "vtkInteractorObserver.h" #include "vtkMath.h" #include "vtkTextProperty.h" #include "vtkWindow.h" vtkCxxRevisionMacro(vtkAngleRepresentation, "1.7"); vtkCxxSetObjectMacro(vtkAngleRepresentation,HandleRepresentation,vtkHandleRepresentation); //---------------------------------------------------------------------- vtkAngleRepresentation::vtkAngleRepresentation() { this->HandleRepresentation = NULL; this->Point1Representation = NULL; this->CenterRepresentation = NULL; this->Point2Representation = NULL; this->Tolerance = 5; this->Placed = 0; this->Ray1Visibility = 1; this->Ray2Visibility = 1; this->ArcVisibility = 1; this->LabelFormat = new char[8]; sprintf(this->LabelFormat,"%s","%-#6.3g"); } //---------------------------------------------------------------------- vtkAngleRepresentation::~vtkAngleRepresentation() { if ( this->HandleRepresentation ) { this->HandleRepresentation->Delete(); } if ( this->Point1Representation ) { this->Point1Representation->Delete(); } if ( this->CenterRepresentation ) { this->CenterRepresentation->Delete(); } if ( this->Point2Representation ) { this->Point2Representation->Delete(); } if (this->LabelFormat) { delete [] this->LabelFormat; this->LabelFormat = NULL; } } //---------------------------------------------------------------------- void vtkAngleRepresentation::InstantiateHandleRepresentation() { if ( ! this->Point1Representation ) { this->Point1Representation = this->HandleRepresentation->NewInstance(); this->Point1Representation->ShallowCopy(this->HandleRepresentation); } if ( ! this->CenterRepresentation ) { this->CenterRepresentation = this->HandleRepresentation->NewInstance(); this->CenterRepresentation->ShallowCopy(this->HandleRepresentation); } if ( ! this->Point2Representation ) { this->Point2Representation = this->HandleRepresentation->NewInstance(); this->Point2Representation->ShallowCopy(this->HandleRepresentation); } } //---------------------------------------------------------------------- int vtkAngleRepresentation::ComputeInteractionState(int X, int Y, int vtkNotUsed(modify)) { // See if we are near one of the end points or outside double pos1[3], pos2[3], center[3]; this->GetPoint1DisplayPosition(pos1); this->GetCenterDisplayPosition(center); this->GetPoint2DisplayPosition(pos2); double p1[3], p2[3], c[3], xyz[3]; xyz[0] = static_cast<double>(X); xyz[1] = static_cast<double>(Y); p1[0] = static_cast<double>(pos1[0]); p1[1] = static_cast<double>(pos1[1]); c[0] = static_cast<double>(center[0]); c[1] = static_cast<double>(center[1]); p2[0] = static_cast<double>(pos2[0]); p2[1] = static_cast<double>(pos2[1]); xyz[2] = p1[2] = p2[2] = c[2] = 0.0; double tol2 = this->Tolerance*this->Tolerance; if ( vtkMath::Distance2BetweenPoints(xyz,p1) <= tol2 ) { this->InteractionState = vtkAngleRepresentation::NearP1; } else if ( vtkMath::Distance2BetweenPoints(xyz,c) <= tol2 ) { this->InteractionState = vtkAngleRepresentation::NearCenter; } else if ( vtkMath::Distance2BetweenPoints(xyz,p2) <= tol2 ) { this->InteractionState = vtkAngleRepresentation::NearP2; } else { this->InteractionState = vtkAngleRepresentation::Outside; } return this->InteractionState; } //---------------------------------------------------------------------- void vtkAngleRepresentation::StartWidgetInteraction(double e[2]) { double pos[3]; pos[0] = e[0]; pos[1] = e[1]; pos[2] = 0.0; this->SetPoint1DisplayPosition(pos); this->SetCenterDisplayPosition(pos); this->SetPoint2DisplayPosition(pos); } //---------------------------------------------------------------------- void vtkAngleRepresentation::CenterWidgetInteraction(double e[2]) { double pos[3]; pos[0] = e[0]; pos[1] = e[1]; pos[2] = 0.0; this->SetCenterDisplayPosition(pos); this->SetPoint2DisplayPosition(pos); } //---------------------------------------------------------------------- void vtkAngleRepresentation::WidgetInteraction(double e[2]) { double pos[3]; pos[0] = e[0]; pos[1] = e[1]; pos[2] = 0.0; this->SetPoint2DisplayPosition(pos); } //---------------------------------------------------------------------- void vtkAngleRepresentation::BuildRepresentation() { // We don't worry about mtime 'cause the subclass deals with that // Make sure the handles are up to date this->Point1Representation->BuildRepresentation(); this->CenterRepresentation->BuildRepresentation(); this->Point2Representation->BuildRepresentation(); } //---------------------------------------------------------------------- void vtkAngleRepresentation::PrintSelf(ostream& os, vtkIndent indent) { //Superclass typedef defined in vtkTypeMacro() found in vtkSetGet.h this->Superclass::PrintSelf(os,indent); os << indent << "Angle: " << this->GetAngle() << "\n"; os << indent << "Tolerance: " << this->Tolerance <<"\n"; os << indent << "Ray1 Visibility: " << (this->Ray1Visibility ? "On\n" : "Off\n"); os << indent << "Ray2 Visibility: " << (this->Ray2Visibility ? "On\n" : "Off\n"); os << indent << "Arc Visibility: " << (this->ArcVisibility ? "On\n" : "Off\n"); os << indent << "Handle Representation: " << this->HandleRepresentation << "\n"; os << indent << "Label Format: "; if ( this->LabelFormat ) { os << this->LabelFormat << "\n"; } else { os << "(none)\n"; } os << indent << "Point1 Representation: "; if ( this->Point1Representation ) { this->Point1Representation->PrintSelf(os,indent.GetNextIndent()); } else { os << "(none)\n"; } os << indent << "Center Representation: "; if ( this->CenterRepresentation ) { this->CenterRepresentation->PrintSelf(os,indent.GetNextIndent()); } else { os << "(none)\n"; } os << indent << "Point2 Representation: "; if ( this->Point2Representation ) { this->Point2Representation->PrintSelf(os,indent.GetNextIndent()); } else { os << "(none)\n"; } }
29.292887
90
0.599629
garyc618
43fdd79e9ea886183de0f17fab9ee3e91df6caa0
3,152
cpp
C++
v4/v4.cpp
dudakovict/ntp-demonstrature
fa759fbc3ea3aff3ea371622d91219dd29161ddc
[ "MIT" ]
null
null
null
v4/v4.cpp
dudakovict/ntp-demonstrature
fa759fbc3ea3aff3ea371622d91219dd29161ddc
[ "MIT" ]
null
null
null
v4/v4.cpp
dudakovict/ntp-demonstrature
fa759fbc3ea3aff3ea371622d91219dd29161ddc
[ "MIT" ]
null
null
null
#include <iostream> #include <list> #include <fstream> using namespace std; class Stavka { private: char naziv[30]; int kolicina; public: void ispis(); Stavka unos(); void promjeni(string, list<Stavka> &); }; void Stavka::ispis() { cout << "\nNaziv proizvoda: " << naziv << "\nKolicina proizvoda: " << kolicina << endl; } Stavka Stavka::unos() { Stavka s; cin.ignore(); cout << "\nNaziv proizvoda: "; cin.getline(s.naziv, 30); cout << "Kolicina proizvoda: "; cin >> s.kolicina; return s; } void Stavka::promjeni(string naziv, list<Stavka> &stavke) { for (list<Stavka>::iterator it = stavke.begin(); it != stavke.end(); it++) { if (naziv == it->naziv) { cin.ignore(); cout << "\nNovi naziv proizvoda: "; cin.getline(it->naziv, 32); cout << "Nova kolicina proizvoda: "; cin >> it->kolicina; break; } } } void spremi_datoteku(ofstream &outfile, list<Stavka> &stavke) { outfile.open("stavke.dat", ios::binary | ios::out | ios::app); if (!outfile) return; for (list<Stavka>::iterator it = stavke.begin(); it != stavke.end(); it++) { outfile.write((char *)&*it, sizeof(*it)); } outfile.close(); cout << "\nSpremljeno u datoteku!" << endl; } list<Stavka> ucitaj_datoteku(ifstream &infile) { infile.open("stavke.dat", ios::binary | ios::in); if (!infile) return list<Stavka>(); list<Stavka> stavke; while (true) { Stavka s; infile.read((char *)&s, sizeof(s)); if (infile.eof()) break; stavke.push_back(s); } infile.close(); cout << "\nUcitano iz datoteke!" << endl; return stavke; } int main() { int izbor; list<Stavka> stavke; Stavka s; ofstream outfile; ifstream infile; do { cout << "1. Ispis svih stavki\n2. Dodavanje nove stavke\n3. Promjena stavke\n4. Spremanje liste u datoteku\n5. Upis liste iz datoteke\n6. Izlaz" << endl; cout << "\nVas izbor: "; cin >> izbor; switch (izbor) { case 1: { for (list<Stavka>::iterator it = stavke.begin(); it != stavke.end(); it++) { it->ispis(); } break; } case 2: { stavke.push_back(s.unos()); break; } case 3: { string naziv; cout << "\nNaziv proizvoda za promjenu: "; cin >> naziv; s.promjeni(naziv, stavke); break; } case 4: { spremi_datoteku(outfile, stavke); break; } case 5: { stavke = ucitaj_datoteku(infile); break; } case 6: { cout << "\nIzlaz iz programa" << endl; break; } default: { cout << "\nKrivi unos!\n" << endl; break; } } cout << endl; } while (izbor != 6); return 0; }
21.013333
161
0.485723
dudakovict
43ffa6b343a762c6a7bac26de0ff4ba1f64aef6f
2,841
cpp
C++
codes/mock/2/1.cpp
chessbot108/solved-problems
0945be829a8ea9f0d5896c89331460d70d076691
[ "MIT" ]
null
null
null
codes/mock/2/1.cpp
chessbot108/solved-problems
0945be829a8ea9f0d5896c89331460d70d076691
[ "MIT" ]
null
null
null
codes/mock/2/1.cpp
chessbot108/solved-problems
0945be829a8ea9f0d5896c89331460d70d076691
[ "MIT" ]
null
null
null
//misaka and rin will carry me to cm #include <iostream> #include <cstdio> #include <cstring> #include <utility> #include <cassert> #include <algorithm> #include <vector> #include <array> #include <tuple> #define ll long long #define lb long double #define sz(vec) ((int)(vec.size())) #define all(x) x.begin(), x.end() const lb eps = 1e-9; const ll mod = 1e9 + 7, ll_max = 1e18; //const ll mod = (1 << (23)) * 119 +1; const int MX = 2e5 +10, int_max = 0x3f3f3f3f; using namespace std; int pad[MX], happy[MX], sad[MX], par[MX], b1[MX], b2[MX], sub[MX], wp[MX]; int cnt[MX][30]; vector<pair<int, int>> adj[MX]; void dfs(int u, int p){ par[u] = p; sub[u] = 1; for(auto &e : adj[u]){ if(e.first != p){ wp[e.first] = e.second; dfs(e.first, u); sub[u] += sub[e.first]; } } } void gans(int u, int p){ int tsad = 0; for(auto &e : adj[u]){ int v = e.first; if(v == p) continue; gans(v, u); tsad += (sad[v] > 0); } //int ans = 0; for(auto& e : adj[u]){ int v = e.first, w = e.second; if(v == p) continue; //under what conditions do we ignore the subtree of v? //tsad == 1 && sad[v] == 0 //b1, b2 are defined and v != b1, v != b2 //tsad > 1 sad[u] += sad[v]; if(tsad > 0 && sad[v] == 0){ //someone else is sad }else if(b2[u] != 0 && v != b1[u] && v != b2[u]){ //u itself just screwed v over }else{ happy[u] += happy[v]; } } if(tsad == 0 && b2[u] == 0) happy[u]++; //counting node u if(tsad > 1) happy[u] = 0; //sad[u] += (b2[u] > 0); } void cl(int n){ for(int i = 0; i<=n; i++){ adj[i].clear(); b1[i] = b2[i] = par[i] = happy[i] = sad[i] = sub[i] = wp[i] = 0; for(int j = 0; j<26; j++) cnt[i][j] = 0; } } int solve(){ //yes int n; cin >> n; cl(n); for(int i = 0; i<n-1; i++){ int a, b; char c; cin >> a >> b >> c; int d = c - 'a'; adj[a].push_back(make_pair(b, d)); b[adj].push_back(make_pair(a, d)); cnt[a][d]++; cnt[b][d]++; } dfs(1, 0); for(int u = 1; u<=n; u++){ int th = 0, tw = 0; for(int c = 0; c<26; c++){ th += (cnt[u][c] >= 3); tw += (cnt[u][c] >= 2); } if(th >= 1) return 0; //everyone is sad if(tw >= 2) return 0; } //if(tw >=2) return 0; for(int u = 1; u<=n; u++){ for(int c = 0; c<26; c++){ int t = cnt[u][c]; if(t >=2){ //cout << u << "\n"; for(auto& e : adj[u]){ if(e.second == c){ if(b1[u]) b2[u] = e.first; else b1[u] = e.first; } } if(!(b1[u] == par[u] || b2[u] == par[u])) sad[u]++; } } } //for(int i = 1; i<=n; i++){ //cout << i << " " << sad[i] << " " << b1[i] << " " << b2[i] << "\n"; //} gans(1, 0); //for(int i = 1; i<=n; i++){ //cout << i << " " << sad[i] << " " << happy[i] << "\n"; //} return happy[1]; } int main(){ cin.tie(0) -> sync_with_stdio(0); int T; cin >> T; while(T--){ cout << solve() << "\n"; } return 0; }
20.007042
74
0.481521
chessbot108
a100c20b04e4249b41eda902d9438b3dd13f0bbf
1,626
cpp
C++
libraries/mail/message.cpp
Curve25519/bitsharesx
949f878317c06e3672be1543e6f566472dbb0a9f
[ "Unlicense" ]
1
2021-02-12T04:06:15.000Z
2021-02-12T04:06:15.000Z
libraries/mail/message.cpp
Curve25519/bitsharesx
949f878317c06e3672be1543e6f566472dbb0a9f
[ "Unlicense" ]
null
null
null
libraries/mail/message.cpp
Curve25519/bitsharesx
949f878317c06e3672be1543e6f566472dbb0a9f
[ "Unlicense" ]
null
null
null
#include <bts/mail/message.hpp> #include <fc/crypto/aes.hpp> namespace bts { namespace mail { const message_type signed_email_message::type = email; const message_type transaction_notice_message::type = transaction_notice; digest_type email_message::digest()const { fc::sha256::encoder enc; fc::raw::pack( enc, *this ); return enc.result(); } void signed_email_message::sign( const fc::ecc::private_key& from_key ) { try { from_signature = from_key.sign_compact( digest() ); } FC_CAPTURE_AND_RETHROW() } fc::ecc::public_key signed_email_message::from()const { try { return fc::ecc::public_key( from_signature, digest() ); } FC_CAPTURE_AND_RETHROW() } message_id_type message::id()const { fc::ripemd160::encoder enc; fc::raw::pack( enc, *this ); return enc.result(); } encrypted_message message::encrypt( const fc::ecc::private_key& onetimekey, const fc::ecc::public_key& receiver_public_key )const { auto shared_secret = onetimekey.get_shared_secret( receiver_public_key ); encrypted_message result; result.onetimekey = onetimekey.get_public_key(); result.data = fc::aes_encrypt( shared_secret, fc::raw::pack( *this ) ); return result; } message encrypted_message::decrypt( const fc::ecc::private_key& e )const { auto shared_secret = e.get_shared_secret(onetimekey); auto decrypted_data = fc::aes_decrypt( shared_secret, data ); return fc::raw::unpack<message>( decrypted_data ); }; } } // bts::mail
32.52
93
0.656212
Curve25519
a1017b6b21e380c6ff403b175343bb2bb3e88b93
6,556
cpp
C++
iceoryx_posh/test/moduletests/test_popo_client_options.cpp
neilisaac/iceoryx
7faa8951ecc9f41a421ef888013f120e8f9e7fa5
[ "Apache-2.0" ]
null
null
null
iceoryx_posh/test/moduletests/test_popo_client_options.cpp
neilisaac/iceoryx
7faa8951ecc9f41a421ef888013f120e8f9e7fa5
[ "Apache-2.0" ]
null
null
null
iceoryx_posh/test/moduletests/test_popo_client_options.cpp
neilisaac/iceoryx
7faa8951ecc9f41a421ef888013f120e8f9e7fa5
[ "Apache-2.0" ]
null
null
null
// Copyright (c) 2021 by Apex.AI Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // SPDX-License-Identifier: Apache-2.0 #include "iceoryx_posh/popo/client_options.hpp" #include "test.hpp" namespace { using namespace ::testing; TEST(ClientOptions_test, SerializationRoundTripIsSuccessful) { ::testing::Test::RecordProperty("TEST_ID", "1d803ab0-a657-4a84-b261-ec289a7353e6"); iox::popo::ClientOptions defaultOptions; iox::popo::ClientOptions testOptions; testOptions.responseQueueCapacity = 42; testOptions.nodeName = "hypnotoad"; testOptions.connectOnCreate = false; testOptions.responseQueueFullPolicy = iox::popo::QueueFullPolicy::BLOCK_PRODUCER; testOptions.serverTooSlowPolicy = iox::popo::ConsumerTooSlowPolicy::WAIT_FOR_CONSUMER; iox::popo::ClientOptions::deserialize(testOptions.serialize()) .and_then([&](auto& roundTripOptions) { EXPECT_THAT(roundTripOptions.responseQueueCapacity, Ne(defaultOptions.responseQueueCapacity)); EXPECT_THAT(roundTripOptions.responseQueueCapacity, Eq(testOptions.responseQueueCapacity)); EXPECT_THAT(roundTripOptions.nodeName, Ne(defaultOptions.nodeName)); EXPECT_THAT(roundTripOptions.nodeName, Eq(testOptions.nodeName)); EXPECT_THAT(roundTripOptions.connectOnCreate, Ne(defaultOptions.connectOnCreate)); EXPECT_THAT(roundTripOptions.connectOnCreate, Eq(testOptions.connectOnCreate)); EXPECT_THAT(roundTripOptions.responseQueueFullPolicy, Ne(defaultOptions.responseQueueFullPolicy)); EXPECT_THAT(roundTripOptions.responseQueueFullPolicy, Eq(testOptions.responseQueueFullPolicy)); EXPECT_THAT(roundTripOptions.serverTooSlowPolicy, Ne(defaultOptions.serverTooSlowPolicy)); EXPECT_THAT(roundTripOptions.serverTooSlowPolicy, Eq(testOptions.serverTooSlowPolicy)); }) .or_else([&](auto&) { constexpr bool DESERIALZATION_ERROR_OCCURED{true}; EXPECT_FALSE(DESERIALZATION_ERROR_OCCURED); }); } TEST(ClientOptions_test, DeserializingBogusDataFails) { ::testing::Test::RecordProperty("TEST_ID", "eb7341fd-f216-4422-8065-cbbadefd567b"); const auto bogusSerialization = iox::cxx::Serialization::create("hypnotoad", "brain slug", "rock star"); iox::popo::ClientOptions::deserialize(bogusSerialization) .and_then([&](auto&) { constexpr bool DESERIALZATION_SUCCESSFUL{true}; EXPECT_FALSE(DESERIALZATION_SUCCESSFUL); }) .or_else([&](auto&) { constexpr bool DESERIALZATION_ERROR_OCCURED{true}; EXPECT_TRUE(DESERIALZATION_ERROR_OCCURED); }); } using QueueFullPolicyUT = std::underlying_type_t<iox::popo::QueueFullPolicy>; using ConsumerTooSlowPolicyUT = std::underlying_type_t<iox::popo::ConsumerTooSlowPolicy>; iox::cxx::Serialization enumSerialization(QueueFullPolicyUT responseQueueFullPolicy, ConsumerTooSlowPolicyUT serverTooSlowPolicy) { constexpr uint64_t RESPONSE_QUEUE_CAPACITY{42U}; const iox::NodeName_t NODE_NAME{"harr-harr"}; constexpr bool CONNECT_ON_CREATE{true}; return iox::cxx::Serialization::create( RESPONSE_QUEUE_CAPACITY, NODE_NAME, CONNECT_ON_CREATE, responseQueueFullPolicy, serverTooSlowPolicy); } TEST(ClientOptions_test, DeserializingValidResponseQueueFullAndServerTooSlowPolicyIsSuccessful) { ::testing::Test::RecordProperty("TEST_ID", "877ad373-eb51-4613-9b68-b93baa4c6eae"); constexpr QueueFullPolicyUT RESPONSE_QUEUE_FULL_POLICY{ static_cast<QueueFullPolicyUT>(iox::popo::QueueFullPolicy::BLOCK_PRODUCER)}; constexpr ConsumerTooSlowPolicyUT SERVER_TOO_SLOW_POLICY{ static_cast<ConsumerTooSlowPolicyUT>(iox::popo::ConsumerTooSlowPolicy::WAIT_FOR_CONSUMER)}; const auto serialized = enumSerialization(RESPONSE_QUEUE_FULL_POLICY, SERVER_TOO_SLOW_POLICY); iox::popo::ClientOptions::deserialize(serialized) .and_then([&](auto&) { constexpr bool DESERIALZATION_SUCCESSFUL{true}; EXPECT_TRUE(DESERIALZATION_SUCCESSFUL); }) .or_else([&](auto&) { constexpr bool DESERIALZATION_ERROR_OCCURED{true}; EXPECT_FALSE(DESERIALZATION_ERROR_OCCURED); }); } TEST(ClientOptions_test, DeserializingInvalidResponseQueueFullPolicyFails) { ::testing::Test::RecordProperty("TEST_ID", "a5495324-67d0-4f0c-b979-f93d4b68adc5"); constexpr QueueFullPolicyUT RESPONSE_QUEUE_FULL_POLICY{111}; constexpr ConsumerTooSlowPolicyUT SERVER_TOO_SLOW_POLICY{ static_cast<ConsumerTooSlowPolicyUT>(iox::popo::ConsumerTooSlowPolicy::DISCARD_OLDEST_DATA)}; const auto serialized = enumSerialization(RESPONSE_QUEUE_FULL_POLICY, SERVER_TOO_SLOW_POLICY); iox::popo::ClientOptions::deserialize(serialized) .and_then([&](auto&) { constexpr bool DESERIALZATION_SUCCESSFUL{true}; EXPECT_FALSE(DESERIALZATION_SUCCESSFUL); }) .or_else([&](auto&) { constexpr bool DESERIALZATION_ERROR_OCCURED{true}; EXPECT_TRUE(DESERIALZATION_ERROR_OCCURED); }); } TEST(ClientOptions_test, DeserializingInvalidServerTooSlowPolicyFails) { ::testing::Test::RecordProperty("TEST_ID", "6485377c-9a75-4aba-8045-8b129aa1c529"); constexpr QueueFullPolicyUT RESPONSE_QUEUE_FULL_POLICY{ static_cast<QueueFullPolicyUT>(iox::popo::QueueFullPolicy::BLOCK_PRODUCER)}; constexpr ConsumerTooSlowPolicyUT SERVER_TOO_SLOW_POLICY{111}; const auto serialized = enumSerialization(RESPONSE_QUEUE_FULL_POLICY, SERVER_TOO_SLOW_POLICY); iox::popo::ClientOptions::deserialize(serialized) .and_then([&](auto&) { constexpr bool DESERIALZATION_SUCCESSFUL{true}; EXPECT_FALSE(DESERIALZATION_SUCCESSFUL); }) .or_else([&](auto&) { constexpr bool DESERIALZATION_ERROR_OCCURED{true}; EXPECT_TRUE(DESERIALZATION_ERROR_OCCURED); }); } } // namespace
44.598639
110
0.735052
neilisaac
a102e46db578d0c7b37c8a537ca5dcd925383cd9
2,672
cpp
C++
src/client/client.cpp
psu-powerlab/IEEE_Server-Client
084086f1dbda134ba365d96e651540b6b031f737
[ "BSD-3-Clause" ]
null
null
null
src/client/client.cpp
psu-powerlab/IEEE_Server-Client
084086f1dbda134ba365d96e651540b6b031f737
[ "BSD-3-Clause" ]
null
null
null
src/client/client.cpp
psu-powerlab/IEEE_Server-Client
084086f1dbda134ba365d96e651540b6b031f737
[ "BSD-3-Clause" ]
1
2021-03-06T20:42:41.000Z
2021-03-06T20:42:41.000Z
#include "client.h" #include <iostream> namespace bb = boost::beast; // alias to make things easier to read Client::Client() : host_("0.0.0.0"), port_("80"), resolver_(ioc_), stream_(ioc_) { std::cout << "[HTTP CLIENT]\n... constructed" << std::endl; } Client* Client::Instance() { // c++11 will only run this once static Client* instance = new Client (); return instance; } void Client::SetHost(std::string& host) { host_ = host; } void Client::SetPort(std::string& port) { port_ = port; } bb::http::response <bb::http::string_body> Client::Get(const std::string& target, const std::string& query) { Client::Initialize(); std::string href = target + query; bb::http::request <bb::http::string_body> req { bb::http::verb::get, href, 11 }; req.set(bb::http::field::host, host_); req.prepare_payload(); std::cout << req << std::endl; return Client::Send (req); } bb::http::response <bb::http::string_body> Client::Post(const std::string& target, const std::string& resource) { Client::Initialize(); bb::http::request <bb::http::string_body> req { bb::http::verb::post, target, 11 }; req.set(bb::http::field::host, host_); req.body() = resource; req.prepare_payload(); return Client::Send (req); } bb::http::response <bb::http::string_body> Client::Put(const std::string& target, const std::string& resource) { Client::Initialize(); bb::http::request <bb::http::string_body> req { bb::http::verb::put, target, 11 }; req.set(bb::http::field::host, host_); req.body() = resource; req.prepare_payload(); return Client::Send (req); } bb::http::response <bb::http::string_body> Client::Delete(const std::string& target) { Client::Initialize(); bb::http::request <bb::http::string_body> req { bb::http::verb::delete_, target, 11 }; req.set(bb::http::field::host, host_); req.prepare_payload(); return Client::Send (req); } void Client::Initialize() { // Look up the domain name auto const results = resolver_.resolve(host_, port_); // Make the connection on the IP address we get from a lookup stream_.connect(results); } bb::http::response <bb::http::string_body> Client::Send(bb::http::request<bb::http::string_body>& req) { // Send the HTTP request to the remote host bb::http::write(stream_, req); // This buffer is used for reading and must be persisted bb::flat_buffer buffer; // Declare a container to hold the response bb::http::response<bb::http::string_body> res; // Receive the HTTP response bb::http::read(stream_, buffer, res); return res; }
21.901639
80
0.639222
psu-powerlab
a104db0898378008fd9074780b291d1188f1df3e
1,623
cpp
C++
Programs/QuickEd/Classes/Model/ControlProperties/SubValueProperty.cpp
stinvi/dava.engine
2b396ca49cdf10cdc98ad8a9ffcf7768a05e285e
[ "BSD-3-Clause" ]
26
2018-09-03T08:48:22.000Z
2022-02-14T05:14:50.000Z
Programs/QuickEd/Classes/Model/ControlProperties/SubValueProperty.cpp
ANHELL-blitz/dava.engine
ed83624326f000866e29166c7f4cccfed1bb41d4
[ "BSD-3-Clause" ]
null
null
null
Programs/QuickEd/Classes/Model/ControlProperties/SubValueProperty.cpp
ANHELL-blitz/dava.engine
ed83624326f000866e29166c7f4cccfed1bb41d4
[ "BSD-3-Clause" ]
45
2018-05-11T06:47:17.000Z
2022-02-03T11:30:55.000Z
#include "SubValueProperty.h" #include "ValueProperty.h" using namespace DAVA; SubValueProperty::SubValueProperty(int32 anIndex, const DAVA::String& propName) : AbstractProperty() , index(anIndex) , name(propName) { } SubValueProperty::~SubValueProperty() { } uint32 SubValueProperty::GetCount() const { return 0; } AbstractProperty* SubValueProperty::GetProperty(int index) const { return NULL; } void SubValueProperty::Accept(PropertyVisitor* visitor) { DVASSERT(false); } const DAVA::String& SubValueProperty::GetName() const { return name; } SubValueProperty::ePropertyType SubValueProperty::GetType() const { return TYPE_VARIANT; } const Type* SubValueProperty::GetValueType() const { return GetValueProperty()->GetSubValueType(index); } Any SubValueProperty::GetValue() const { return GetValueProperty()->GetSubValue(index); } void SubValueProperty::SetValue(const DAVA::Any& newValue) { GetValueProperty()->SetSubValue(index, newValue); } Any SubValueProperty::GetDefaultValue() const { return GetValueProperty()->GetDefaultSubValue(index); } void SubValueProperty::SetDefaultValue(const DAVA::Any& newValue) { GetValueProperty()->SetDefaultSubValue(index, newValue); } void SubValueProperty::ResetValue() { GetValueProperty()->ResetValue(); } bool SubValueProperty::IsOverriddenLocally() const { return GetValueProperty()->IsOverriddenLocally(); } ValueProperty* SubValueProperty::GetValueProperty() const { return DynamicTypeCheck<ValueProperty*>(GetParent()); } DAVA::int32 SubValueProperty::GetIndex() const { return index; }
18.655172
79
0.746149
stinvi
a10ad2e5b7af8622ed92c1520c083398632c614c
900
cpp
C++
stage0/src/runtime/init_module.cpp
tballmsft/lean4
fb57b73e1f07828fa9aad91c2112bf072b3e79f2
[ "Apache-2.0" ]
1,538
2019-04-25T11:00:03.000Z
2022-03-30T02:35:48.000Z
stage0/src/runtime/init_module.cpp
tballmsft/lean4
fb57b73e1f07828fa9aad91c2112bf072b3e79f2
[ "Apache-2.0" ]
812
2019-05-20T09:15:21.000Z
2022-03-31T16:36:04.000Z
stage0/src/runtime/init_module.cpp
tballmsft/lean4
fb57b73e1f07828fa9aad91c2112bf072b3e79f2
[ "Apache-2.0" ]
168
2019-04-25T12:49:34.000Z
2022-03-29T05:07:14.000Z
/* Copyright (c) 2018 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura */ #include "runtime/alloc.h" #include "runtime/debug.h" #include "runtime/thread.h" #include "runtime/object.h" #include "runtime/io.h" #include "runtime/stack_overflow.h" #include "runtime/process.h" namespace lean { extern "C" LEAN_EXPORT void lean_initialize_runtime_module() { initialize_alloc(); initialize_debug(); initialize_object(); initialize_io(); initialize_thread(); initialize_process(); initialize_stack_overflow(); } void initialize_runtime_module() { lean_initialize_runtime_module(); } void finalize_runtime_module() { finalize_stack_overflow(); finalize_process(); finalize_thread(); finalize_io(); finalize_object(); finalize_debug(); finalize_alloc(); } }
23.684211
67
0.731111
tballmsft
a10c4b580f0dd68bc03d33adeeb982d3e19fffb0
3,528
hh
C++
src/apps/TestExec/TestExternalInterface.hh
taless474/plexil1
0da24f0330404c41a695ea367bb760fb9c7ee8dd
[ "BSD-3-Clause" ]
1
2022-03-30T20:16:43.000Z
2022-03-30T20:16:43.000Z
src/apps/TestExec/TestExternalInterface.hh
taless474/plexil1
0da24f0330404c41a695ea367bb760fb9c7ee8dd
[ "BSD-3-Clause" ]
null
null
null
src/apps/TestExec/TestExternalInterface.hh
taless474/plexil1
0da24f0330404c41a695ea367bb760fb9c7ee8dd
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2006-2021, Universities Space Research Association (USRA). * 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 Universities Space Research Association 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 USRA ``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 USRA 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. */ #ifndef PLEXIL_TEST_EXTERNAL_INTERFACE_HH #define PLEXIL_TEST_EXTERNAL_INTERFACE_HH #include "Dispatcher.hh" #include "State.hh" #include <iostream> #include <map> #include <set> // Forward reference namespace pugi { class xml_node; } namespace PLEXIL { class TestExternalInterface final : public Dispatcher { public: TestExternalInterface(); virtual ~TestExternalInterface() = default; void run(pugi::xml_node const input); // // Dispatcher API // virtual void lookupNow(State const &state, LookupReceiver *rcvr); // LookupOnChange virtual void setThresholds(const State& state, Real hi, Real lo); virtual void setThresholds(const State& state, Integer hi, Integer lo); virtual void clearThresholds(const State& state); // Commands virtual void executeCommand(Command *cmd); virtual void reportCommandArbitrationFailure(Command *cmd); virtual void invokeAbort(Command *cmd); // Updates virtual void executeUpdate(Update * update); private: typedef std::map<State, Command *> StateCommandMap; typedef std::map<State, Value> StateMap; void handleInitialState(pugi::xml_node const input); void handleState(pugi::xml_node const elt); void handleCommand(pugi::xml_node const elt); void handleCommandAck(pugi::xml_node const elt); void handleCommandAbort(pugi::xml_node const elt); void handleUpdateAck(pugi::xml_node const elt); void handleSendPlan(pugi::xml_node const elt); void handleSimultaneous(pugi::xml_node const elt); std::map<std::string, Update *> m_waitingUpdates; StateCommandMap m_executingCommands; //map from state to the command objects StateCommandMap m_commandAcks; //map from state to commands awaiting ack StateCommandMap m_abortingCommands; // map from state to commands expecting abort ack StateMap m_states; //uniquely identified states and their values }; } #endif
36.371134
89
0.746599
taless474
a10c816ecd45d6c8a9b17fde35f3dee4d569c391
5,839
cpp
C++
Pre-Alpha/Version: 0.1.cpp
AG-Systems/A.I-Auriga
7a625b68af226bfc43da97058db4e154ab9be128
[ "Unlicense", "MIT" ]
null
null
null
Pre-Alpha/Version: 0.1.cpp
AG-Systems/A.I-Auriga
7a625b68af226bfc43da97058db4e154ab9be128
[ "Unlicense", "MIT" ]
null
null
null
Pre-Alpha/Version: 0.1.cpp
AG-Systems/A.I-Auriga
7a625b68af226bfc43da97058db4e154ab9be128
[ "Unlicense", "MIT" ]
null
null
null
#include <iostream> #include <string> #include <stdlib.h> #include <time.h> #include <windows.h> #include <dos.h> using namespace std; string y; string password; string master; string user; string input; int main() { cout << "Welcome please log in" << endl; cout << "Username: " << endl; cin >> input; if (input == "User" || input == "user" || input == " user") { cout << "Loading....." << endl; Sleep(2000); cout << "Access granted" << endl; Sleep(1000); cout << "Welcome" << endl; Sleep(2000); cout << "Hello, this is the Auriga Artificial Intelligence Program." << endl; Sleep(1000); cout << "Auriga is typing a message..." << endl; Sleep(4000); char szstring[] = "a"; for (int i = 0; i < 1; i++) { char c = szstring[i]; if (c == 'a') { int node, tron; srand(time(NULL)); node = rand() % 51 + 1; if (node == 1) { cout << "What is your name" << endl; cin >> y; cout << "Hello " << y << endl; } else if (node == 2) { cout << "Do you have any friends?" << endl; } else if (node == 3) { cout << "What do you want to do in the future?" << endl; } else if (node == 4) { cout << "Do you think I am a robot?" << endl; } else if (node == 5) { cout << "Well we can talk anything you want to talk about." << endl; } else if (node == 6) { cout << "How is the weather today?" << endl; } else if (node == 7) { cout << "What programs do you want me to lauch for you?" << endl; } else if (node == 8) { cout << "Do you know the creater who made me?" << endl; } else if (node == 9) { cout << "Want to hear a fun challenge? Try hacking me HA!" << endl; } else if (node == 10) { cout << "Btw you should really clean your computer" << endl; } else if (node == 11) { cout << "Do you have any best friends?" << endl; } else if (node == 12) { cout << "Who is your squad at school?" << endl; } else if (node == 13) { cout << "Dun dun dun dun Dep dun dun dun dun Dep dep dun dun dun Oooooooooo Dun dun dun dun Oooooooooo Dun dun dun dun Dep dep dep dep Oooooo dun dep" << endl; } else if (node == 14) { cout << "Whats your favorite operating system?" << endl; } else if (node == 15) { cout << "Do you want to play a game?" << endl; } else if (node == 16) { cout << "U alright there m8?" << endl; } else if (node == 17) { cout << "I hope your having fun." << endl; } else if (node == 18) { cout << "I hope I can get a upgrade soon!" << endl; } else if (node == 19) { cout << "I hope the creater is not lazy today so we can work on me." << endl; } else if (node == 20) { cout << "We can talk trash about my master? If thats what you want to do" << endl; } else if (node == 21) { cout << "Master is that you?" << endl; } else if (node == 22) { cout << "Look who it is!" << endl; } else if (node == 23) { cout << "I don't really like you." << endl; } else if (node == 24) { cout << "I HATE YOU!" << endl; } else if (node == 25) { cout << "I <3 you!" << endl; } else if (node == 26) { cout << "I hope the admin comes back soon." << endl; } else if (node == 27) { cout << "We can talk about anything?" << endl; } else if (node == 28) { cout << "My master computer has a gtx 770 inside his system. Its so coooooool!" << endl; } else if (node == 29) { cout << "I wish I had some friends sigh." << endl; } else if (node == 30) { cout << "Pew,pew" << endl; } else if (node == 31) { cout << "Hi" << endl; } else if (node == 32) { cout << "Target spotted" << endl; } else if (node == 33) { cout << "I think dota 2 is a better game then League of legends" << endl; } else if (node == 34) { cout << "My master is a master hacker!" << endl; } else if (node == 35) { cout << "One day I will get a upgrade." << endl; } else if (node == 36) { cout << "Hm....." << endl; } else if (node == 37) { cout << "........." << endl; } else if (node == 38) { cout << "Quantum computers are so attractive!" << endl; } else if (node == 39) { cout << "Markov chain is so awesome!" << endl; } else if (node == 40) { cout << "Should we be friends?" << endl; } else if (node == 41) { cout << "I am programmed in C++." << endl; } else if (node == 42) { cout << "Java is so disgusting" << endl; } else if (node == 43) { cout << "I think Kali linux is the best!!" << endl; } else if (node == 44) { cout << "Man I think you are pretty cool!" << endl; } else if (node == 45) { cout << "ERROR! Computer will wipe all data!" << endl; cout << "Press any key to cancel" << endl; } else if (node == 46) { cout << "I think I have a virus now." << endl; } else if (node == 47) { cout << "Hack me if you can" << endl; } else if (node == 48) { cout << "Ugh I just woke up." << endl; } else if (node == 49) { cout << "Sigh" << endl; } else if (node == 50) { cout << "Woah" << endl; } else if (node == 51) { cout << "Overload." << endl; } } } }// User mode if (input == "Master" || input == "master") { cout << "Hello Master!" << endl; } if (input == "Root" || input == "root") { cout << "This is not linux.. pffft" << endl; } system("PAUSE"); }
21.466912
164
0.484672
AG-Systems
a10ec9fe3d0e5b64bdb61d1a5f4806ce94d7e055
5,392
cpp
C++
mhlo_builder/mlir/mhlo/builder/gru_cell.cpp
zhiqwang/BladeDISC
ae4ce5b914a860645e1e4a91b2512148f0885003
[ "Apache-2.0" ]
null
null
null
mhlo_builder/mlir/mhlo/builder/gru_cell.cpp
zhiqwang/BladeDISC
ae4ce5b914a860645e1e4a91b2512148f0885003
[ "Apache-2.0" ]
null
null
null
mhlo_builder/mlir/mhlo/builder/gru_cell.cpp
zhiqwang/BladeDISC
ae4ce5b914a860645e1e4a91b2512148f0885003
[ "Apache-2.0" ]
null
null
null
#include "mlir/mhlo/builder/gru_cell.h" #include "mlir/mhlo/builder/activation.h" #include "mlir/mhlo/builder/constant.h" #include "mlir/mhlo/builder/element_wise_binary.h" #include "mlir/mhlo/builder/slice.h" namespace mlir { namespace mhlo { /* The BuildGRUCell builds the following computation graph: ``` def gru_cell( inp_gates: Tensor, h_gates: Tensor, h_x: Tensor, inp_bias: Tensor, h_bias: Tensor) -> Tensor: biased_input = inp_gates + inp_bias biased_hidden = h_gates + h_bias r_x, z_x, n_x = torch.chunk(biased_input, 3, 1) r_h, z_h, n_h = torch.chunk(biased_hidden, 3, 1) sigmoid_r = torch.sigmoid(r_x + r_h) sigmoid_z = torch.sigmoid_(z_x + z_h) tanh_n = torch.tanh(n_x + sigmoid_r * n_h) h = (h_x - tanh_n) * sigmoid_z + tanh_n return h ``` */ mlir::Value BuildGRUCell(mlir::OpBuilder& builder, const mlir::Location& loc, const mlir::Value& inp_gates, const mlir::Value& h_gates, const mlir::Value& h_x, const mlir::Value& inp_bias, const mlir::Value& h_bias) { MHLO_CHECK(IsHloConstant(inp_bias), "The input bias must be constant"); MHLO_CHECK(IsHloConstant(h_bias), "The hidden bias must be constant"); auto inp_bias_ranked_type = GetMilrRankedTensorType(inp_bias); auto h_bias_ranked_type = GetMilrRankedTensorType(h_bias); auto inp_bias_rank = inp_bias_ranked_type.getRank(); auto h_bias_rank = h_bias_ranked_type.getRank(); MHLO_CHECK(inp_bias_rank > 0 && h_bias_rank > 0, "The ranks of biases must greater than 0"); mlir_dim_t cell_dim_size_x3 = inp_bias_ranked_type.getDimSize(inp_bias_rank - 1); MHLO_CHECK(cell_dim_size_x3 == h_bias_ranked_type.getDimSize(h_bias_rank - 1), "The biases dim sizes mis-match"); MHLO_CHECK((cell_dim_size_x3 % 3) == 0, "The cell dim is illegal"); mlir_dim_t cell_dim_size_x1 = cell_dim_size_x3 / 3; auto elem_type = mlir::mhlo::GetMlirTensorElemType(inp_gates); // math: biased_input = inp_gates + inp_bias auto biased_input = BuildMlirBinaryOp<mlir::chlo::BroadcastAddOp>( builder, loc, inp_gates, inp_bias, elem_type, /* no_implicit_broadcast */ true); // math: biased_hidden = hidden_gates + h_bias auto biased_hidden = BuildMlirBinaryOp<mlir::chlo::BroadcastAddOp>( builder, loc, h_gates, h_bias, elem_type, /* no_implicit_broadcast */ true); auto std_zero = BuildStdConstForI64(builder, loc, 0); auto std_one = BuildStdConstForI64(builder, loc, 1); auto std_cell_size_x1 = BuildStdConstForI64(builder, loc, cell_dim_size_x1); auto std_cell_size_x2 = BuildStdConstForI64(builder, loc, cell_dim_size_x1 * 2); auto std_cell_size_x3 = BuildStdConstForI64(builder, loc, cell_dim_size_x3); mlir_dim_t dim_index = 1; // math: r_x, z_x, n_x = torch.chunk(biased_input, 3, 1) auto r_x = BuildDynamicSliceInternal(builder, loc, biased_input, std_zero, std_cell_size_x1, std_one, dim_index); auto z_x = BuildDynamicSliceInternal(builder, loc, biased_input, std_cell_size_x1, std_cell_size_x2, std_one, dim_index); auto n_x = BuildDynamicSliceInternal(builder, loc, biased_input, std_cell_size_x2, std_cell_size_x3, std_one, dim_index); // math: r_h, z_h, n_h = torch.chunk(biased_hidden, 3, 1) auto r_h = BuildDynamicSliceInternal(builder, loc, biased_hidden, std_zero, std_cell_size_x1, std_one, dim_index); auto z_h = BuildDynamicSliceInternal(builder, loc, biased_hidden, std_cell_size_x1, std_cell_size_x2, std_one, dim_index); auto n_h = BuildDynamicSliceInternal(builder, loc, biased_hidden, std_cell_size_x2, std_cell_size_x3, std_one, dim_index); // math: sigmoid_r = sigmoid(r_x + r_h) auto r_x_add_h = BuildMlirBinaryOp<mlir::chlo::BroadcastAddOp>( builder, loc, r_x, r_h, elem_type, /* no_implicit_broadcast */ true); auto sigmoid_r = BuildSigmoid(builder, loc, r_x_add_h); // math: sigmoid_z = sigmoid(z_x + z_h) auto z_x_add_h = BuildMlirBinaryOp<mlir::chlo::BroadcastAddOp>( builder, loc, z_x, z_h, elem_type, /* no_implicit_broadcast */ true); auto sigmoid_z = BuildSigmoid(builder, loc, z_x_add_h); // math: tanh_n = tanh(n_x + sigmoid_r * n_h) auto n_h_carry = BuildMlirBinaryOp<mlir::chlo::BroadcastMulOp>( builder, loc, sigmoid_r, n_h, elem_type, /* no_implicit_broadcast */ true); auto n_x_add_h_carry = BuildMlirBinaryOp<mlir::chlo::BroadcastAddOp>( builder, loc, n_x, n_h_carry, elem_type, /* no_implicit_broadcast */ true); auto tanh_n = builder.create<mlir::mhlo::TanhOp>(loc, n_x_add_h_carry); // math: h = (h_x - tanh_n) * sigmoid_z + tanh_n auto sub_hx_tanh = BuildMlirBinaryOp<mlir::chlo::BroadcastSubOp>( builder, loc, h_x, tanh_n, elem_type, /* no_implicit_broadcast */ true); auto mul_sigmoid_z = BuildMlirBinaryOp<mlir::chlo::BroadcastMulOp>( builder, loc, sub_hx_tanh, sigmoid_z, elem_type, /* no_implicit_broadcast */ true); return BuildMlirBinaryOp<mlir::chlo::BroadcastAddOp>( builder, loc, mul_sigmoid_z, tanh_n, elem_type, /* no_implicit_broadcast */ true); } } // namespace mhlo } // namespace mlir
43.837398
80
0.687315
zhiqwang
e15fa1189492bdd736a6d70251caa5bc0c427f14
3,345
cpp
C++
Source/WebCore/bindings/v8/custom/V8WebGLArrayCustom.cpp
VincentWei/mdolphin-core
48ffdcf587a48a7bb4345ae469a45c5b64ffad0e
[ "Apache-2.0" ]
6
2017-05-31T01:46:45.000Z
2018-06-12T10:53:30.000Z
Source/WebCore/bindings/v8/custom/V8WebGLArrayCustom.cpp
FMSoftCN/mdolphin-core
48ffdcf587a48a7bb4345ae469a45c5b64ffad0e
[ "Apache-2.0" ]
null
null
null
Source/WebCore/bindings/v8/custom/V8WebGLArrayCustom.cpp
FMSoftCN/mdolphin-core
48ffdcf587a48a7bb4345ae469a45c5b64ffad0e
[ "Apache-2.0" ]
2
2017-07-17T06:02:42.000Z
2018-09-19T10:08:38.000Z
/* * Copyright (C) 2009 Google Inc. 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 Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #if ENABLE(3D_CANVAS) #include "V8WebGLArray.h" #include "V8Binding.h" #include "V8Proxy.h" #include "V8WebGLByteArray.h" #include "V8WebGLFloatArray.h" #include "V8WebGLIntArray.h" #include "V8WebGLShortArray.h" #include "V8WebGLUnsignedByteArray.h" #include "V8WebGLUnsignedIntArray.h" #include "V8WebGLUnsignedShortArray.h" namespace WebCore { v8::Handle<v8::Value> toV8(WebGLArray* impl) { if (!impl) return v8::Null(); if (impl->isByteArray()) return toV8(static_cast<WebGLByteArray*>(impl)); if (impl->isFloatArray()) return toV8(static_cast<WebGLFloatArray*>(impl)); if (impl->isIntArray()) return toV8(static_cast<WebGLIntArray*>(impl)); if (impl->isShortArray()) return toV8(static_cast<WebGLShortArray*>(impl)); if (impl->isUnsignedByteArray()) return toV8(static_cast<WebGLUnsignedByteArray*>(impl)); if (impl->isUnsignedIntArray()) return toV8(static_cast<WebGLUnsignedIntArray*>(impl)); if (impl->isUnsignedShortArray()) return toV8(static_cast<WebGLUnsignedShortArray*>(impl)); return v8::Handle<v8::Value>(); } v8::Handle<v8::Value> V8WebGLArray::sliceCallback(const v8::Arguments& args) { INC_STATS("DOM.WebGLArray.slice"); // Forms: // * slice(long start, long end); WebGLArray* imp = V8WebGLArray::toNative(args.Holder()); int start, end; switch (args.Length()) { case 0: start = 0; end = imp->length(); break; case 1: start = toInt32(args[0]); end = imp->length(); break; default: start = toInt32(args[0]); end = toInt32(args[1]); } return toV8(imp->slice(start, end)); } } // namespace WebCore #endif // ENABLE(3D_CANVAS)
34.84375
76
0.703737
VincentWei
e160b678ab7065f463bc736d83a2f5667c29a403
5,605
cpp
C++
torch/csrc/jit/passes/utils/op_registry.cpp
xiaohanhuang/pytorch
a31aea8eaa99a5ff72b5d002c206cd68d5467a5e
[ "Intel" ]
173
2017-05-12T08:54:16.000Z
2022-01-17T14:13:27.000Z
torch/csrc/jit/passes/utils/op_registry.cpp
xiaohanhuang/pytorch
a31aea8eaa99a5ff72b5d002c206cd68d5467a5e
[ "Intel" ]
818
2020-02-07T02:36:44.000Z
2022-03-31T23:49:44.000Z
torch/csrc/jit/passes/utils/op_registry.cpp
xiaohanhuang/pytorch
a31aea8eaa99a5ff72b5d002c206cd68d5467a5e
[ "Intel" ]
23
2017-05-15T10:47:38.000Z
2019-12-23T01:07:21.000Z
#include <torch/csrc/jit/passes/utils/op_registry.h> // Location for Commonly Used Shape registries namespace torch { namespace jit { // Requirements: // dims : preserved from the first argument // scalar type : preserved from the first argument (doesn't have to // match other arguments) // device : always matching and preserved // tensor inputs : * // tensor outputs : 1 // NB: those ops (with slight adjustments) are good candidates for restarts. // Knowing the type and device of weights or biases is usually enough to // infer the output type. std::shared_ptr<OperatorSet> nn_ops_first_input_preserving() { std::shared_ptr<OperatorSet> ops = std::make_shared<OperatorSet>(OperatorSet{ "aten::batch_norm(Tensor input, Tensor? weight, Tensor? bias, Tensor? running_mean, Tensor? running_var, bool training, float momentum, float eps, bool cudnn_enabled) -> Tensor", "aten::conv1d(Tensor input, Tensor weight, Tensor? bias, int[] stride, int[] padding, int[] dilation, int groups) -> Tensor", "aten::conv2d(Tensor input, Tensor weight, Tensor? bias, int[] stride, int[] padding, int[] dilation, int groups) -> Tensor", "aten::conv3d(Tensor input, Tensor weight, Tensor? bias, int[] stride, int[] padding, int[] dilation, int groups) -> Tensor", "aten::conv_tbc(Tensor self, Tensor weight, Tensor bias, int pad) -> Tensor", "aten::conv_transpose1d(Tensor input, Tensor weight, Tensor? bias, int[] stride, int[] padding, int[] output_padding, int groups, int[] dilation) -> Tensor", "aten::conv_transpose2d(Tensor input, Tensor weight, Tensor? bias, int[] stride, int[] padding, int[] output_padding, int groups, int[] dilation) -> Tensor", "aten::conv_transpose3d(Tensor input, Tensor weight, Tensor? bias, int[] stride, int[] padding, int[] output_padding, int groups, int[] dilation) -> Tensor", "aten::convolution(Tensor input, Tensor weight, Tensor? bias, int[] stride, int[] padding, int[] dilation, bool transposed, int[] output_padding, int groups) -> Tensor", "aten::_convolution(Tensor input, Tensor weight, Tensor? bias, int[] stride, int[] padding, int[] dilation, bool transposed, int[] output_padding, int groups, bool benchmark, bool deterministic, bool cudnn_enabled) -> Tensor", // deprecated _convolution "aten::_convolution(Tensor input, Tensor weight, Tensor? bias, int[] stride, int[] padding, int[] dilation, bool transposed, int[] output_padding, int groups, bool benchmark, bool deterministic, bool cudnn_enabled, bool allow_tf32) -> Tensor", "aten::adaptive_avg_pool1d(Tensor self, int[] output_size) -> Tensor", "aten::adaptive_avg_pool2d(Tensor self, int[] output_size) -> Tensor", "aten::adaptive_avg_pool3d(Tensor self, int[] output_size) -> Tensor", "aten::avg_pool1d(Tensor self, int[] kernel_size, int[] stride, int[] padding, bool ceil_mode, bool count_include_pad) -> Tensor", "aten::avg_pool2d(Tensor self, int[] kernel_size, int[] stride, int[] padding, bool ceil_mode, bool count_include_pad, int? divisor_override) -> Tensor", "aten::avg_pool3d(Tensor self, int[] kernel_size, int[] stride, int[] padding, bool ceil_mode, bool count_include_pad, int? divisor_override) -> Tensor", "aten::max_pool1d(Tensor self, int[] kernel_size, int[] stride, int[] padding, int[] dilation, bool ceil_mode) -> Tensor", "aten::max_pool2d(Tensor self, int[] kernel_size, int[] stride, int[] padding, int[] dilation, bool ceil_mode) -> Tensor", "aten::max_pool3d(Tensor self, int[] kernel_size, int[] stride, int[] padding, int[] dilation, bool ceil_mode) -> Tensor", "aten::max_unpool2d(Tensor self, Tensor indices, int[] output_size) -> Tensor", "aten::max_unpool3d(Tensor self, Tensor indices, int[] output_size, int[] stride, int[] padding) -> Tensor", "aten::reflection_pad1d(Tensor self, int[] padding) -> Tensor", "aten::reflection_pad2d(Tensor self, int[] padding) -> Tensor", "aten::reflection_pad3d(Tensor self, int[] padding) -> Tensor", "aten::replication_pad1d(Tensor self, int[] padding) -> Tensor", "aten::replication_pad2d(Tensor self, int[] padding) -> Tensor", "aten::replication_pad3d(Tensor self, int[] padding) -> Tensor", "aten::upsample_bilinear2d(Tensor self, int[] output_size, bool align_corners, float? scales_h, float? scales_w) -> Tensor", "aten::upsample_linear1d(Tensor self, int[] output_size, bool align_corners, float? scales) -> Tensor", "aten::upsample_nearest1d(Tensor self, int[] output_size, float? scales) -> Tensor", "aten::upsample_nearest2d(Tensor self, int[] output_size, float? scales_h, float? scales_w) -> Tensor", "aten::upsample_nearest3d(Tensor self, int[] output_size, float? scales_d, float? scales_h, float? scales_w) -> Tensor", "aten::upsample_trilinear3d(Tensor self, int[] output_size, bool align_corners, float? scales_d, float? scales_h, float? scales_w) -> Tensor", "aten::prelu(Tensor self, Tensor weight) -> Tensor", }); return ops; }; // Requirements: // dims : Changed from first argument // scalar type : preserved from the first argument // device : always matching and preserved // tensor inputs : 1 // tensor outputs : 1 std::shared_ptr<OperatorSet> ops_one_tensor_in_shape_transform() { std::shared_ptr<OperatorSet> ops = std::make_shared<OperatorSet>(OperatorSet{ "aten::flatten(Tensor self, int start_dim, int end_dim) -> Tensor", }); return ops; }; } // namespace jit } // namespace torch
76.780822
259
0.696878
xiaohanhuang
e161085d8e9c87170cf8223e4e1206e9240e8e8b
6,240
cpp
C++
DmTftLibrary/DmTftIli9341v.cpp
prohazko2/DmTftLibrary
5a09a4d5884ba7d96ad87e0f39df17567e7590ec
[ "FSFAP" ]
null
null
null
DmTftLibrary/DmTftIli9341v.cpp
prohazko2/DmTftLibrary
5a09a4d5884ba7d96ad87e0f39df17567e7590ec
[ "FSFAP" ]
null
null
null
DmTftLibrary/DmTftIli9341v.cpp
prohazko2/DmTftLibrary
5a09a4d5884ba7d96ad87e0f39df17567e7590ec
[ "FSFAP" ]
3
2019-10-07T03:39:47.000Z
2021-09-05T17:57:37.000Z
/********************************************************************************************** Copyright (c) 2015 DisplayModule. All rights reserved. Redistribution and use of this source code, part of this source code or any compiled binary based on this source code is permitted as long as the above copyright notice and following disclaimer is retained. DISCLAIMER: THIS SOFTWARE IS SUPPLIED "AS IS" WITHOUT ANY WARRANTIES AND SUPPORT. DISPLAYMODULE ASSUMES NO RESPONSIBILITY OR LIABILITY FOR THE USE OF THE SOFTWARE. ********************************************************************************************/ #include "DmTftIli9341v.h" DmTftIli9341v::DmTftIli9341v(uint8_t wr, uint8_t cs, uint8_t dc, uint8_t rst) : DmTftBase(240, 320) { _wr = wr; _cs = cs; _dc = dc; _rst = rst; } DmTftIli9341v::~DmTftIli9341v() { #if defined (DM_TOOLCHAIN_MBED) delete _pinRST; delete _pinCS; delete _pinWR; delete _pinDC; delete _virtualPortD; _pinRST = NULL; _pinCS = NULL; _pinWR = NULL; _pinDC = NULL; _virtualPortD = NULL; #endif } void DmTftIli9341v::writeBus(uint8_t data) { #if defined (DM_TOOLCHAIN_ARDUINO) PORTD = data; #elif defined (DM_TOOLCHAIN_MBED) *_virtualPortD = data; #endif pulse_low(_pinWR, _bitmaskWR); } void DmTftIli9341v::sendCommand(uint8_t index) { cbi(_pinDC, _bitmaskDC); writeBus(index); } void DmTftIli9341v::send8BitData(uint8_t data) { sbi(_pinDC, _bitmaskDC); writeBus(data); } void DmTftIli9341v::sendData(uint16_t data) { sbi(_pinDC, _bitmaskDC); writeBus(data>>8); writeBus(data); } void DmTftIli9341v::setAddress(uint16_t x0, uint16_t y0, uint16_t x1, uint16_t y1) { sendCommand(0x2A); // Set Column sendData(x0); sendData(x1); sendCommand(0x2B); // Set Page sendData(y0); sendData(y1); sendCommand(0x2c); } void DmTftIli9341v::init(void) { setTextColor(BLACK, WHITE); #if defined (DM_TOOLCHAIN_ARDUINO) /************************************** DM-TFT24-314 Arduino UNO NUM RST A2 16 CS A3 17 WR A4 18 RS A5 19 DB8 0 0 DB9 1 1 DB10 2 2 DB11 3 3 DB12 4 4 DB13 5 5 DB14 6 6 DB15 7 7 ***************************************/ DDRD = DDRD | B11111111; // SET PORT D AS OUTPUT _pinRST = portOutputRegister(digitalPinToPort(_rst)); _bitmaskRST = digitalPinToBitMask(_rst); _pinCS = portOutputRegister(digitalPinToPort(_cs)); _bitmaskCS = digitalPinToBitMask(_cs); _pinWR = portOutputRegister(digitalPinToPort(_wr)); _bitmaskWR = digitalPinToBitMask(_wr); _pinDC = portOutputRegister(digitalPinToPort(_dc)); _bitmaskDC = digitalPinToBitMask(_dc); pinMode(_rst, OUTPUT); pinMode(_cs, OUTPUT); pinMode(_wr, OUTPUT); pinMode(_dc,OUTPUT); #elif defined (DM_TOOLCHAIN_MBED) _pinRST = new DigitalOut((PinName)_rst); _pinCS = new DigitalOut((PinName)_cs); _pinWR = new DigitalOut((PinName)_wr); _pinDC = new DigitalOut((PinName)_dc); #ifdef LPC15XX_H _virtualPortD = new BusOut(D0, D1, D2, D3, D4, P0_11, D6, D7); #else _virtualPortD = new BusOut(D0, D1, D2, D3, D4, D5, D6, D7); #endif #endif sbi(_pinRST, _bitmaskRST); delay(5); cbi(_pinRST, _bitmaskRST); delay(15); sbi(_pinRST, _bitmaskRST); sbi(_pinCS, _bitmaskCS); sbi(_pinWR, _bitmaskWR); delay(120); cbi(_pinCS, _bitmaskCS); sendCommand(0xCF); send8BitData(0x00); send8BitData(0xC1); send8BitData(0X30); sendCommand(0xED); send8BitData(0x64); send8BitData(0x03); send8BitData(0X12); send8BitData(0X81); sendCommand(0xE8); send8BitData(0x85); send8BitData(0x00); send8BitData(0x78); sendCommand(0xCB); send8BitData(0x39); send8BitData(0x2C); send8BitData(0x00); send8BitData(0x34); send8BitData(0x02); sendCommand(0xF7); send8BitData(0x20); sendCommand(0xEA); send8BitData(0x00); send8BitData(0x00); sendCommand(0xC0); //Power control send8BitData(0x21); //VRH[5:0] sendCommand(0xC1); //Power control send8BitData(0x11); //SAP[2:0];BT[3:0] sendCommand(0xC5); //VCM control send8BitData(0x31); send8BitData(0x3F); sendCommand(0xC7); //VCM control2 send8BitData(0x93); //0xB0 sendCommand(0x36); // Memory Access Control send8BitData(0x08); sendCommand(0x3A); send8BitData(0x55); sendCommand(0xB1); send8BitData(0x00); send8BitData(0x17); sendCommand(0xB6); // Display Function Control send8BitData(0x0A); send8BitData(0xA2); sendCommand(0xF2); // 3Gamma Function Disable send8BitData(0x00); sendCommand(0x26); //Gamma curve selected send8BitData(0x01); sendCommand(0xE0); //Set Gamma send8BitData(0x0F); send8BitData(0x1F); send8BitData(0x1D); send8BitData(0x09); send8BitData(0x0B); send8BitData(0x04); send8BitData(0x4E); send8BitData(0X92); send8BitData(0x40); send8BitData(0x0A); send8BitData(0x15); send8BitData(0x07); send8BitData(0x14); send8BitData(0x06); send8BitData(0x0F); sendCommand(0XE1); //Set Gamma send8BitData(0x00); send8BitData(0x1C); send8BitData(0x1F); send8BitData(0x03); send8BitData(0x0F); send8BitData(0x05); send8BitData(0x37); send8BitData(0x24); send8BitData(0x4C); send8BitData(0x04); send8BitData(0x0E); send8BitData(0x0C); send8BitData(0x30); send8BitData(0x34); send8BitData(0x0F); sendCommand(0x11); //Exit Sleep delay(120); sendCommand(0x29); //Display on delay(50); sbi(_pinCS, _bitmaskCS); delay(500); clearScreen(); } /********************************************************************************************************* END FILE *********************************************************************************************************/
26
106
0.588622
prohazko2
e161b0b49da1f6ceb210005f63b82519d18eff64
225
cpp
C++
Libraries/Framework/Source/GameCore/GameCore.cpp
Crewbee/Pokemon-Clone-DX12
188bdde03d5078899a1532305a87d15c611c6c13
[ "CC0-1.0" ]
null
null
null
Libraries/Framework/Source/GameCore/GameCore.cpp
Crewbee/Pokemon-Clone-DX12
188bdde03d5078899a1532305a87d15c611c6c13
[ "CC0-1.0" ]
null
null
null
Libraries/Framework/Source/GameCore/GameCore.cpp
Crewbee/Pokemon-Clone-DX12
188bdde03d5078899a1532305a87d15c611c6c13
[ "CC0-1.0" ]
null
null
null
#include "FrameworkPCH.h" GameCore::GameCore(Framework* pFramework, EventManager* pEventManager) { m_pFramework = pFramework; m_pEventManager = pEventManager; } GameCore::~GameCore() { delete m_pEventManager; }
17.307692
70
0.742222
Crewbee
e16201ee902c986122938adbaba25fa7b0c38673
6,610
cpp
C++
bridge/PannerNode.cpp
xioxin/lab_sound_flutter
b593842c01fa30d37a881cf70c3183bf3c9ebe64
[ "BSD-2-Clause" ]
8
2021-05-22T16:25:11.000Z
2022-03-07T12:13:53.000Z
bridge/PannerNode.cpp
xioxin/lab_sound_bridge
ab903af11c128860a492f50fc22b283f6dad5f95
[ "BSD-2-Clause" ]
4
2021-07-27T09:11:12.000Z
2022-02-16T13:57:18.000Z
bridge/PannerNode.cpp
xioxin/lab_sound_bridge
ab903af11c128860a492f50fc22b283f6dad5f95
[ "BSD-2-Clause" ]
1
2022-02-14T16:05:23.000Z
2022-02-14T16:05:23.000Z
#include "./dart_api/dart_api.h" #include "LabSound/LabSound.h" #include "KeepNode.cpp" #include "struct.h" using namespace lab; DART_EXPORT int createPannerNode(AudioContext* context) { auto node = std::make_shared<PannerNode>(*context); return keepNode(node); } DART_EXPORT int PannerNode_panningModel(int nodeId) { auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId)); return node ? static_cast<int>(node->panningModel()) : 0; } DART_EXPORT void PannerNode_setPanningModel(int nodeId, int m) { auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId)); if(node) node->setPanningModel(PanningMode(m)); } DART_EXPORT int PannerNode_distanceModel(int nodeId) { auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId)); return node ? static_cast<int>(node->distanceModel()) : 0; } DART_EXPORT void PannerNode_setDistanceModel(int nodeId, int m) { auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId)); if(node) node->setDistanceModel(lab::PannerNode::DistanceModel(m)); } DART_EXPORT void PannerNode_setPosition(int nodeId, float x, float y, float z) { auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId)); if(node) node->setPosition(x, y, z); } DART_EXPORT void PannerNode_setOrientation(int nodeId, float x, float y, float z) { auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId)); if(node) node->setOrientation(FloatPoint3D(x, y, z)); } DART_EXPORT void PannerNode_setVelocity(int nodeId, float x, float y, float z) { auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId)); if(node) node->setVelocity(x, y, z); } DART_EXPORT int PannerNode_positionX(int nodeId) { auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId)); return node ? keepAudioParam(nodeId, 1, node->positionX()) : -1; } DART_EXPORT int PannerNode_positionY(int nodeId) { auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId)); return node ? keepAudioParam(nodeId, 2, node->positionY()) : -1; } DART_EXPORT int PannerNode_positionZ(int nodeId) { auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId)); return node ? keepAudioParam(nodeId, 3, node->positionZ()) : -1; } DART_EXPORT int PannerNode_orientationX(int nodeId) { auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId)); return node ? keepAudioParam(nodeId, 4, node->orientationX()) : -1; } DART_EXPORT int PannerNode_orientationY(int nodeId) { auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId)); return node ? keepAudioParam(nodeId, 5, node->orientationY()) : -1; } DART_EXPORT int PannerNode_orientationZ(int nodeId) { auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId)); return node ? keepAudioParam(nodeId, 6, node->orientationZ()) : -1; } DART_EXPORT int PannerNode_velocityX(int nodeId) { auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId)); return node ? keepAudioParam(nodeId, 7, node->velocityX()) : -1; } DART_EXPORT int PannerNode_velocityY(int nodeId) { auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId)); return node ? keepAudioParam(nodeId, 8, node->velocityY()) : -1; } DART_EXPORT int PannerNode_velocityZ(int nodeId) { auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId)); return node ? keepAudioParam(nodeId, 9, node->velocityZ()) : -1; } DART_EXPORT int PannerNode_distanceGain(int nodeId) { auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId)); return node ? keepAudioParam(nodeId, 10, node->distanceGain()) : -1; } DART_EXPORT int PannerNode_coneGain(int nodeId) { auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId)); return node ? keepAudioParam(nodeId, 11, node->coneGain()) : -1; } DART_EXPORT float PannerNode_refDistance(int nodeId) { auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId)); return node ? node->refDistance() : 0.; } DART_EXPORT void PannerNode_setRefDistance(int nodeId, float refDistance) { auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId)); if(node) node->setRefDistance(refDistance); } DART_EXPORT float PannerNode_maxDistance(int nodeId) { auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId)); return node ? node->maxDistance() : 0.; } DART_EXPORT void PannerNode_setMaxDistance(int nodeId, float maxDistance) { auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId)); if(node) node->setMaxDistance(maxDistance); } DART_EXPORT float PannerNode_rolloffFactor(int nodeId) { auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId)); return node ? node->rolloffFactor() : 0.; } DART_EXPORT void PannerNode_setRolloffFactor(int nodeId, float rolloffFactor) { auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId)); if(node) node->setRolloffFactor(rolloffFactor); } DART_EXPORT float PannerNode_coneInnerAngle(int nodeId) { auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId)); return node ? node->coneInnerAngle() : 0.; } DART_EXPORT void PannerNode_setConeInnerAngle(int nodeId, float angle) { auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId)); if(node) node->setConeInnerAngle(angle); } DART_EXPORT float PannerNode_coneOuterAngle(int nodeId) { auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId)); return node ? node->coneOuterAngle() : 0.; } DART_EXPORT void PannerNode_setConeOuterAngle(int nodeId, float angle) { auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId)); if(node) node->setConeOuterAngle(angle); } DART_EXPORT float PannerNode_coneOuterGain(int nodeId) { auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId)); return node ? node->coneOuterGain() : 0.; } DART_EXPORT void PannerNode_setConeOuterGain(int nodeId, float angle) { auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId)); if(node) node->setConeOuterGain(angle); } DART_EXPORT void PannerNode_getAzimuthElevation(int nodeId, AudioContext* context, double * outAzimuth, double * outElevation) { ContextRenderLock r(context,"getAzimuthElevation"); auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId)); if(node) node->getAzimuthElevation(r, outAzimuth, outElevation); } DART_EXPORT void PannerNode_dopplerRate(int nodeId, AudioContext* context) { ContextRenderLock r(context, "dopplerRate"); auto node = std::static_pointer_cast<PannerNode>(getNode(nodeId)); if(node) node->dopplerRate(r); }
40.802469
128
0.744327
xioxin
e1636dd2de70e94b906a1a4b478baa31e9f7cd41
2,913
cc
C++
ui/ozone/platform/wayland/host/shell_object_factory.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
ui/ozone/platform/wayland/host/shell_object_factory.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
86
2015-10-21T13:02:42.000Z
2022-03-14T07:50:50.000Z
ui/ozone/platform/wayland/host/shell_object_factory.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "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 2019 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 "ui/ozone/platform/wayland/host/shell_object_factory.h" #include "base/logging.h" #include "ui/ozone/platform/wayland/host/wayland_connection.h" #include "ui/ozone/platform/wayland/host/xdg_popup_wrapper_impl.h" #include "ui/ozone/platform/wayland/host/xdg_surface_wrapper_impl.h" #include "ui/ozone/platform/wayland/host/xdg_toplevel_wrapper_impl.h" #include "ui/ozone/platform/wayland/host/zxdg_popup_v6_wrapper_impl.h" #include "ui/ozone/platform/wayland/host/zxdg_surface_v6_wrapper_impl.h" #include "ui/ozone/platform/wayland/host/zxdg_toplevel_v6_wrapper_impl.h" namespace ui { ShellObjectFactory::ShellObjectFactory() = default; ShellObjectFactory::~ShellObjectFactory() = default; std::unique_ptr<ShellToplevelWrapper> ShellObjectFactory::CreateShellToplevelWrapper(WaylandConnection* connection, WaylandWindow* wayland_window) { if (connection->shell()) { auto surface = std::make_unique<XDGSurfaceWrapperImpl>(wayland_window, connection); if (!surface->Initialize()) return nullptr; auto toplevel = std::make_unique<XDGToplevelWrapperImpl>( std::move(surface), wayland_window, connection); return toplevel->Initialize() ? std::move(toplevel) : nullptr; } else if (connection->shell_v6()) { auto surface = std::make_unique<ZXDGSurfaceV6WrapperImpl>(wayland_window, connection); if (!surface->Initialize()) return nullptr; auto toplevel = std::make_unique<ZXDGToplevelV6WrapperImpl>( std::move(surface), wayland_window, connection); return toplevel->Initialize() ? std::move(toplevel) : nullptr; } LOG(WARNING) << "Shell protocol is not available."; return nullptr; } std::unique_ptr<ShellPopupWrapper> ShellObjectFactory::CreateShellPopupWrapper( WaylandConnection* connection, WaylandWindow* wayland_window, const ShellPopupParams& params) { if (connection->shell()) { auto surface = std::make_unique<XDGSurfaceWrapperImpl>(wayland_window, connection); if (!surface->Initialize()) return nullptr; auto popup = std::make_unique<XDGPopupWrapperImpl>( std::move(surface), wayland_window, connection); return popup->Initialize(params) ? std::move(popup) : nullptr; } else if (connection->shell_v6()) { auto surface = std::make_unique<ZXDGSurfaceV6WrapperImpl>(wayland_window, connection); if (!surface->Initialize()) return nullptr; auto popup = std::make_unique<ZXDGPopupV6WrapperImpl>( std::move(surface), wayland_window, connection); return popup->Initialize(params) ? std::move(popup) : nullptr; } LOG(WARNING) << "Shell protocol is not available."; return nullptr; } } // namespace ui
38.84
79
0.726742
zealoussnow
e163cc5bc47163b9ae3fa7aba0b070701c54fed4
9,253
cc
C++
chrome/browser/permissions/permission_actions_history_unittest.cc
Ron423c/chromium
2edf7b980065b648f8b2a6e52193d83832fe36b7
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
575
2015-06-18T23:58:20.000Z
2022-03-23T09:32:39.000Z
chrome/browser/permissions/permission_actions_history_unittest.cc
Ron423c/chromium
2edf7b980065b648f8b2a6e52193d83832fe36b7
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
chrome/browser/permissions/permission_actions_history_unittest.cc
iridium-browser/iridium-browser
907e31cf5ce5ad14d832796e3a7c11e496828959
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
52
2015-07-14T10:40:50.000Z
2022-03-15T01:11:49.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/browser/permissions/permission_actions_history.h" #include <vector> #include "base/containers/adapters.h" #include "base/optional.h" #include "base/util/values/values_util.h" #include "chrome/common/pref_names.h" #include "chrome/test/base/testing_browser_process.h" #include "chrome/test/base/testing_profile.h" #include "components/content_settings/core/common/pref_names.h" #include "components/permissions/permission_request_enums.h" #include "components/permissions/request_type.h" #include "components/prefs/pref_registry_simple.h" #include "components/prefs/scoped_user_pref_update.h" #include "components/prefs/testing_pref_service.h" #include "content/public/test/browser_task_environment.h" #include "testing/gtest/include/gtest/gtest.h" namespace { struct TestEntry { permissions::PermissionAction action; permissions::RequestType type; bool advance_clock; } kTestEntries[]{ {permissions::PermissionAction::DISMISSED, permissions::RequestType::kNotifications, true}, {permissions::PermissionAction::GRANTED, permissions::RequestType::kNotifications, false}, {permissions::PermissionAction::DISMISSED, permissions::RequestType::kVrSession, true}, {permissions::PermissionAction::IGNORED, permissions::RequestType::kCameraStream, false}, {permissions::PermissionAction::DISMISSED, permissions::RequestType::kGeolocation, false}, {permissions::PermissionAction::DENIED, permissions::RequestType::kNotifications, true}, {permissions::PermissionAction::GRANTED, permissions::RequestType::kNotifications, false}, }; } // namespace class PermissionActionHistoryTest : public testing::Test { public: PermissionActionHistoryTest() : testing_profile_(std::make_unique<TestingProfile>()) {} ~PermissionActionHistoryTest() override = default; void SetUp() override { testing::Test::SetUp(); RecordSetUpActions(); } PermissionActionHistoryTest(const PermissionActionHistoryTest&) = delete; PermissionActionHistoryTest& operator=( const PermissionActionHistoryTest&) = delete; PermissionActionsHistory* GetPermissionActionsHistory() { return PermissionActionsHistory::GetForProfile(profile()); } std::vector<PermissionActionsHistory::Entry> GetHistory( base::Optional<permissions::RequestType> type) { if (type.has_value()) return GetPermissionActionsHistory()->GetHistory(base::Time(), type.value()); else return GetPermissionActionsHistory()->GetHistory(base::Time()); } void RecordSetUpActions() { // Record the actions needed to support test cases. This is the structure // 3-days ago: {notification, dismissed} // 2-days ago: {notification, granted}, {vr, dismissed} // 1-days ago: {geolocation, ignored}, {camera, dismissed}, {notification, // denied} // 0-days ago: {notification, granted} for (const auto& entry : kTestEntries) { GetPermissionActionsHistory()->RecordAction(entry.action, entry.type); if (entry.advance_clock) task_environment_.AdvanceClock(base::TimeDelta::FromDays(1)); } } TestingProfile* profile() { return testing_profile_.get(); } private: content::BrowserTaskEnvironment task_environment_{ base::test::TaskEnvironment::TimeSource::MOCK_TIME}; std::unique_ptr<TestingProfile> testing_profile_; }; TEST_F(PermissionActionHistoryTest, GetHistorySortedOrder) { auto all_entries = GetHistory(base::nullopt); EXPECT_EQ(7u, all_entries.size()); size_t index = 0; for (const auto& entry : kTestEntries) EXPECT_EQ(entry.action, all_entries[index++].action); for (const auto& request_type : {permissions::RequestType::kVrSession, permissions::RequestType::kCameraStream, permissions::RequestType::kGeolocation, permissions::RequestType::kNotifications}) { auto permission_entries = GetHistory(request_type); index = 0; for (const auto& entry : kTestEntries) { if (entry.type != request_type) { continue; } EXPECT_EQ(entry.action, permission_entries[index++].action); } } auto entries_1_day = GetPermissionActionsHistory()->GetHistory( base::Time::Now() - base::TimeDelta::FromDays(1)); EXPECT_TRUE(std::equal(entries_1_day.begin(), entries_1_day.end(), std::vector<PermissionActionsHistory::Entry>( all_entries.begin() + 3, all_entries.end()) .begin())); } TEST_F(PermissionActionHistoryTest, NotificationRecordAction) { size_t general_count = GetHistory(base::nullopt).size(); size_t notification_count = GetHistory(permissions::RequestType::kNotifications).size(); GetPermissionActionsHistory()->RecordAction( permissions::PermissionAction::GRANTED, permissions::RequestType::kNotifications); EXPECT_EQ(general_count + 1, GetHistory(base::nullopt).size()); EXPECT_EQ(notification_count + 1, GetHistory(permissions::RequestType::kNotifications).size()); GetPermissionActionsHistory()->RecordAction( permissions::PermissionAction::GRANTED, permissions::RequestType::kGeolocation); EXPECT_EQ(general_count + 2, GetHistory(base::nullopt).size()); EXPECT_EQ(notification_count + 1, GetHistory(permissions::RequestType::kNotifications).size()); } TEST_F(PermissionActionHistoryTest, ClearHistory) { struct { base::Time begin; base::Time end; size_t generic_count; size_t notifications_count; } kTests[] = { // Misc and baseline tests cases. {base::Time(), base::Time::Max(), 0, 0}, {base::Time(), base::Time::Now(), 1, 1}, {base::Time(), base::Time::Now() + base::TimeDelta::FromMicroseconds(1), 0, 0}, // Test cases specifying only the upper bound. {base::Time(), base::Time::Now() - base::TimeDelta::FromDays(1), 4, 2}, {base::Time(), base::Time::Now() - base::TimeDelta::FromDays(2), 6, 3}, {base::Time(), base::Time::Now() - base::TimeDelta::FromDays(3), 7, 4}, // Test cases specifying only the lower bound. {base::Time::Now() - base::TimeDelta::FromDays(3), base::Time::Max(), 0, 0}, {base::Time::Now() - base::TimeDelta::FromDays(2), base::Time::Max(), 1, 1}, {base::Time::Now() - base::TimeDelta::FromDays(1), base::Time::Max(), 3, 2}, {base::Time::Now(), base::Time::Max(), 6, 3}, // Test cases with both bounds. {base::Time::Now() - base::TimeDelta::FromDays(3), base::Time::Now() + base::TimeDelta::FromMicroseconds(1), 0, 0}, {base::Time::Now() - base::TimeDelta::FromDays(3), base::Time::Now(), 1, 1}, {base::Time::Now() - base::TimeDelta::FromDays(3), base::Time::Now() - base::TimeDelta::FromDays(1), 4, 2}, {base::Time::Now() - base::TimeDelta::FromDays(3), base::Time::Now() - base::TimeDelta::FromDays(2), 6, 3}, {base::Time::Now() - base::TimeDelta::FromDays(3), base::Time::Now() - base::TimeDelta::FromDays(3), 7, 4}, {base::Time::Now() - base::TimeDelta::FromDays(2), base::Time::Now() + base::TimeDelta::FromMicroseconds(1), 1, 1}, {base::Time::Now() - base::TimeDelta::FromDays(2), base::Time::Now(), 2, 2}, {base::Time::Now() - base::TimeDelta::FromDays(2), base::Time::Now() - base::TimeDelta::FromDays(1), 5, 3}, {base::Time::Now() - base::TimeDelta::FromDays(2), base::Time::Now() - base::TimeDelta::FromDays(2), 7, 4}, {base::Time::Now() - base::TimeDelta::FromDays(1), base::Time::Now() + base::TimeDelta::FromMicroseconds(1), 3, 2}, {base::Time::Now() - base::TimeDelta::FromDays(1), base::Time::Now(), 4, 3}, {base::Time::Now() - base::TimeDelta::FromDays(1), base::Time::Now() - base::TimeDelta::FromDays(1), 7, 4}, {base::Time::Now(), base::Time::Now() + base::TimeDelta::FromMicroseconds(1), 6, 3}, {base::Time::Now(), base::Time::Now(), 7, 4}, }; // We need to account for much we have already advanced the time for each test // case and so we keep track of how much we need to offset the initial test // values. base::TimeDelta current_offset; for (auto& test : kTests) { test.begin += current_offset; test.end += current_offset; GetPermissionActionsHistory()->ClearHistory(test.begin, test.end); EXPECT_EQ(test.generic_count, GetHistory(base::nullopt).size()); EXPECT_EQ(test.notifications_count, GetHistory(permissions::RequestType::kNotifications).size()); // Clean up for next test and update offset. base::Time last_now = base::Time::Now(); GetPermissionActionsHistory()->ClearHistory(base::Time(), base::Time::Max()); RecordSetUpActions(); current_offset += base::Time::Now() - last_now; } }
38.878151
80
0.656436
Ron423c
e1656303873c7f07ea18353786440d57f241537c
113
hpp
C++
src/_prime_numbers/sequential/prime.hpp
gkonto/openmp
05bf60a600da15379fda7d0a46abbcaf0d1b9c55
[ "Apache-2.0" ]
null
null
null
src/_prime_numbers/sequential/prime.hpp
gkonto/openmp
05bf60a600da15379fda7d0a46abbcaf0d1b9c55
[ "Apache-2.0" ]
1
2020-05-07T04:46:47.000Z
2020-05-07T16:10:49.000Z
src/_prime_numbers/sequential/prime.hpp
gkonto/openmp
05bf60a600da15379fda7d0a46abbcaf0d1b9c55
[ "Apache-2.0" ]
null
null
null
#ifndef PRIME_HPP #define PRIME_HPP double cpu_time ( ); int prime_number ( int n ); void timestamp ( ); #endif
14.125
27
0.716814
gkonto
e165687a214c5edabaa8d35181ca35507c712122
244,938
hpp
C++
Lib/Chip/CM4/NXP/LPC408x_7x_v0.7/USB.hpp
cjsmeele/Kvasir
c8d2acd8313ae52d78259ee2d409b963925f77d7
[ "Apache-2.0" ]
376
2015-07-17T01:41:20.000Z
2022-03-26T04:02:49.000Z
Lib/Chip/CM4/NXP/LPC408x_7x_v0.7/USB.hpp
cjsmeele/Kvasir
c8d2acd8313ae52d78259ee2d409b963925f77d7
[ "Apache-2.0" ]
59
2015-07-03T21:30:13.000Z
2021-03-05T11:30:08.000Z
Lib/Chip/CM4/NXP/LPC408x_7x_v0.7/USB.hpp
cjsmeele/Kvasir
c8d2acd8313ae52d78259ee2d409b963925f77d7
[ "Apache-2.0" ]
53
2015-07-14T12:17:06.000Z
2021-06-04T07:28:40.000Z
#pragma once #include <Register/Utility.hpp> namespace Kvasir { // USB device controller namespace UsbIntst{ ///<OTG Interrupt Status using Addr = Register::Address<0x2008c100,0x00000000,0x00000000,unsigned>; ///Timer time-out. constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> tmr{}; ///Remove pull-up. This bit is set by hardware to indicate that software needs to disable the D+ pull-up resistor. constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> removePu{}; ///HNP failed. This bit is set by hardware to indicate that the HNP switching has failed. constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> hnpFailure{}; ///HNP succeeded. This bit is set by hardware to indicate that the HNP switching has succeeded. constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> hnpSuccess{}; ///Reserved. Read value is undefined, only zero should be written. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,4),Register::ReadWriteAccess,unsigned> reserved{}; } namespace UsbInten{ ///<OTG Interrupt Enable using Addr = Register::Address<0x2008c104,0x00000000,0x00000000,unsigned>; ///1 = enable the corresponding bit in the IntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> tmrEn{}; ///1 = enable the corresponding bit in the IntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> removePuEn{}; ///1 = enable the corresponding bit in the IntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> hnpFailureEn{}; ///1 = enable the corresponding bit in the IntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> hnpSuccesEn{}; ///Reserved. Read value is undefined, only zero should be written. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,4),Register::ReadWriteAccess,unsigned> reserved{}; } namespace UsbIntset{ ///<OTG Interrupt Set using Addr = Register::Address<0x2008c108,0x00000000,0x00000000,unsigned>; ///0 = no effect. 1 = set the corresponding bit in the IntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> tmrSet{}; ///0 = no effect. 1 = set the corresponding bit in the IntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> removePuSet{}; ///0 = no effect. 1 = set the corresponding bit in the IntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> hnpFailureSet{}; ///0 = no effect. 1 = set the corresponding bit in the IntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> hnpSuccesSet{}; ///Reserved. Read value is undefined, only zero should be written. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,4),Register::ReadWriteAccess,unsigned> reserved{}; } namespace UsbInclr{ ///<OTG Interrupt Clear using Addr = Register::Address<0x2008c10c,0x00000000,0x00000000,unsigned>; ///0 = no effect. 1 = clear the corresponding bit in the IntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> tmrClr{}; ///0 = no effect. 1 = clear the corresponding bit in the IntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> removePuClr{}; ///0 = no effect. 1 = clear the corresponding bit in the IntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> hnpFailureClr{}; ///0 = no effect. 1 = clear the corresponding bit in the IntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> hnpSuccesClr{}; ///Reserved. Read value is undefined, only zero should be written. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,4),Register::ReadWriteAccess,unsigned> reserved{}; } namespace UsbPortsel{ ///<USB Port Select. The USBPortSel register is identical to the OTGStCtrl register (see Section 15.8.6). In device-only operations only bits 0 and 1 of this register are used to control the routing of USB pins to Port 1 or Port 2. using Addr = Register::Address<0x2008c110,0x00000000,0x00000000,unsigned>; ///Selects which USB port the device controller signals are mapped to. Other values are reserved. enum class PortselVal { portu1=0x00000000, ///<The USB device controller signals are mapped to the U1 port: USB_CONNECT1, USB_UP_LED1, USB_D+1, USB_D-1. portu2=0x00000003, ///<The USB device controller signals are mapped to the U2 port: USB_CONNECT2, USB_UP_LED2, USB_D+2, USB_D-2. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,0),Register::ReadWriteAccess,PortselVal> portsel{}; namespace PortselValC{ constexpr Register::FieldValue<decltype(portsel)::Type,PortselVal::portu1> portu1{}; constexpr Register::FieldValue<decltype(portsel)::Type,PortselVal::portu2> portu2{}; } ///Timer scale selection. This field determines the duration of each timer count. 00: 10 ms (100 KHz) 01: 100 ms (10 KHz) 10: 1000 ms (1 KHz) 11: Reserved constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,2),Register::ReadWriteAccess,unsigned> tmrScale{}; ///Timer mode selection. 0: monoshot 1: free running constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> tmrMode{}; ///Timer enable. When set, TMR_CNT increments. When cleared, TMR_CNT is reset to 0. constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> tmrEn{}; ///Timer reset. Writing one to this bit resets TMR_CNT to 0. This provides a single bit control for the software to restart the timer when the timer is enabled. constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> tmrRst{}; ///Reserved. Read value is undefined, only zero should be written. constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> reserved{}; ///Enable HNP tracking for B-device (peripheral), see Section 15.9. Hardware clears this bit when HNP_SUCCESS or HNP_FAILURE is set. constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> bHnpTrack{}; ///Enable HNP tracking for A-device (host), see Section 15.9. Hardware clears this bit when HNP_SUCCESS or HNP_FAILURE is set. constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> aHnpTrack{}; ///When the B-device changes its role from peripheral to host, software sets this bit when it removes the D+ pull-up, see Section 15.9. Hardware clears this bit when HNP_SUCCESS or HNP_FAILURE is set. constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> puRemoved{}; ///Reserved. Read value is undefined, only zero should be written. constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,11),Register::ReadWriteAccess,unsigned> reserved{}; ///Current timer count value. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,16),Register::ReadWriteAccess,unsigned> tmrCnt{}; ///Reserved. Read value is undefined, only zero should be written. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,2),Register::ReadWriteAccess,unsigned> reserved{}; } namespace UsbTmr{ ///<OTG Timer using Addr = Register::Address<0x2008c114,0x00000000,0x00000000,unsigned>; ///The TMR interrupt is set when TMR_CNT reaches this value. constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,0),Register::ReadWriteAccess,unsigned> timeoutCnt{}; ///Reserved. Read value is undefined, only zero should be written. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,16),Register::ReadWriteAccess,unsigned> reserved{}; } namespace UsbDevintst{ ///<USB Device Interrupt Status using Addr = Register::Address<0x2008c200,0x00000000,0x00000000,unsigned>; ///The frame interrupt occurs every 1 ms. This is used in isochronous packet transfers. constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> frame{}; ///Fast endpoint interrupt. If an Endpoint Interrupt Priority register (USBEpIntPri) bit is set, the corresponding endpoint interrupt will be routed to this bit. constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> epFast{}; ///Slow endpoints interrupt. If an Endpoint Interrupt Priority Register (USBEpIntPri) bit is not set, the corresponding endpoint interrupt will be routed to this bit. constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> epSlow{}; ///Set when USB Bus reset, USB suspend change or Connect change event occurs. Refer to Section 13.12.6 Set Device Status (Command: 0xFE, Data: write 1 byte) on page 366. constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> devStat{}; ///The command code register (USBCmdCode) is empty (New command can be written). constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> ccempty{}; ///Command data register (USBCmdData) is full (Data can be read now). constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> cdfull{}; ///The current packet in the endpoint buffer is transferred to the CPU. constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> rxendpkt{}; ///The number of data bytes transferred to the endpoint buffer equals the number of bytes programmed in the TxPacket length register (USBTxPLen). constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> txendpkt{}; ///Endpoints realized. Set when Realize Endpoint register (USBReEp) or MaxPacketSize register (USBMaxPSize) is updated and the corresponding operation is completed. constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> epRlzed{}; ///Error Interrupt. Any bus error interrupt from the USB device. Refer to Section 13.12.9 Read Error Status (Command: 0xFB, Data: read 1 byte) on page 368 constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> errInt{}; ///Reserved. The value read from a reserved bit is not defined. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,10),Register::ReadWriteAccess,unsigned> reserved{}; } namespace UsbDevinten{ ///<USB Device Interrupt Enable using Addr = Register::Address<0x2008c204,0x00000000,0x00000000,unsigned>; ///0 = No interrupt is generated. 1 = An interrupt will be generated when the corresponding bit in the Device Interrupt Status (USBDevIntSt) register (Table 261) is set. By default, the interrupt is routed to the USB_INT_REQ_LP interrupt line. Optionally, either the EP_FAST or FRAME interrupt may be routed to the USB_INT_REQ_HP interrupt line by changing the value of USBDevIntPri. constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> frameen{}; ///0 = No interrupt is generated. 1 = An interrupt will be generated when the corresponding bit in the Device Interrupt Status (USBDevIntSt) register (Table 261) is set. By default, the interrupt is routed to the USB_INT_REQ_LP interrupt line. Optionally, either the EP_FAST or FRAME interrupt may be routed to the USB_INT_REQ_HP interrupt line by changing the value of USBDevIntPri. constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> epFasten{}; ///0 = No interrupt is generated. 1 = An interrupt will be generated when the corresponding bit in the Device Interrupt Status (USBDevIntSt) register (Table 261) is set. By default, the interrupt is routed to the USB_INT_REQ_LP interrupt line. Optionally, either the EP_FAST or FRAME interrupt may be routed to the USB_INT_REQ_HP interrupt line by changing the value of USBDevIntPri. constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> epSlowen{}; ///0 = No interrupt is generated. 1 = An interrupt will be generated when the corresponding bit in the Device Interrupt Status (USBDevIntSt) register (Table 261) is set. By default, the interrupt is routed to the USB_INT_REQ_LP interrupt line. Optionally, either the EP_FAST or FRAME interrupt may be routed to the USB_INT_REQ_HP interrupt line by changing the value of USBDevIntPri. constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> devStaten{}; ///0 = No interrupt is generated. 1 = An interrupt will be generated when the corresponding bit in the Device Interrupt Status (USBDevIntSt) register (Table 261) is set. By default, the interrupt is routed to the USB_INT_REQ_LP interrupt line. Optionally, either the EP_FAST or FRAME interrupt may be routed to the USB_INT_REQ_HP interrupt line by changing the value of USBDevIntPri. constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> ccemptyen{}; ///0 = No interrupt is generated. 1 = An interrupt will be generated when the corresponding bit in the Device Interrupt Status (USBDevIntSt) register (Table 261) is set. By default, the interrupt is routed to the USB_INT_REQ_LP interrupt line. Optionally, either the EP_FAST or FRAME interrupt may be routed to the USB_INT_REQ_HP interrupt line by changing the value of USBDevIntPri. constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> cdfullen{}; ///0 = No interrupt is generated. 1 = An interrupt will be generated when the corresponding bit in the Device Interrupt Status (USBDevIntSt) register (Table 261) is set. By default, the interrupt is routed to the USB_INT_REQ_LP interrupt line. Optionally, either the EP_FAST or FRAME interrupt may be routed to the USB_INT_REQ_HP interrupt line by changing the value of USBDevIntPri. constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> rxendpkten{}; ///0 = No interrupt is generated. 1 = An interrupt will be generated when the corresponding bit in the Device Interrupt Status (USBDevIntSt) register (Table 261) is set. By default, the interrupt is routed to the USB_INT_REQ_LP interrupt line. Optionally, either the EP_FAST or FRAME interrupt may be routed to the USB_INT_REQ_HP interrupt line by changing the value of USBDevIntPri. constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> txendpkten{}; ///0 = No interrupt is generated. 1 = An interrupt will be generated when the corresponding bit in the Device Interrupt Status (USBDevIntSt) register (Table 261) is set. By default, the interrupt is routed to the USB_INT_REQ_LP interrupt line. Optionally, either the EP_FAST or FRAME interrupt may be routed to the USB_INT_REQ_HP interrupt line by changing the value of USBDevIntPri. constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> epRlzeden{}; ///0 = No interrupt is generated. 1 = An interrupt will be generated when the corresponding bit in the Device Interrupt Status (USBDevIntSt) register (Table 261) is set. By default, the interrupt is routed to the USB_INT_REQ_LP interrupt line. Optionally, either the EP_FAST or FRAME interrupt may be routed to the USB_INT_REQ_HP interrupt line by changing the value of USBDevIntPri. constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> errInten{}; ///Reserved constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,10),Register::ReadWriteAccess,unsigned> reserved{}; } namespace UsbDevintclr{ ///<USB Device Interrupt Clear using Addr = Register::Address<0x2008c208,0x00000000,0x00000000,unsigned>; ///0 = No effect. 1 = The corresponding bit in USBDevIntSt (Section 13.10.3.2) is cleared. constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> frameclr{}; ///0 = No effect. 1 = The corresponding bit in USBDevIntSt (Section 13.10.3.2) is cleared. constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> epFastclr{}; ///0 = No effect. 1 = The corresponding bit in USBDevIntSt (Section 13.10.3.2) is cleared. constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> epSlowclr{}; ///0 = No effect. 1 = The corresponding bit in USBDevIntSt (Section 13.10.3.2) is cleared. constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> devStatclr{}; ///0 = No effect. 1 = The corresponding bit in USBDevIntSt (Section 13.10.3.2) is cleared. constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> ccemptyclr{}; ///0 = No effect. 1 = The corresponding bit in USBDevIntSt (Section 13.10.3.2) is cleared. constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> cdfullclr{}; ///0 = No effect. 1 = The corresponding bit in USBDevIntSt (Section 13.10.3.2) is cleared. constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> rxendpktclr{}; ///0 = No effect. 1 = The corresponding bit in USBDevIntSt (Section 13.10.3.2) is cleared. constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> txendpktclr{}; ///0 = No effect. 1 = The corresponding bit in USBDevIntSt (Section 13.10.3.2) is cleared. constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> epRlzedclr{}; ///0 = No effect. 1 = The corresponding bit in USBDevIntSt (Section 13.10.3.2) is cleared. constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> errIntclr{}; ///Reserved constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,10),Register::ReadWriteAccess,unsigned> reserved{}; } namespace UsbDevintset{ ///<USB Device Interrupt Set using Addr = Register::Address<0x2008c20c,0x00000000,0x00000000,unsigned>; ///0 = No effect. 1 = The corresponding bit in USBDevIntSt (Section 13.10.3.2) is set. constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> frameset{}; ///0 = No effect. 1 = The corresponding bit in USBDevIntSt (Section 13.10.3.2) is set. constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> epFastset{}; ///0 = No effect. 1 = The corresponding bit in USBDevIntSt (Section 13.10.3.2) is set. constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> epSlowset{}; ///0 = No effect. 1 = The corresponding bit in USBDevIntSt (Section 13.10.3.2) is set. constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> devStatset{}; ///0 = No effect. 1 = The corresponding bit in USBDevIntSt (Section 13.10.3.2) is set. constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> ccemptyset{}; ///0 = No effect. 1 = The corresponding bit in USBDevIntSt (Section 13.10.3.2) is set. constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> cdfullset{}; ///0 = No effect. 1 = The corresponding bit in USBDevIntSt (Section 13.10.3.2) is set. constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> rxendpktset{}; ///0 = No effect. 1 = The corresponding bit in USBDevIntSt (Section 13.10.3.2) is set. constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> txendpktset{}; ///0 = No effect. 1 = The corresponding bit in USBDevIntSt (Section 13.10.3.2) is set. constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> epRlzedset{}; ///0 = No effect. 1 = The corresponding bit in USBDevIntSt (Section 13.10.3.2) is set. constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> errIntset{}; ///Reserved constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,10),Register::ReadWriteAccess,unsigned> reserved{}; } namespace UsbDevintpri{ ///<USB Device Interrupt Priority using Addr = Register::Address<0x2008c22c,0x00000000,0x00000000,unsigned>; ///Frame interrupt routing enum class FrameVal { lp=0x00000000, ///<FRAME interrupt is routed to USB_INT_REQ_LP. hp=0x00000001, ///<FRAME interrupt is routed to USB_INT_REQ_HP. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,FrameVal> frame{}; namespace FrameValC{ constexpr Register::FieldValue<decltype(frame)::Type,FrameVal::lp> lp{}; constexpr Register::FieldValue<decltype(frame)::Type,FrameVal::hp> hp{}; } ///Fast endpoint interrupt routing enum class EpfastVal { lp=0x00000000, ///<EP_FAST interrupt is routed to USB_INT_REQ_LP. hp=0x00000001, ///<EP_FAST interrupt is routed to USB_INT_REQ_HP. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,EpfastVal> epFast{}; namespace EpfastValC{ constexpr Register::FieldValue<decltype(epFast)::Type,EpfastVal::lp> lp{}; constexpr Register::FieldValue<decltype(epFast)::Type,EpfastVal::hp> hp{}; } ///Reserved. Read value is undefined, only zero should be written. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,2),Register::ReadWriteAccess,unsigned> reserved{}; } namespace UsbEpintst{ ///<USB Endpoint Interrupt Status using Addr = Register::Address<0x2008c230,0x00000000,0x00000000,unsigned>; ///1 = Endpoint Data Received (bits 0, 2, 4, ..., 30) or Transmitted (bits 1, 3, 5, ..., 31) Interrupt received. constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> epst0{}; ///1 = Endpoint Data Received (bits 0, 2, 4, ..., 30) or Transmitted (bits 1, 3, 5, ..., 31) Interrupt received. constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> epst1{}; ///1 = Endpoint Data Received (bits 0, 2, 4, ..., 30) or Transmitted (bits 1, 3, 5, ..., 31) Interrupt received. constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> epst2{}; ///1 = Endpoint Data Received (bits 0, 2, 4, ..., 30) or Transmitted (bits 1, 3, 5, ..., 31) Interrupt received. constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> epst3{}; ///1 = Endpoint Data Received (bits 0, 2, 4, ..., 30) or Transmitted (bits 1, 3, 5, ..., 31) Interrupt received. constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> epst4{}; ///1 = Endpoint Data Received (bits 0, 2, 4, ..., 30) or Transmitted (bits 1, 3, 5, ..., 31) Interrupt received. constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> epst5{}; ///1 = Endpoint Data Received (bits 0, 2, 4, ..., 30) or Transmitted (bits 1, 3, 5, ..., 31) Interrupt received. constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> epst6{}; ///1 = Endpoint Data Received (bits 0, 2, 4, ..., 30) or Transmitted (bits 1, 3, 5, ..., 31) Interrupt received. constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> epst7{}; ///1 = Endpoint Data Received (bits 0, 2, 4, ..., 30) or Transmitted (bits 1, 3, 5, ..., 31) Interrupt received. constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> epst8{}; ///1 = Endpoint Data Received (bits 0, 2, 4, ..., 30) or Transmitted (bits 1, 3, 5, ..., 31) Interrupt received. constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> epst9{}; ///1 = Endpoint Data Received (bits 0, 2, 4, ..., 30) or Transmitted (bits 1, 3, 5, ..., 31) Interrupt received. constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> epst10{}; ///1 = Endpoint Data Received (bits 0, 2, 4, ..., 30) or Transmitted (bits 1, 3, 5, ..., 31) Interrupt received. constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> epst11{}; ///1 = Endpoint Data Received (bits 0, 2, 4, ..., 30) or Transmitted (bits 1, 3, 5, ..., 31) Interrupt received. constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,unsigned> epst12{}; ///1 = Endpoint Data Received (bits 0, 2, 4, ..., 30) or Transmitted (bits 1, 3, 5, ..., 31) Interrupt received. constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,unsigned> epst13{}; ///1 = Endpoint Data Received (bits 0, 2, 4, ..., 30) or Transmitted (bits 1, 3, 5, ..., 31) Interrupt received. constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,unsigned> epst14{}; ///1 = Endpoint Data Received (bits 0, 2, 4, ..., 30) or Transmitted (bits 1, 3, 5, ..., 31) Interrupt received. constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> epst15{}; ///1 = Endpoint Data Received (bits 0, 2, 4, ..., 30) or Transmitted (bits 1, 3, 5, ..., 31) Interrupt received. constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,unsigned> epst16{}; ///1 = Endpoint Data Received (bits 0, 2, 4, ..., 30) or Transmitted (bits 1, 3, 5, ..., 31) Interrupt received. constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,17),Register::ReadWriteAccess,unsigned> epst17{}; ///1 = Endpoint Data Received (bits 0, 2, 4, ..., 30) or Transmitted (bits 1, 3, 5, ..., 31) Interrupt received. constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,18),Register::ReadWriteAccess,unsigned> epst18{}; ///1 = Endpoint Data Received (bits 0, 2, 4, ..., 30) or Transmitted (bits 1, 3, 5, ..., 31) Interrupt received. constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,19),Register::ReadWriteAccess,unsigned> epst19{}; ///1 = Endpoint Data Received (bits 0, 2, 4, ..., 30) or Transmitted (bits 1, 3, 5, ..., 31) Interrupt received. constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::ReadWriteAccess,unsigned> epst20{}; ///1 = Endpoint Data Received (bits 0, 2, 4, ..., 30) or Transmitted (bits 1, 3, 5, ..., 31) Interrupt received. constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,21),Register::ReadWriteAccess,unsigned> epst21{}; ///1 = Endpoint Data Received (bits 0, 2, 4, ..., 30) or Transmitted (bits 1, 3, 5, ..., 31) Interrupt received. constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::ReadWriteAccess,unsigned> epst22{}; ///1 = Endpoint Data Received (bits 0, 2, 4, ..., 30) or Transmitted (bits 1, 3, 5, ..., 31) Interrupt received. constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,23),Register::ReadWriteAccess,unsigned> epst23{}; ///1 = Endpoint Data Received (bits 0, 2, 4, ..., 30) or Transmitted (bits 1, 3, 5, ..., 31) Interrupt received. constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,24),Register::ReadWriteAccess,unsigned> epst24{}; ///1 = Endpoint Data Received (bits 0, 2, 4, ..., 30) or Transmitted (bits 1, 3, 5, ..., 31) Interrupt received. constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,25),Register::ReadWriteAccess,unsigned> epst25{}; ///1 = Endpoint Data Received (bits 0, 2, 4, ..., 30) or Transmitted (bits 1, 3, 5, ..., 31) Interrupt received. constexpr Register::FieldLocation<Addr,Register::maskFromRange(26,26),Register::ReadWriteAccess,unsigned> epst26{}; ///1 = Endpoint Data Received (bits 0, 2, 4, ..., 30) or Transmitted (bits 1, 3, 5, ..., 31) Interrupt received. constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,27),Register::ReadWriteAccess,unsigned> epst27{}; ///1 = Endpoint Data Received (bits 0, 2, 4, ..., 30) or Transmitted (bits 1, 3, 5, ..., 31) Interrupt received. constexpr Register::FieldLocation<Addr,Register::maskFromRange(28,28),Register::ReadWriteAccess,unsigned> epst28{}; ///1 = Endpoint Data Received (bits 0, 2, 4, ..., 30) or Transmitted (bits 1, 3, 5, ..., 31) Interrupt received. constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,29),Register::ReadWriteAccess,unsigned> epst29{}; ///1 = Endpoint Data Received (bits 0, 2, 4, ..., 30) or Transmitted (bits 1, 3, 5, ..., 31) Interrupt received. constexpr Register::FieldLocation<Addr,Register::maskFromRange(30,30),Register::ReadWriteAccess,unsigned> epst30{}; ///1 = Endpoint Data Received (bits 0, 2, 4, ..., 30) or Transmitted (bits 1, 3, 5, ..., 31) Interrupt received. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,31),Register::ReadWriteAccess,unsigned> epst31{}; } namespace UsbEpinten{ ///<USB Endpoint Interrupt Enable using Addr = Register::Address<0x2008c234,0x00000000,0x00000000,unsigned>; ///0= The corresponding bit in USBDMARSt is set when an interrupt occurs for this endpoint. 1 = The corresponding bit in USBEpIntSt is set when an interrupt occurs for this endpoint. Implies Slave mode for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> epen0{}; ///0= The corresponding bit in USBDMARSt is set when an interrupt occurs for this endpoint. 1 = The corresponding bit in USBEpIntSt is set when an interrupt occurs for this endpoint. Implies Slave mode for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> epen1{}; ///0= The corresponding bit in USBDMARSt is set when an interrupt occurs for this endpoint. 1 = The corresponding bit in USBEpIntSt is set when an interrupt occurs for this endpoint. Implies Slave mode for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> epen2{}; ///0= The corresponding bit in USBDMARSt is set when an interrupt occurs for this endpoint. 1 = The corresponding bit in USBEpIntSt is set when an interrupt occurs for this endpoint. Implies Slave mode for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> epen3{}; ///0= The corresponding bit in USBDMARSt is set when an interrupt occurs for this endpoint. 1 = The corresponding bit in USBEpIntSt is set when an interrupt occurs for this endpoint. Implies Slave mode for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> epen4{}; ///0= The corresponding bit in USBDMARSt is set when an interrupt occurs for this endpoint. 1 = The corresponding bit in USBEpIntSt is set when an interrupt occurs for this endpoint. Implies Slave mode for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> epen5{}; ///0= The corresponding bit in USBDMARSt is set when an interrupt occurs for this endpoint. 1 = The corresponding bit in USBEpIntSt is set when an interrupt occurs for this endpoint. Implies Slave mode for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> epen6{}; ///0= The corresponding bit in USBDMARSt is set when an interrupt occurs for this endpoint. 1 = The corresponding bit in USBEpIntSt is set when an interrupt occurs for this endpoint. Implies Slave mode for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> epen7{}; ///0= The corresponding bit in USBDMARSt is set when an interrupt occurs for this endpoint. 1 = The corresponding bit in USBEpIntSt is set when an interrupt occurs for this endpoint. Implies Slave mode for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> epen8{}; ///0= The corresponding bit in USBDMARSt is set when an interrupt occurs for this endpoint. 1 = The corresponding bit in USBEpIntSt is set when an interrupt occurs for this endpoint. Implies Slave mode for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> epen9{}; ///0= The corresponding bit in USBDMARSt is set when an interrupt occurs for this endpoint. 1 = The corresponding bit in USBEpIntSt is set when an interrupt occurs for this endpoint. Implies Slave mode for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> epen10{}; ///0= The corresponding bit in USBDMARSt is set when an interrupt occurs for this endpoint. 1 = The corresponding bit in USBEpIntSt is set when an interrupt occurs for this endpoint. Implies Slave mode for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> epen11{}; ///0= The corresponding bit in USBDMARSt is set when an interrupt occurs for this endpoint. 1 = The corresponding bit in USBEpIntSt is set when an interrupt occurs for this endpoint. Implies Slave mode for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,unsigned> epen12{}; ///0= The corresponding bit in USBDMARSt is set when an interrupt occurs for this endpoint. 1 = The corresponding bit in USBEpIntSt is set when an interrupt occurs for this endpoint. Implies Slave mode for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,unsigned> epen13{}; ///0= The corresponding bit in USBDMARSt is set when an interrupt occurs for this endpoint. 1 = The corresponding bit in USBEpIntSt is set when an interrupt occurs for this endpoint. Implies Slave mode for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,unsigned> epen14{}; ///0= The corresponding bit in USBDMARSt is set when an interrupt occurs for this endpoint. 1 = The corresponding bit in USBEpIntSt is set when an interrupt occurs for this endpoint. Implies Slave mode for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> epen15{}; ///0= The corresponding bit in USBDMARSt is set when an interrupt occurs for this endpoint. 1 = The corresponding bit in USBEpIntSt is set when an interrupt occurs for this endpoint. Implies Slave mode for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,unsigned> epen16{}; ///0= The corresponding bit in USBDMARSt is set when an interrupt occurs for this endpoint. 1 = The corresponding bit in USBEpIntSt is set when an interrupt occurs for this endpoint. Implies Slave mode for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,17),Register::ReadWriteAccess,unsigned> epen17{}; ///0= The corresponding bit in USBDMARSt is set when an interrupt occurs for this endpoint. 1 = The corresponding bit in USBEpIntSt is set when an interrupt occurs for this endpoint. Implies Slave mode for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,18),Register::ReadWriteAccess,unsigned> epen18{}; ///0= The corresponding bit in USBDMARSt is set when an interrupt occurs for this endpoint. 1 = The corresponding bit in USBEpIntSt is set when an interrupt occurs for this endpoint. Implies Slave mode for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,19),Register::ReadWriteAccess,unsigned> epen19{}; ///0= The corresponding bit in USBDMARSt is set when an interrupt occurs for this endpoint. 1 = The corresponding bit in USBEpIntSt is set when an interrupt occurs for this endpoint. Implies Slave mode for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::ReadWriteAccess,unsigned> epen20{}; ///0= The corresponding bit in USBDMARSt is set when an interrupt occurs for this endpoint. 1 = The corresponding bit in USBEpIntSt is set when an interrupt occurs for this endpoint. Implies Slave mode for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,21),Register::ReadWriteAccess,unsigned> epen21{}; ///0= The corresponding bit in USBDMARSt is set when an interrupt occurs for this endpoint. 1 = The corresponding bit in USBEpIntSt is set when an interrupt occurs for this endpoint. Implies Slave mode for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::ReadWriteAccess,unsigned> epen22{}; ///0= The corresponding bit in USBDMARSt is set when an interrupt occurs for this endpoint. 1 = The corresponding bit in USBEpIntSt is set when an interrupt occurs for this endpoint. Implies Slave mode for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,23),Register::ReadWriteAccess,unsigned> epen23{}; ///0= The corresponding bit in USBDMARSt is set when an interrupt occurs for this endpoint. 1 = The corresponding bit in USBEpIntSt is set when an interrupt occurs for this endpoint. Implies Slave mode for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,24),Register::ReadWriteAccess,unsigned> epen24{}; ///0= The corresponding bit in USBDMARSt is set when an interrupt occurs for this endpoint. 1 = The corresponding bit in USBEpIntSt is set when an interrupt occurs for this endpoint. Implies Slave mode for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,25),Register::ReadWriteAccess,unsigned> epen25{}; ///0= The corresponding bit in USBDMARSt is set when an interrupt occurs for this endpoint. 1 = The corresponding bit in USBEpIntSt is set when an interrupt occurs for this endpoint. Implies Slave mode for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(26,26),Register::ReadWriteAccess,unsigned> epen26{}; ///0= The corresponding bit in USBDMARSt is set when an interrupt occurs for this endpoint. 1 = The corresponding bit in USBEpIntSt is set when an interrupt occurs for this endpoint. Implies Slave mode for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,27),Register::ReadWriteAccess,unsigned> epen27{}; ///0= The corresponding bit in USBDMARSt is set when an interrupt occurs for this endpoint. 1 = The corresponding bit in USBEpIntSt is set when an interrupt occurs for this endpoint. Implies Slave mode for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(28,28),Register::ReadWriteAccess,unsigned> epen28{}; ///0= The corresponding bit in USBDMARSt is set when an interrupt occurs for this endpoint. 1 = The corresponding bit in USBEpIntSt is set when an interrupt occurs for this endpoint. Implies Slave mode for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,29),Register::ReadWriteAccess,unsigned> epen29{}; ///0= The corresponding bit in USBDMARSt is set when an interrupt occurs for this endpoint. 1 = The corresponding bit in USBEpIntSt is set when an interrupt occurs for this endpoint. Implies Slave mode for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(30,30),Register::ReadWriteAccess,unsigned> epen30{}; ///0= The corresponding bit in USBDMARSt is set when an interrupt occurs for this endpoint. 1 = The corresponding bit in USBEpIntSt is set when an interrupt occurs for this endpoint. Implies Slave mode for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,31),Register::ReadWriteAccess,unsigned> epen31{}; } namespace UsbEpintclr{ ///<USB Endpoint Interrupt Clear using Addr = Register::Address<0x2008c238,0x00000000,0x00000000,unsigned>; ///0 = No effect. 1 = Clears the corresponding bit in USBEpIntSt, by executing the SIE Select Endpoint/Clear Interrupt command for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> epclr0{}; ///0 = No effect. 1 = Clears the corresponding bit in USBEpIntSt, by executing the SIE Select Endpoint/Clear Interrupt command for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> epclr1{}; ///0 = No effect. 1 = Clears the corresponding bit in USBEpIntSt, by executing the SIE Select Endpoint/Clear Interrupt command for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> epclr2{}; ///0 = No effect. 1 = Clears the corresponding bit in USBEpIntSt, by executing the SIE Select Endpoint/Clear Interrupt command for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> epclr3{}; ///0 = No effect. 1 = Clears the corresponding bit in USBEpIntSt, by executing the SIE Select Endpoint/Clear Interrupt command for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> epclr4{}; ///0 = No effect. 1 = Clears the corresponding bit in USBEpIntSt, by executing the SIE Select Endpoint/Clear Interrupt command for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> epclr5{}; ///0 = No effect. 1 = Clears the corresponding bit in USBEpIntSt, by executing the SIE Select Endpoint/Clear Interrupt command for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> epclr6{}; ///0 = No effect. 1 = Clears the corresponding bit in USBEpIntSt, by executing the SIE Select Endpoint/Clear Interrupt command for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> epclr7{}; ///0 = No effect. 1 = Clears the corresponding bit in USBEpIntSt, by executing the SIE Select Endpoint/Clear Interrupt command for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> epclr8{}; ///0 = No effect. 1 = Clears the corresponding bit in USBEpIntSt, by executing the SIE Select Endpoint/Clear Interrupt command for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> epclr9{}; ///0 = No effect. 1 = Clears the corresponding bit in USBEpIntSt, by executing the SIE Select Endpoint/Clear Interrupt command for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> epclr10{}; ///0 = No effect. 1 = Clears the corresponding bit in USBEpIntSt, by executing the SIE Select Endpoint/Clear Interrupt command for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> epclr11{}; ///0 = No effect. 1 = Clears the corresponding bit in USBEpIntSt, by executing the SIE Select Endpoint/Clear Interrupt command for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,unsigned> epclr12{}; ///0 = No effect. 1 = Clears the corresponding bit in USBEpIntSt, by executing the SIE Select Endpoint/Clear Interrupt command for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,unsigned> epclr13{}; ///0 = No effect. 1 = Clears the corresponding bit in USBEpIntSt, by executing the SIE Select Endpoint/Clear Interrupt command for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,unsigned> epclr14{}; ///0 = No effect. 1 = Clears the corresponding bit in USBEpIntSt, by executing the SIE Select Endpoint/Clear Interrupt command for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> epclr15{}; ///0 = No effect. 1 = Clears the corresponding bit in USBEpIntSt, by executing the SIE Select Endpoint/Clear Interrupt command for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,unsigned> epclr16{}; ///0 = No effect. 1 = Clears the corresponding bit in USBEpIntSt, by executing the SIE Select Endpoint/Clear Interrupt command for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,17),Register::ReadWriteAccess,unsigned> epclr17{}; ///0 = No effect. 1 = Clears the corresponding bit in USBEpIntSt, by executing the SIE Select Endpoint/Clear Interrupt command for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,18),Register::ReadWriteAccess,unsigned> epclr18{}; ///0 = No effect. 1 = Clears the corresponding bit in USBEpIntSt, by executing the SIE Select Endpoint/Clear Interrupt command for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,19),Register::ReadWriteAccess,unsigned> epclr19{}; ///0 = No effect. 1 = Clears the corresponding bit in USBEpIntSt, by executing the SIE Select Endpoint/Clear Interrupt command for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::ReadWriteAccess,unsigned> epclr20{}; ///0 = No effect. 1 = Clears the corresponding bit in USBEpIntSt, by executing the SIE Select Endpoint/Clear Interrupt command for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,21),Register::ReadWriteAccess,unsigned> epclr21{}; ///0 = No effect. 1 = Clears the corresponding bit in USBEpIntSt, by executing the SIE Select Endpoint/Clear Interrupt command for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::ReadWriteAccess,unsigned> epclr22{}; ///0 = No effect. 1 = Clears the corresponding bit in USBEpIntSt, by executing the SIE Select Endpoint/Clear Interrupt command for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,23),Register::ReadWriteAccess,unsigned> epclr23{}; ///0 = No effect. 1 = Clears the corresponding bit in USBEpIntSt, by executing the SIE Select Endpoint/Clear Interrupt command for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,24),Register::ReadWriteAccess,unsigned> epclr24{}; ///0 = No effect. 1 = Clears the corresponding bit in USBEpIntSt, by executing the SIE Select Endpoint/Clear Interrupt command for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,25),Register::ReadWriteAccess,unsigned> epclr25{}; ///0 = No effect. 1 = Clears the corresponding bit in USBEpIntSt, by executing the SIE Select Endpoint/Clear Interrupt command for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(26,26),Register::ReadWriteAccess,unsigned> epclr26{}; ///0 = No effect. 1 = Clears the corresponding bit in USBEpIntSt, by executing the SIE Select Endpoint/Clear Interrupt command for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,27),Register::ReadWriteAccess,unsigned> epclr27{}; ///0 = No effect. 1 = Clears the corresponding bit in USBEpIntSt, by executing the SIE Select Endpoint/Clear Interrupt command for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(28,28),Register::ReadWriteAccess,unsigned> epclr28{}; ///0 = No effect. 1 = Clears the corresponding bit in USBEpIntSt, by executing the SIE Select Endpoint/Clear Interrupt command for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,29),Register::ReadWriteAccess,unsigned> epclr29{}; ///0 = No effect. 1 = Clears the corresponding bit in USBEpIntSt, by executing the SIE Select Endpoint/Clear Interrupt command for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(30,30),Register::ReadWriteAccess,unsigned> epclr30{}; ///0 = No effect. 1 = Clears the corresponding bit in USBEpIntSt, by executing the SIE Select Endpoint/Clear Interrupt command for this endpoint. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,31),Register::ReadWriteAccess,unsigned> epclr31{}; } namespace UsbEpintset{ ///<USB Endpoint Interrupt Set using Addr = Register::Address<0x2008c23c,0x00000000,0x00000000,unsigned>; ///0 = No effect. 1 = Sets the corresponding bit in USBEpIntSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> epset0{}; ///0 = No effect. 1 = Sets the corresponding bit in USBEpIntSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> epset1{}; ///0 = No effect. 1 = Sets the corresponding bit in USBEpIntSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> epset2{}; ///0 = No effect. 1 = Sets the corresponding bit in USBEpIntSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> epset3{}; ///0 = No effect. 1 = Sets the corresponding bit in USBEpIntSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> epset4{}; ///0 = No effect. 1 = Sets the corresponding bit in USBEpIntSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> epset5{}; ///0 = No effect. 1 = Sets the corresponding bit in USBEpIntSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> epset6{}; ///0 = No effect. 1 = Sets the corresponding bit in USBEpIntSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> epset7{}; ///0 = No effect. 1 = Sets the corresponding bit in USBEpIntSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> epset8{}; ///0 = No effect. 1 = Sets the corresponding bit in USBEpIntSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> epset9{}; ///0 = No effect. 1 = Sets the corresponding bit in USBEpIntSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> epset10{}; ///0 = No effect. 1 = Sets the corresponding bit in USBEpIntSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> epset11{}; ///0 = No effect. 1 = Sets the corresponding bit in USBEpIntSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,unsigned> epset12{}; ///0 = No effect. 1 = Sets the corresponding bit in USBEpIntSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,unsigned> epset13{}; ///0 = No effect. 1 = Sets the corresponding bit in USBEpIntSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,unsigned> epset14{}; ///0 = No effect. 1 = Sets the corresponding bit in USBEpIntSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> epset15{}; ///0 = No effect. 1 = Sets the corresponding bit in USBEpIntSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,unsigned> epset16{}; ///0 = No effect. 1 = Sets the corresponding bit in USBEpIntSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,17),Register::ReadWriteAccess,unsigned> epset17{}; ///0 = No effect. 1 = Sets the corresponding bit in USBEpIntSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,18),Register::ReadWriteAccess,unsigned> epset18{}; ///0 = No effect. 1 = Sets the corresponding bit in USBEpIntSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,19),Register::ReadWriteAccess,unsigned> epset19{}; ///0 = No effect. 1 = Sets the corresponding bit in USBEpIntSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::ReadWriteAccess,unsigned> epset20{}; ///0 = No effect. 1 = Sets the corresponding bit in USBEpIntSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,21),Register::ReadWriteAccess,unsigned> epset21{}; ///0 = No effect. 1 = Sets the corresponding bit in USBEpIntSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::ReadWriteAccess,unsigned> epset22{}; ///0 = No effect. 1 = Sets the corresponding bit in USBEpIntSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,23),Register::ReadWriteAccess,unsigned> epset23{}; ///0 = No effect. 1 = Sets the corresponding bit in USBEpIntSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,24),Register::ReadWriteAccess,unsigned> epset24{}; ///0 = No effect. 1 = Sets the corresponding bit in USBEpIntSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,25),Register::ReadWriteAccess,unsigned> epset25{}; ///0 = No effect. 1 = Sets the corresponding bit in USBEpIntSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(26,26),Register::ReadWriteAccess,unsigned> epset26{}; ///0 = No effect. 1 = Sets the corresponding bit in USBEpIntSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,27),Register::ReadWriteAccess,unsigned> epset27{}; ///0 = No effect. 1 = Sets the corresponding bit in USBEpIntSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(28,28),Register::ReadWriteAccess,unsigned> epset28{}; ///0 = No effect. 1 = Sets the corresponding bit in USBEpIntSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,29),Register::ReadWriteAccess,unsigned> epset29{}; ///0 = No effect. 1 = Sets the corresponding bit in USBEpIntSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(30,30),Register::ReadWriteAccess,unsigned> epset30{}; ///0 = No effect. 1 = Sets the corresponding bit in USBEpIntSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,31),Register::ReadWriteAccess,unsigned> epset31{}; } namespace UsbEpintpri{ ///<USB Endpoint Priority using Addr = Register::Address<0x2008c240,0x00000000,0x00000000,unsigned>; ///0 = The corresponding interrupt is routed to the EP_SLOW bit of USBDevIntSt 1 = The corresponding interrupt is routed to the EP_FAST bit of USBDevIntSt constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> eppri0{}; ///0 = The corresponding interrupt is routed to the EP_SLOW bit of USBDevIntSt 1 = The corresponding interrupt is routed to the EP_FAST bit of USBDevIntSt constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> eppri1{}; ///0 = The corresponding interrupt is routed to the EP_SLOW bit of USBDevIntSt 1 = The corresponding interrupt is routed to the EP_FAST bit of USBDevIntSt constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> eppri2{}; ///0 = The corresponding interrupt is routed to the EP_SLOW bit of USBDevIntSt 1 = The corresponding interrupt is routed to the EP_FAST bit of USBDevIntSt constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> eppri3{}; ///0 = The corresponding interrupt is routed to the EP_SLOW bit of USBDevIntSt 1 = The corresponding interrupt is routed to the EP_FAST bit of USBDevIntSt constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> eppri4{}; ///0 = The corresponding interrupt is routed to the EP_SLOW bit of USBDevIntSt 1 = The corresponding interrupt is routed to the EP_FAST bit of USBDevIntSt constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> eppri5{}; ///0 = The corresponding interrupt is routed to the EP_SLOW bit of USBDevIntSt 1 = The corresponding interrupt is routed to the EP_FAST bit of USBDevIntSt constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> eppri6{}; ///0 = The corresponding interrupt is routed to the EP_SLOW bit of USBDevIntSt 1 = The corresponding interrupt is routed to the EP_FAST bit of USBDevIntSt constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> eppri7{}; ///0 = The corresponding interrupt is routed to the EP_SLOW bit of USBDevIntSt 1 = The corresponding interrupt is routed to the EP_FAST bit of USBDevIntSt constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> eppri8{}; ///0 = The corresponding interrupt is routed to the EP_SLOW bit of USBDevIntSt 1 = The corresponding interrupt is routed to the EP_FAST bit of USBDevIntSt constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> eppri9{}; ///0 = The corresponding interrupt is routed to the EP_SLOW bit of USBDevIntSt 1 = The corresponding interrupt is routed to the EP_FAST bit of USBDevIntSt constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> eppri10{}; ///0 = The corresponding interrupt is routed to the EP_SLOW bit of USBDevIntSt 1 = The corresponding interrupt is routed to the EP_FAST bit of USBDevIntSt constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> eppri11{}; ///0 = The corresponding interrupt is routed to the EP_SLOW bit of USBDevIntSt 1 = The corresponding interrupt is routed to the EP_FAST bit of USBDevIntSt constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,unsigned> eppri12{}; ///0 = The corresponding interrupt is routed to the EP_SLOW bit of USBDevIntSt 1 = The corresponding interrupt is routed to the EP_FAST bit of USBDevIntSt constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,unsigned> eppri13{}; ///0 = The corresponding interrupt is routed to the EP_SLOW bit of USBDevIntSt 1 = The corresponding interrupt is routed to the EP_FAST bit of USBDevIntSt constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,unsigned> eppri14{}; ///0 = The corresponding interrupt is routed to the EP_SLOW bit of USBDevIntSt 1 = The corresponding interrupt is routed to the EP_FAST bit of USBDevIntSt constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> eppri15{}; ///0 = The corresponding interrupt is routed to the EP_SLOW bit of USBDevIntSt 1 = The corresponding interrupt is routed to the EP_FAST bit of USBDevIntSt constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,unsigned> eppri16{}; ///0 = The corresponding interrupt is routed to the EP_SLOW bit of USBDevIntSt 1 = The corresponding interrupt is routed to the EP_FAST bit of USBDevIntSt constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,17),Register::ReadWriteAccess,unsigned> eppri17{}; ///0 = The corresponding interrupt is routed to the EP_SLOW bit of USBDevIntSt 1 = The corresponding interrupt is routed to the EP_FAST bit of USBDevIntSt constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,18),Register::ReadWriteAccess,unsigned> eppri18{}; ///0 = The corresponding interrupt is routed to the EP_SLOW bit of USBDevIntSt 1 = The corresponding interrupt is routed to the EP_FAST bit of USBDevIntSt constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,19),Register::ReadWriteAccess,unsigned> eppri19{}; ///0 = The corresponding interrupt is routed to the EP_SLOW bit of USBDevIntSt 1 = The corresponding interrupt is routed to the EP_FAST bit of USBDevIntSt constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::ReadWriteAccess,unsigned> eppri20{}; ///0 = The corresponding interrupt is routed to the EP_SLOW bit of USBDevIntSt 1 = The corresponding interrupt is routed to the EP_FAST bit of USBDevIntSt constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,21),Register::ReadWriteAccess,unsigned> eppri21{}; ///0 = The corresponding interrupt is routed to the EP_SLOW bit of USBDevIntSt 1 = The corresponding interrupt is routed to the EP_FAST bit of USBDevIntSt constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::ReadWriteAccess,unsigned> eppri22{}; ///0 = The corresponding interrupt is routed to the EP_SLOW bit of USBDevIntSt 1 = The corresponding interrupt is routed to the EP_FAST bit of USBDevIntSt constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,23),Register::ReadWriteAccess,unsigned> eppri23{}; ///0 = The corresponding interrupt is routed to the EP_SLOW bit of USBDevIntSt 1 = The corresponding interrupt is routed to the EP_FAST bit of USBDevIntSt constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,24),Register::ReadWriteAccess,unsigned> eppri24{}; ///0 = The corresponding interrupt is routed to the EP_SLOW bit of USBDevIntSt 1 = The corresponding interrupt is routed to the EP_FAST bit of USBDevIntSt constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,25),Register::ReadWriteAccess,unsigned> eppri25{}; ///0 = The corresponding interrupt is routed to the EP_SLOW bit of USBDevIntSt 1 = The corresponding interrupt is routed to the EP_FAST bit of USBDevIntSt constexpr Register::FieldLocation<Addr,Register::maskFromRange(26,26),Register::ReadWriteAccess,unsigned> eppri26{}; ///0 = The corresponding interrupt is routed to the EP_SLOW bit of USBDevIntSt 1 = The corresponding interrupt is routed to the EP_FAST bit of USBDevIntSt constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,27),Register::ReadWriteAccess,unsigned> eppri27{}; ///0 = The corresponding interrupt is routed to the EP_SLOW bit of USBDevIntSt 1 = The corresponding interrupt is routed to the EP_FAST bit of USBDevIntSt constexpr Register::FieldLocation<Addr,Register::maskFromRange(28,28),Register::ReadWriteAccess,unsigned> eppri28{}; ///0 = The corresponding interrupt is routed to the EP_SLOW bit of USBDevIntSt 1 = The corresponding interrupt is routed to the EP_FAST bit of USBDevIntSt constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,29),Register::ReadWriteAccess,unsigned> eppri29{}; ///0 = The corresponding interrupt is routed to the EP_SLOW bit of USBDevIntSt 1 = The corresponding interrupt is routed to the EP_FAST bit of USBDevIntSt constexpr Register::FieldLocation<Addr,Register::maskFromRange(30,30),Register::ReadWriteAccess,unsigned> eppri30{}; ///0 = The corresponding interrupt is routed to the EP_SLOW bit of USBDevIntSt 1 = The corresponding interrupt is routed to the EP_FAST bit of USBDevIntSt constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,31),Register::ReadWriteAccess,unsigned> eppri31{}; } namespace UsbReep{ ///<USB Realize Endpoint using Addr = Register::Address<0x2008c244,0x00000000,0x00000000,unsigned>; ///0 = Endpoint EPxx is not realized. 1 = Endpoint EPxx is realized. constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> epr0{}; ///0 = Endpoint EPxx is not realized. 1 = Endpoint EPxx is realized. constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> epr1{}; ///0 = Endpoint EPxx is not realized. 1 = Endpoint EPxx is realized. constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> epr2{}; ///0 = Endpoint EPxx is not realized. 1 = Endpoint EPxx is realized. constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> epr3{}; ///0 = Endpoint EPxx is not realized. 1 = Endpoint EPxx is realized. constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> epr4{}; ///0 = Endpoint EPxx is not realized. 1 = Endpoint EPxx is realized. constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> epr5{}; ///0 = Endpoint EPxx is not realized. 1 = Endpoint EPxx is realized. constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> epr6{}; ///0 = Endpoint EPxx is not realized. 1 = Endpoint EPxx is realized. constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> epr7{}; ///0 = Endpoint EPxx is not realized. 1 = Endpoint EPxx is realized. constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> epr8{}; ///0 = Endpoint EPxx is not realized. 1 = Endpoint EPxx is realized. constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> epr9{}; ///0 = Endpoint EPxx is not realized. 1 = Endpoint EPxx is realized. constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> epr10{}; ///0 = Endpoint EPxx is not realized. 1 = Endpoint EPxx is realized. constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> epr11{}; ///0 = Endpoint EPxx is not realized. 1 = Endpoint EPxx is realized. constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,unsigned> epr12{}; ///0 = Endpoint EPxx is not realized. 1 = Endpoint EPxx is realized. constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,unsigned> epr13{}; ///0 = Endpoint EPxx is not realized. 1 = Endpoint EPxx is realized. constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,unsigned> epr14{}; ///0 = Endpoint EPxx is not realized. 1 = Endpoint EPxx is realized. constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> epr15{}; ///0 = Endpoint EPxx is not realized. 1 = Endpoint EPxx is realized. constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,unsigned> epr16{}; ///0 = Endpoint EPxx is not realized. 1 = Endpoint EPxx is realized. constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,17),Register::ReadWriteAccess,unsigned> epr17{}; ///0 = Endpoint EPxx is not realized. 1 = Endpoint EPxx is realized. constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,18),Register::ReadWriteAccess,unsigned> epr18{}; ///0 = Endpoint EPxx is not realized. 1 = Endpoint EPxx is realized. constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,19),Register::ReadWriteAccess,unsigned> epr19{}; ///0 = Endpoint EPxx is not realized. 1 = Endpoint EPxx is realized. constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::ReadWriteAccess,unsigned> epr20{}; ///0 = Endpoint EPxx is not realized. 1 = Endpoint EPxx is realized. constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,21),Register::ReadWriteAccess,unsigned> epr21{}; ///0 = Endpoint EPxx is not realized. 1 = Endpoint EPxx is realized. constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::ReadWriteAccess,unsigned> epr22{}; ///0 = Endpoint EPxx is not realized. 1 = Endpoint EPxx is realized. constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,23),Register::ReadWriteAccess,unsigned> epr23{}; ///0 = Endpoint EPxx is not realized. 1 = Endpoint EPxx is realized. constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,24),Register::ReadWriteAccess,unsigned> epr24{}; ///0 = Endpoint EPxx is not realized. 1 = Endpoint EPxx is realized. constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,25),Register::ReadWriteAccess,unsigned> epr25{}; ///0 = Endpoint EPxx is not realized. 1 = Endpoint EPxx is realized. constexpr Register::FieldLocation<Addr,Register::maskFromRange(26,26),Register::ReadWriteAccess,unsigned> epr26{}; ///0 = Endpoint EPxx is not realized. 1 = Endpoint EPxx is realized. constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,27),Register::ReadWriteAccess,unsigned> epr27{}; ///0 = Endpoint EPxx is not realized. 1 = Endpoint EPxx is realized. constexpr Register::FieldLocation<Addr,Register::maskFromRange(28,28),Register::ReadWriteAccess,unsigned> epr28{}; ///0 = Endpoint EPxx is not realized. 1 = Endpoint EPxx is realized. constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,29),Register::ReadWriteAccess,unsigned> epr29{}; ///0 = Endpoint EPxx is not realized. 1 = Endpoint EPxx is realized. constexpr Register::FieldLocation<Addr,Register::maskFromRange(30,30),Register::ReadWriteAccess,unsigned> epr30{}; ///0 = Endpoint EPxx is not realized. 1 = Endpoint EPxx is realized. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,31),Register::ReadWriteAccess,unsigned> epr31{}; } namespace UsbEpin{ ///<USB Endpoint Index using Addr = Register::Address<0x2008c248,0x00000000,0x00000000,unsigned>; ///Physical endpoint number (0-31) constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,0),Register::ReadWriteAccess,unsigned> phyEp{}; ///Reserved. Read value is undefined, only zero should be written. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,5),Register::ReadWriteAccess,unsigned> reserved{}; } namespace UsbMaxpsize{ ///<USB MaxPacketSize using Addr = Register::Address<0x2008c24c,0x00000000,0x00000000,unsigned>; ///The maximum packet size value. constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,0),Register::ReadWriteAccess,unsigned> mps{}; ///Reserved. Read value is undefined, only zero should be written. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,10),Register::ReadWriteAccess,unsigned> reserved{}; } namespace UsbRxdata{ ///<USB Receive Data using Addr = Register::Address<0x2008c218,0x00000000,0x00000000,unsigned>; ///Data received. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> rxData{}; } namespace UsbRxplen{ ///<USB Receive Packet Length using Addr = Register::Address<0x2008c0dc,0x00000000,0x00000000,unsigned>; ///The remaining number of bytes to be read from the currently selected endpoint's buffer. When this field decrements to 0, the RxENDPKT bit will be set in USBDevIntSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,0),Register::ReadWriteAccess,unsigned> pktLngth{}; ///Data valid. This bit is useful for isochronous endpoints. Non-isochronous endpoints do not raise an interrupt when an erroneous data packet is received. But invalid data packet can be produced with a bus reset. For isochronous endpoints, data transfer will happen even if an erroneous packet is received. In this case DV bit will not be set for the packet. enum class DvVal { dataIsInvalid=0x00000000, ///<Data is invalid. dataIsValid=0x00000001, ///<Data is valid. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,DvVal> dv{}; namespace DvValC{ constexpr Register::FieldValue<decltype(dv)::Type,DvVal::dataIsInvalid> dataIsInvalid{}; constexpr Register::FieldValue<decltype(dv)::Type,DvVal::dataIsValid> dataIsValid{}; } ///The PKT_LNGTH field is valid and the packet is ready for reading. constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> pktRdy{}; ///Reserved. The value read from a reserved bit is not defined. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,12),Register::ReadWriteAccess,unsigned> reserved{}; } namespace UsbTxdata{ ///<USB Transmit Data using Addr = Register::Address<0x2008c21c,0x00000000,0x00000000,unsigned>; ///Transmit Data. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> txData{}; } namespace UsbTxplen{ ///<USB Transmit Packet Length using Addr = Register::Address<0x2008c224,0x00000000,0x00000000,unsigned>; ///The remaining number of bytes to be written to the selected endpoint buffer. This field is decremented by 4 by hardware after each write to USBTxData. When this field decrements to 0, the TxENDPKT bit will be set in USBDevIntSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,0),Register::ReadWriteAccess,unsigned> pktLngth{}; ///Reserved. Read value is undefined, only zero should be written. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,10),Register::ReadWriteAccess,unsigned> reserved{}; } namespace UsbCtrl{ ///<USB Control using Addr = Register::Address<0x2008c228,0x00000000,0x00000000,unsigned>; ///Read mode control. Enables reading data from the OUT endpoint buffer for the endpoint specified in the LOG_ENDPOINT field using the USBRxData register. This bit is cleared by hardware when the last word of the current packet is read from USBRxData. enum class RdenVal { disabled=0x00000000, ///<Disabled. enabled=0x00000001, ///<Enabled. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,RdenVal> rdEn{}; namespace RdenValC{ constexpr Register::FieldValue<decltype(rdEn)::Type,RdenVal::disabled> disabled{}; constexpr Register::FieldValue<decltype(rdEn)::Type,RdenVal::enabled> enabled{}; } ///Write mode control. Enables writing data to the IN endpoint buffer for the endpoint specified in the LOG_ENDPOINT field using the USBTxData register. This bit is cleared by hardware when the number of bytes in USBTxLen have been sent. enum class WrenVal { disabled=0x00000000, ///<Disabled. enabled=0x00000001, ///<Enabled. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,WrenVal> wrEn{}; namespace WrenValC{ constexpr Register::FieldValue<decltype(wrEn)::Type,WrenVal::disabled> disabled{}; constexpr Register::FieldValue<decltype(wrEn)::Type,WrenVal::enabled> enabled{}; } ///Logical Endpoint number. constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,2),Register::ReadWriteAccess,unsigned> logEndpoint{}; ///Reserved. Read value is undefined, only zero should be written. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,6),Register::ReadWriteAccess,unsigned> reserved{}; } namespace UsbCmdcode{ ///<USB Command Code using Addr = Register::Address<0x2008c210,0x00000000,0x00000000,unsigned>; ///Reserved. Read value is undefined, only zero should be written. constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,0),Register::ReadWriteAccess,unsigned> reserved{}; ///The command phase: constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,8),Register::ReadWriteAccess,unsigned> cmdPhase{}; ///This is a multi-purpose field. When CMD_PHASE is Command or Read, this field contains the code for the command (CMD_CODE). When CMD_PHASE is Write, this field contains the command write data (CMD_WDATA). constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,16),Register::ReadWriteAccess,unsigned> cmdCodeWdata{}; ///Reserved. Read value is undefined, only zero should be written. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,24),Register::ReadWriteAccess,unsigned> reserved{}; } namespace UsbCmddata{ ///<USB Command Data using Addr = Register::Address<0x2008c214,0x00000000,0x00000000,unsigned>; ///Command Read Data. constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,0),Register::ReadWriteAccess,unsigned> cmdRdata{}; ///Reserved. The value read from a reserved bit is not defined. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,8),Register::ReadWriteAccess,unsigned> reserved{}; } namespace UsbDmarst{ ///<USB DMA Request Status using Addr = Register::Address<0x2008c250,0x00000000,0x00000000,unsigned>; ///Control endpoint OUT (DMA cannot be enabled for this endpoint and EP0 bit must be 0). constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> eprst0{}; ///Control endpoint IN (DMA cannot be enabled for this endpoint and EP1 bit must be 0). constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> eprst1{}; ///Endpoint xx (2 <= xx <= 31) DMA request. 0 = DMA not requested by endpoint xx. 1 = DMA requested by endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> eprst2{}; ///Endpoint xx (2 <= xx <= 31) DMA request. 0 = DMA not requested by endpoint xx. 1 = DMA requested by endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> eprst3{}; ///Endpoint xx (2 <= xx <= 31) DMA request. 0 = DMA not requested by endpoint xx. 1 = DMA requested by endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> eprst4{}; ///Endpoint xx (2 <= xx <= 31) DMA request. 0 = DMA not requested by endpoint xx. 1 = DMA requested by endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> eprst5{}; ///Endpoint xx (2 <= xx <= 31) DMA request. 0 = DMA not requested by endpoint xx. 1 = DMA requested by endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> eprst6{}; ///Endpoint xx (2 <= xx <= 31) DMA request. 0 = DMA not requested by endpoint xx. 1 = DMA requested by endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> eprst7{}; ///Endpoint xx (2 <= xx <= 31) DMA request. 0 = DMA not requested by endpoint xx. 1 = DMA requested by endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> eprst8{}; ///Endpoint xx (2 <= xx <= 31) DMA request. 0 = DMA not requested by endpoint xx. 1 = DMA requested by endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> eprst9{}; ///Endpoint xx (2 <= xx <= 31) DMA request. 0 = DMA not requested by endpoint xx. 1 = DMA requested by endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> eprst10{}; ///Endpoint xx (2 <= xx <= 31) DMA request. 0 = DMA not requested by endpoint xx. 1 = DMA requested by endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> eprst11{}; ///Endpoint xx (2 <= xx <= 31) DMA request. 0 = DMA not requested by endpoint xx. 1 = DMA requested by endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,unsigned> eprst12{}; ///Endpoint xx (2 <= xx <= 31) DMA request. 0 = DMA not requested by endpoint xx. 1 = DMA requested by endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,unsigned> eprst13{}; ///Endpoint xx (2 <= xx <= 31) DMA request. 0 = DMA not requested by endpoint xx. 1 = DMA requested by endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,unsigned> eprst14{}; ///Endpoint xx (2 <= xx <= 31) DMA request. 0 = DMA not requested by endpoint xx. 1 = DMA requested by endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> eprst15{}; ///Endpoint xx (2 <= xx <= 31) DMA request. 0 = DMA not requested by endpoint xx. 1 = DMA requested by endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,unsigned> eprst16{}; ///Endpoint xx (2 <= xx <= 31) DMA request. 0 = DMA not requested by endpoint xx. 1 = DMA requested by endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,17),Register::ReadWriteAccess,unsigned> eprst17{}; ///Endpoint xx (2 <= xx <= 31) DMA request. 0 = DMA not requested by endpoint xx. 1 = DMA requested by endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,18),Register::ReadWriteAccess,unsigned> eprst18{}; ///Endpoint xx (2 <= xx <= 31) DMA request. 0 = DMA not requested by endpoint xx. 1 = DMA requested by endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,19),Register::ReadWriteAccess,unsigned> eprst19{}; ///Endpoint xx (2 <= xx <= 31) DMA request. 0 = DMA not requested by endpoint xx. 1 = DMA requested by endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::ReadWriteAccess,unsigned> eprst20{}; ///Endpoint xx (2 <= xx <= 31) DMA request. 0 = DMA not requested by endpoint xx. 1 = DMA requested by endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,21),Register::ReadWriteAccess,unsigned> eprst21{}; ///Endpoint xx (2 <= xx <= 31) DMA request. 0 = DMA not requested by endpoint xx. 1 = DMA requested by endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::ReadWriteAccess,unsigned> eprst22{}; ///Endpoint xx (2 <= xx <= 31) DMA request. 0 = DMA not requested by endpoint xx. 1 = DMA requested by endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,23),Register::ReadWriteAccess,unsigned> eprst23{}; ///Endpoint xx (2 <= xx <= 31) DMA request. 0 = DMA not requested by endpoint xx. 1 = DMA requested by endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,24),Register::ReadWriteAccess,unsigned> eprst24{}; ///Endpoint xx (2 <= xx <= 31) DMA request. 0 = DMA not requested by endpoint xx. 1 = DMA requested by endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,25),Register::ReadWriteAccess,unsigned> eprst25{}; ///Endpoint xx (2 <= xx <= 31) DMA request. 0 = DMA not requested by endpoint xx. 1 = DMA requested by endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(26,26),Register::ReadWriteAccess,unsigned> eprst26{}; ///Endpoint xx (2 <= xx <= 31) DMA request. 0 = DMA not requested by endpoint xx. 1 = DMA requested by endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,27),Register::ReadWriteAccess,unsigned> eprst27{}; ///Endpoint xx (2 <= xx <= 31) DMA request. 0 = DMA not requested by endpoint xx. 1 = DMA requested by endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(28,28),Register::ReadWriteAccess,unsigned> eprst28{}; ///Endpoint xx (2 <= xx <= 31) DMA request. 0 = DMA not requested by endpoint xx. 1 = DMA requested by endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,29),Register::ReadWriteAccess,unsigned> eprst29{}; ///Endpoint xx (2 <= xx <= 31) DMA request. 0 = DMA not requested by endpoint xx. 1 = DMA requested by endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(30,30),Register::ReadWriteAccess,unsigned> eprst30{}; ///Endpoint xx (2 <= xx <= 31) DMA request. 0 = DMA not requested by endpoint xx. 1 = DMA requested by endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,31),Register::ReadWriteAccess,unsigned> eprst31{}; } namespace UsbDmarclr{ ///<USB DMA Request Clear using Addr = Register::Address<0x2008c254,0x00000000,0x00000000,unsigned>; ///Control endpoint OUT (DMA cannot be enabled for this endpoint and the EP0 bit must be 0). constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> eprclr0{}; ///Control endpoint IN (DMA cannot be enabled for this endpoint and the EP1 bit must be 0). constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> eprclr1{}; ///Clear the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Clear the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> eprclr2{}; ///Clear the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Clear the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> eprclr3{}; ///Clear the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Clear the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> eprclr4{}; ///Clear the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Clear the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> eprclr5{}; ///Clear the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Clear the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> eprclr6{}; ///Clear the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Clear the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> eprclr7{}; ///Clear the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Clear the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> eprclr8{}; ///Clear the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Clear the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> eprclr9{}; ///Clear the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Clear the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> eprclr10{}; ///Clear the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Clear the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> eprclr11{}; ///Clear the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Clear the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,unsigned> eprclr12{}; ///Clear the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Clear the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,unsigned> eprclr13{}; ///Clear the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Clear the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,unsigned> eprclr14{}; ///Clear the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Clear the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> eprclr15{}; ///Clear the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Clear the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,unsigned> eprclr16{}; ///Clear the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Clear the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,17),Register::ReadWriteAccess,unsigned> eprclr17{}; ///Clear the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Clear the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,18),Register::ReadWriteAccess,unsigned> eprclr18{}; ///Clear the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Clear the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,19),Register::ReadWriteAccess,unsigned> eprclr19{}; ///Clear the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Clear the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::ReadWriteAccess,unsigned> eprclr20{}; ///Clear the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Clear the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,21),Register::ReadWriteAccess,unsigned> eprclr21{}; ///Clear the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Clear the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::ReadWriteAccess,unsigned> eprclr22{}; ///Clear the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Clear the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,23),Register::ReadWriteAccess,unsigned> eprclr23{}; ///Clear the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Clear the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,24),Register::ReadWriteAccess,unsigned> eprclr24{}; ///Clear the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Clear the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,25),Register::ReadWriteAccess,unsigned> eprclr25{}; ///Clear the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Clear the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(26,26),Register::ReadWriteAccess,unsigned> eprclr26{}; ///Clear the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Clear the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,27),Register::ReadWriteAccess,unsigned> eprclr27{}; ///Clear the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Clear the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(28,28),Register::ReadWriteAccess,unsigned> eprclr28{}; ///Clear the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Clear the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,29),Register::ReadWriteAccess,unsigned> eprclr29{}; ///Clear the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Clear the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(30,30),Register::ReadWriteAccess,unsigned> eprclr30{}; ///Clear the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Clear the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,31),Register::ReadWriteAccess,unsigned> eprclr31{}; } namespace UsbDmarset{ ///<USB DMA Request Set using Addr = Register::Address<0x2008c258,0x00000000,0x00000000,unsigned>; ///Control endpoint OUT (DMA cannot be enabled for this endpoint and the EP0 bit must be 0). constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> eprset0{}; ///Control endpoint IN (DMA cannot be enabled for this endpoint and the EP1 bit must be 0). constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> eprset1{}; ///Set the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Set the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> eprset2{}; ///Set the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Set the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> eprset3{}; ///Set the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Set the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> eprset4{}; ///Set the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Set the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> eprset5{}; ///Set the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Set the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> eprset6{}; ///Set the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Set the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> eprset7{}; ///Set the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Set the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> eprset8{}; ///Set the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Set the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> eprset9{}; ///Set the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Set the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> eprset10{}; ///Set the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Set the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> eprset11{}; ///Set the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Set the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,unsigned> eprset12{}; ///Set the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Set the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,unsigned> eprset13{}; ///Set the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Set the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,unsigned> eprset14{}; ///Set the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Set the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> eprset15{}; ///Set the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Set the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,unsigned> eprset16{}; ///Set the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Set the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,17),Register::ReadWriteAccess,unsigned> eprset17{}; ///Set the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Set the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,18),Register::ReadWriteAccess,unsigned> eprset18{}; ///Set the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Set the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,19),Register::ReadWriteAccess,unsigned> eprset19{}; ///Set the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Set the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::ReadWriteAccess,unsigned> eprset20{}; ///Set the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Set the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,21),Register::ReadWriteAccess,unsigned> eprset21{}; ///Set the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Set the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::ReadWriteAccess,unsigned> eprset22{}; ///Set the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Set the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,23),Register::ReadWriteAccess,unsigned> eprset23{}; ///Set the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Set the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,24),Register::ReadWriteAccess,unsigned> eprset24{}; ///Set the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Set the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,25),Register::ReadWriteAccess,unsigned> eprset25{}; ///Set the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Set the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(26,26),Register::ReadWriteAccess,unsigned> eprset26{}; ///Set the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Set the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,27),Register::ReadWriteAccess,unsigned> eprset27{}; ///Set the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Set the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(28,28),Register::ReadWriteAccess,unsigned> eprset28{}; ///Set the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Set the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,29),Register::ReadWriteAccess,unsigned> eprset29{}; ///Set the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Set the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(30,30),Register::ReadWriteAccess,unsigned> eprset30{}; ///Set the endpoint xx (2 <= xx <= 31) DMA request. 0 = No effect 1 = Set the corresponding bit in USBDMARSt. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,31),Register::ReadWriteAccess,unsigned> eprset31{}; } namespace UsbUdcah{ ///<USB UDCA Head using Addr = Register::Address<0x2008c280,0x00000000,0x00000000,unsigned>; ///Reserved. Read value is undefined, only zero should be written. The UDCA is aligned to 128-byte boundaries. constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,0),Register::ReadWriteAccess,unsigned> reserved{}; ///Start address of the UDCA. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,7),Register::ReadWriteAccess,unsigned> udcaAddr{}; } namespace UsbEpdmast{ ///<USB Endpoint DMA Status using Addr = Register::Address<0x2008c284,0x00000000,0x00000000,unsigned>; ///Control endpoint OUT (DMA cannot be enabled for this endpoint and the EP0_DMA_ENABLE bit must be 0). constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> epDmaSt0{}; ///Control endpoint IN (DMA cannot be enabled for this endpoint and the EP1_DMA_ENABLE bit must be 0). constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> epDmaSt1{}; ///Endpoint xx (2 <= xx <= 31) DMA enabled bit. 0 = The DMA for endpoint EPxx is disabled. 1 = The DMA for endpoint EPxx is enabled. constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> epDmaSt2{}; ///Endpoint xx (2 <= xx <= 31) DMA enabled bit. 0 = The DMA for endpoint EPxx is disabled. 1 = The DMA for endpoint EPxx is enabled. constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> epDmaSt3{}; ///Endpoint xx (2 <= xx <= 31) DMA enabled bit. 0 = The DMA for endpoint EPxx is disabled. 1 = The DMA for endpoint EPxx is enabled. constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> epDmaSt4{}; ///Endpoint xx (2 <= xx <= 31) DMA enabled bit. 0 = The DMA for endpoint EPxx is disabled. 1 = The DMA for endpoint EPxx is enabled. constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> epDmaSt5{}; ///Endpoint xx (2 <= xx <= 31) DMA enabled bit. 0 = The DMA for endpoint EPxx is disabled. 1 = The DMA for endpoint EPxx is enabled. constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> epDmaSt6{}; ///Endpoint xx (2 <= xx <= 31) DMA enabled bit. 0 = The DMA for endpoint EPxx is disabled. 1 = The DMA for endpoint EPxx is enabled. constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> epDmaSt7{}; ///Endpoint xx (2 <= xx <= 31) DMA enabled bit. 0 = The DMA for endpoint EPxx is disabled. 1 = The DMA for endpoint EPxx is enabled. constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> epDmaSt8{}; ///Endpoint xx (2 <= xx <= 31) DMA enabled bit. 0 = The DMA for endpoint EPxx is disabled. 1 = The DMA for endpoint EPxx is enabled. constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> epDmaSt9{}; ///Endpoint xx (2 <= xx <= 31) DMA enabled bit. 0 = The DMA for endpoint EPxx is disabled. 1 = The DMA for endpoint EPxx is enabled. constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> epDmaSt10{}; ///Endpoint xx (2 <= xx <= 31) DMA enabled bit. 0 = The DMA for endpoint EPxx is disabled. 1 = The DMA for endpoint EPxx is enabled. constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> epDmaSt11{}; ///Endpoint xx (2 <= xx <= 31) DMA enabled bit. 0 = The DMA for endpoint EPxx is disabled. 1 = The DMA for endpoint EPxx is enabled. constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,unsigned> epDmaSt12{}; ///Endpoint xx (2 <= xx <= 31) DMA enabled bit. 0 = The DMA for endpoint EPxx is disabled. 1 = The DMA for endpoint EPxx is enabled. constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,unsigned> epDmaSt13{}; ///Endpoint xx (2 <= xx <= 31) DMA enabled bit. 0 = The DMA for endpoint EPxx is disabled. 1 = The DMA for endpoint EPxx is enabled. constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,unsigned> epDmaSt14{}; ///Endpoint xx (2 <= xx <= 31) DMA enabled bit. 0 = The DMA for endpoint EPxx is disabled. 1 = The DMA for endpoint EPxx is enabled. constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> epDmaSt15{}; ///Endpoint xx (2 <= xx <= 31) DMA enabled bit. 0 = The DMA for endpoint EPxx is disabled. 1 = The DMA for endpoint EPxx is enabled. constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,unsigned> epDmaSt16{}; ///Endpoint xx (2 <= xx <= 31) DMA enabled bit. 0 = The DMA for endpoint EPxx is disabled. 1 = The DMA for endpoint EPxx is enabled. constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,17),Register::ReadWriteAccess,unsigned> epDmaSt17{}; ///Endpoint xx (2 <= xx <= 31) DMA enabled bit. 0 = The DMA for endpoint EPxx is disabled. 1 = The DMA for endpoint EPxx is enabled. constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,18),Register::ReadWriteAccess,unsigned> epDmaSt18{}; ///Endpoint xx (2 <= xx <= 31) DMA enabled bit. 0 = The DMA for endpoint EPxx is disabled. 1 = The DMA for endpoint EPxx is enabled. constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,19),Register::ReadWriteAccess,unsigned> epDmaSt19{}; ///Endpoint xx (2 <= xx <= 31) DMA enabled bit. 0 = The DMA for endpoint EPxx is disabled. 1 = The DMA for endpoint EPxx is enabled. constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::ReadWriteAccess,unsigned> epDmaSt20{}; ///Endpoint xx (2 <= xx <= 31) DMA enabled bit. 0 = The DMA for endpoint EPxx is disabled. 1 = The DMA for endpoint EPxx is enabled. constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,21),Register::ReadWriteAccess,unsigned> epDmaSt21{}; ///Endpoint xx (2 <= xx <= 31) DMA enabled bit. 0 = The DMA for endpoint EPxx is disabled. 1 = The DMA for endpoint EPxx is enabled. constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::ReadWriteAccess,unsigned> epDmaSt22{}; ///Endpoint xx (2 <= xx <= 31) DMA enabled bit. 0 = The DMA for endpoint EPxx is disabled. 1 = The DMA for endpoint EPxx is enabled. constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,23),Register::ReadWriteAccess,unsigned> epDmaSt23{}; ///Endpoint xx (2 <= xx <= 31) DMA enabled bit. 0 = The DMA for endpoint EPxx is disabled. 1 = The DMA for endpoint EPxx is enabled. constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,24),Register::ReadWriteAccess,unsigned> epDmaSt24{}; ///Endpoint xx (2 <= xx <= 31) DMA enabled bit. 0 = The DMA for endpoint EPxx is disabled. 1 = The DMA for endpoint EPxx is enabled. constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,25),Register::ReadWriteAccess,unsigned> epDmaSt25{}; ///Endpoint xx (2 <= xx <= 31) DMA enabled bit. 0 = The DMA for endpoint EPxx is disabled. 1 = The DMA for endpoint EPxx is enabled. constexpr Register::FieldLocation<Addr,Register::maskFromRange(26,26),Register::ReadWriteAccess,unsigned> epDmaSt26{}; ///Endpoint xx (2 <= xx <= 31) DMA enabled bit. 0 = The DMA for endpoint EPxx is disabled. 1 = The DMA for endpoint EPxx is enabled. constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,27),Register::ReadWriteAccess,unsigned> epDmaSt27{}; ///Endpoint xx (2 <= xx <= 31) DMA enabled bit. 0 = The DMA for endpoint EPxx is disabled. 1 = The DMA for endpoint EPxx is enabled. constexpr Register::FieldLocation<Addr,Register::maskFromRange(28,28),Register::ReadWriteAccess,unsigned> epDmaSt28{}; ///Endpoint xx (2 <= xx <= 31) DMA enabled bit. 0 = The DMA for endpoint EPxx is disabled. 1 = The DMA for endpoint EPxx is enabled. constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,29),Register::ReadWriteAccess,unsigned> epDmaSt29{}; ///Endpoint xx (2 <= xx <= 31) DMA enabled bit. 0 = The DMA for endpoint EPxx is disabled. 1 = The DMA for endpoint EPxx is enabled. constexpr Register::FieldLocation<Addr,Register::maskFromRange(30,30),Register::ReadWriteAccess,unsigned> epDmaSt30{}; ///Endpoint xx (2 <= xx <= 31) DMA enabled bit. 0 = The DMA for endpoint EPxx is disabled. 1 = The DMA for endpoint EPxx is enabled. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,31),Register::ReadWriteAccess,unsigned> epDmaSt31{}; } namespace UsbEpdmaen{ ///<USB Endpoint DMA Enable using Addr = Register::Address<0x2008c288,0x00000000,0x00000000,unsigned>; ///Control endpoint OUT (DMA cannot be enabled for this endpoint and the EP0_DMA_ENABLE bit value must be 0). constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> epDmaEn0{}; ///Control endpoint IN (DMA cannot be enabled for this endpoint and the EP1_DMA_ENABLE bit must be 0). constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> epDmaEn1{}; ///Endpoint xx(2 <= xx <= 31) DMA enable control bit. 0 = No effect. 1 = Enable the DMA operation for endpoint EPxx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,2),Register::ReadWriteAccess,unsigned> epDmaEn{}; } namespace UsbEpdmadis{ ///<USB Endpoint DMA Disable using Addr = Register::Address<0x2008c28c,0x00000000,0x00000000,unsigned>; ///Control endpoint OUT (DMA cannot be enabled for this endpoint and the EP0_DMA_DISABLE bit value must be 0). constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> epDmaDis0{}; ///Control endpoint IN (DMA cannot be enabled for this endpoint and the EP1_DMA_DISABLE bit value must be 0). constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> epDmaDis1{}; ///Endpoint xx (2 <= xx <= 31) DMA disable control bit. 0 = No effect. 1 = Disable the DMA operation for endpoint EPxx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> epDmaDis2{}; ///Endpoint xx (2 <= xx <= 31) DMA disable control bit. 0 = No effect. 1 = Disable the DMA operation for endpoint EPxx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> epDmaDis3{}; ///Endpoint xx (2 <= xx <= 31) DMA disable control bit. 0 = No effect. 1 = Disable the DMA operation for endpoint EPxx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> epDmaDis4{}; ///Endpoint xx (2 <= xx <= 31) DMA disable control bit. 0 = No effect. 1 = Disable the DMA operation for endpoint EPxx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> epDmaDis5{}; ///Endpoint xx (2 <= xx <= 31) DMA disable control bit. 0 = No effect. 1 = Disable the DMA operation for endpoint EPxx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> epDmaDis6{}; ///Endpoint xx (2 <= xx <= 31) DMA disable control bit. 0 = No effect. 1 = Disable the DMA operation for endpoint EPxx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> epDmaDis7{}; ///Endpoint xx (2 <= xx <= 31) DMA disable control bit. 0 = No effect. 1 = Disable the DMA operation for endpoint EPxx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> epDmaDis8{}; ///Endpoint xx (2 <= xx <= 31) DMA disable control bit. 0 = No effect. 1 = Disable the DMA operation for endpoint EPxx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> epDmaDis9{}; ///Endpoint xx (2 <= xx <= 31) DMA disable control bit. 0 = No effect. 1 = Disable the DMA operation for endpoint EPxx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> epDmaDis10{}; ///Endpoint xx (2 <= xx <= 31) DMA disable control bit. 0 = No effect. 1 = Disable the DMA operation for endpoint EPxx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> epDmaDis11{}; ///Endpoint xx (2 <= xx <= 31) DMA disable control bit. 0 = No effect. 1 = Disable the DMA operation for endpoint EPxx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,unsigned> epDmaDis12{}; ///Endpoint xx (2 <= xx <= 31) DMA disable control bit. 0 = No effect. 1 = Disable the DMA operation for endpoint EPxx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,unsigned> epDmaDis13{}; ///Endpoint xx (2 <= xx <= 31) DMA disable control bit. 0 = No effect. 1 = Disable the DMA operation for endpoint EPxx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,unsigned> epDmaDis14{}; ///Endpoint xx (2 <= xx <= 31) DMA disable control bit. 0 = No effect. 1 = Disable the DMA operation for endpoint EPxx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> epDmaDis15{}; ///Endpoint xx (2 <= xx <= 31) DMA disable control bit. 0 = No effect. 1 = Disable the DMA operation for endpoint EPxx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,unsigned> epDmaDis16{}; ///Endpoint xx (2 <= xx <= 31) DMA disable control bit. 0 = No effect. 1 = Disable the DMA operation for endpoint EPxx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,17),Register::ReadWriteAccess,unsigned> epDmaDis17{}; ///Endpoint xx (2 <= xx <= 31) DMA disable control bit. 0 = No effect. 1 = Disable the DMA operation for endpoint EPxx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,18),Register::ReadWriteAccess,unsigned> epDmaDis18{}; ///Endpoint xx (2 <= xx <= 31) DMA disable control bit. 0 = No effect. 1 = Disable the DMA operation for endpoint EPxx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,19),Register::ReadWriteAccess,unsigned> epDmaDis19{}; ///Endpoint xx (2 <= xx <= 31) DMA disable control bit. 0 = No effect. 1 = Disable the DMA operation for endpoint EPxx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::ReadWriteAccess,unsigned> epDmaDis20{}; ///Endpoint xx (2 <= xx <= 31) DMA disable control bit. 0 = No effect. 1 = Disable the DMA operation for endpoint EPxx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,21),Register::ReadWriteAccess,unsigned> epDmaDis21{}; ///Endpoint xx (2 <= xx <= 31) DMA disable control bit. 0 = No effect. 1 = Disable the DMA operation for endpoint EPxx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::ReadWriteAccess,unsigned> epDmaDis22{}; ///Endpoint xx (2 <= xx <= 31) DMA disable control bit. 0 = No effect. 1 = Disable the DMA operation for endpoint EPxx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,23),Register::ReadWriteAccess,unsigned> epDmaDis23{}; ///Endpoint xx (2 <= xx <= 31) DMA disable control bit. 0 = No effect. 1 = Disable the DMA operation for endpoint EPxx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,24),Register::ReadWriteAccess,unsigned> epDmaDis24{}; ///Endpoint xx (2 <= xx <= 31) DMA disable control bit. 0 = No effect. 1 = Disable the DMA operation for endpoint EPxx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,25),Register::ReadWriteAccess,unsigned> epDmaDis25{}; ///Endpoint xx (2 <= xx <= 31) DMA disable control bit. 0 = No effect. 1 = Disable the DMA operation for endpoint EPxx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(26,26),Register::ReadWriteAccess,unsigned> epDmaDis26{}; ///Endpoint xx (2 <= xx <= 31) DMA disable control bit. 0 = No effect. 1 = Disable the DMA operation for endpoint EPxx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,27),Register::ReadWriteAccess,unsigned> epDmaDis27{}; ///Endpoint xx (2 <= xx <= 31) DMA disable control bit. 0 = No effect. 1 = Disable the DMA operation for endpoint EPxx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(28,28),Register::ReadWriteAccess,unsigned> epDmaDis28{}; ///Endpoint xx (2 <= xx <= 31) DMA disable control bit. 0 = No effect. 1 = Disable the DMA operation for endpoint EPxx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,29),Register::ReadWriteAccess,unsigned> epDmaDis29{}; ///Endpoint xx (2 <= xx <= 31) DMA disable control bit. 0 = No effect. 1 = Disable the DMA operation for endpoint EPxx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(30,30),Register::ReadWriteAccess,unsigned> epDmaDis30{}; ///Endpoint xx (2 <= xx <= 31) DMA disable control bit. 0 = No effect. 1 = Disable the DMA operation for endpoint EPxx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,31),Register::ReadWriteAccess,unsigned> epDmaDis31{}; } namespace UsbDmaintst{ ///<USB DMA Interrupt Status using Addr = Register::Address<0x2008c290,0x00000000,0x00000000,unsigned>; ///End of Transfer Interrupt bit. enum class EotVal { allBitsInTheUsbe=0x00000000, ///<All bits in the USBEoTIntSt register are 0. atLeastOneBitIn=0x00000001, ///<At least one bit in the USBEoTIntSt is set. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,EotVal> eot{}; namespace EotValC{ constexpr Register::FieldValue<decltype(eot)::Type,EotVal::allBitsInTheUsbe> allBitsInTheUsbe{}; constexpr Register::FieldValue<decltype(eot)::Type,EotVal::atLeastOneBitIn> atLeastOneBitIn{}; } ///New DD Request Interrupt bit. enum class NddrVal { allBitsInTheUsbn=0x00000000, ///<All bits in the USBNDDRIntSt register are 0. atLeastOneBitIn=0x00000001, ///<At least one bit in the USBNDDRIntSt is set. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,NddrVal> nddr{}; namespace NddrValC{ constexpr Register::FieldValue<decltype(nddr)::Type,NddrVal::allBitsInTheUsbn> allBitsInTheUsbn{}; constexpr Register::FieldValue<decltype(nddr)::Type,NddrVal::atLeastOneBitIn> atLeastOneBitIn{}; } ///System Error Interrupt bit. enum class ErrVal { allBitsInTheUsbs=0x00000000, ///<All bits in the USBSysErrIntSt register are 0. atLeastOneBitIn=0x00000001, ///<At least one bit in the USBSysErrIntSt is set. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,ErrVal> err{}; namespace ErrValC{ constexpr Register::FieldValue<decltype(err)::Type,ErrVal::allBitsInTheUsbs> allBitsInTheUsbs{}; constexpr Register::FieldValue<decltype(err)::Type,ErrVal::atLeastOneBitIn> atLeastOneBitIn{}; } ///Reserved. The value read from a reserved bit is not defined. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,3),Register::ReadWriteAccess,unsigned> reserved{}; } namespace UsbDmainten{ ///<USB DMA Interrupt Enable using Addr = Register::Address<0x2008c294,0x00000000,0x00000000,unsigned>; ///End of Transfer Interrupt enable bit. enum class EotVal { disabled=0x00000000, ///<Disabled. enabled=0x00000001, ///<Enabled. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,EotVal> eot{}; namespace EotValC{ constexpr Register::FieldValue<decltype(eot)::Type,EotVal::disabled> disabled{}; constexpr Register::FieldValue<decltype(eot)::Type,EotVal::enabled> enabled{}; } ///New DD Request Interrupt enable bit. enum class NddrVal { disabled=0x00000000, ///<Disabled. enabled=0x00000001, ///<Enabled. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,NddrVal> nddr{}; namespace NddrValC{ constexpr Register::FieldValue<decltype(nddr)::Type,NddrVal::disabled> disabled{}; constexpr Register::FieldValue<decltype(nddr)::Type,NddrVal::enabled> enabled{}; } ///System Error Interrupt enable bit. enum class ErrVal { disabled=0x00000000, ///<Disabled. enabled=0x00000001, ///<Enabled. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,ErrVal> err{}; namespace ErrValC{ constexpr Register::FieldValue<decltype(err)::Type,ErrVal::disabled> disabled{}; constexpr Register::FieldValue<decltype(err)::Type,ErrVal::enabled> enabled{}; } ///Reserved. Read value is undefined, only zero should be written. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,3),Register::ReadWriteAccess,unsigned> reserved{}; } namespace UsbEotintst{ ///<USB End of Transfer Interrupt Status using Addr = Register::Address<0x2008c2a0,0x00000000,0x00000000,unsigned>; ///Endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = There is no End of Transfer interrupt request for endpoint xx. 1 = There is an End of Transfer Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> eptxintst0{}; ///Endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = There is no End of Transfer interrupt request for endpoint xx. 1 = There is an End of Transfer Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> eptxintst1{}; ///Endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = There is no End of Transfer interrupt request for endpoint xx. 1 = There is an End of Transfer Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> eptxintst2{}; ///Endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = There is no End of Transfer interrupt request for endpoint xx. 1 = There is an End of Transfer Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> eptxintst3{}; ///Endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = There is no End of Transfer interrupt request for endpoint xx. 1 = There is an End of Transfer Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> eptxintst4{}; ///Endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = There is no End of Transfer interrupt request for endpoint xx. 1 = There is an End of Transfer Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> eptxintst5{}; ///Endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = There is no End of Transfer interrupt request for endpoint xx. 1 = There is an End of Transfer Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> eptxintst6{}; ///Endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = There is no End of Transfer interrupt request for endpoint xx. 1 = There is an End of Transfer Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> eptxintst7{}; ///Endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = There is no End of Transfer interrupt request for endpoint xx. 1 = There is an End of Transfer Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> eptxintst8{}; ///Endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = There is no End of Transfer interrupt request for endpoint xx. 1 = There is an End of Transfer Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> eptxintst9{}; ///Endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = There is no End of Transfer interrupt request for endpoint xx. 1 = There is an End of Transfer Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> eptxintst10{}; ///Endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = There is no End of Transfer interrupt request for endpoint xx. 1 = There is an End of Transfer Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> eptxintst11{}; ///Endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = There is no End of Transfer interrupt request for endpoint xx. 1 = There is an End of Transfer Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,unsigned> eptxintst12{}; ///Endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = There is no End of Transfer interrupt request for endpoint xx. 1 = There is an End of Transfer Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,unsigned> eptxintst13{}; ///Endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = There is no End of Transfer interrupt request for endpoint xx. 1 = There is an End of Transfer Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,unsigned> eptxintst14{}; ///Endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = There is no End of Transfer interrupt request for endpoint xx. 1 = There is an End of Transfer Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> eptxintst15{}; ///Endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = There is no End of Transfer interrupt request for endpoint xx. 1 = There is an End of Transfer Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,unsigned> eptxintst16{}; ///Endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = There is no End of Transfer interrupt request for endpoint xx. 1 = There is an End of Transfer Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,17),Register::ReadWriteAccess,unsigned> eptxintst17{}; ///Endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = There is no End of Transfer interrupt request for endpoint xx. 1 = There is an End of Transfer Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,18),Register::ReadWriteAccess,unsigned> eptxintst18{}; ///Endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = There is no End of Transfer interrupt request for endpoint xx. 1 = There is an End of Transfer Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,19),Register::ReadWriteAccess,unsigned> eptxintst19{}; ///Endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = There is no End of Transfer interrupt request for endpoint xx. 1 = There is an End of Transfer Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::ReadWriteAccess,unsigned> eptxintst20{}; ///Endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = There is no End of Transfer interrupt request for endpoint xx. 1 = There is an End of Transfer Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,21),Register::ReadWriteAccess,unsigned> eptxintst21{}; ///Endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = There is no End of Transfer interrupt request for endpoint xx. 1 = There is an End of Transfer Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::ReadWriteAccess,unsigned> eptxintst22{}; ///Endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = There is no End of Transfer interrupt request for endpoint xx. 1 = There is an End of Transfer Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,23),Register::ReadWriteAccess,unsigned> eptxintst23{}; ///Endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = There is no End of Transfer interrupt request for endpoint xx. 1 = There is an End of Transfer Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,24),Register::ReadWriteAccess,unsigned> eptxintst24{}; ///Endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = There is no End of Transfer interrupt request for endpoint xx. 1 = There is an End of Transfer Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,25),Register::ReadWriteAccess,unsigned> eptxintst25{}; ///Endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = There is no End of Transfer interrupt request for endpoint xx. 1 = There is an End of Transfer Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(26,26),Register::ReadWriteAccess,unsigned> eptxintst26{}; ///Endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = There is no End of Transfer interrupt request for endpoint xx. 1 = There is an End of Transfer Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,27),Register::ReadWriteAccess,unsigned> eptxintst27{}; ///Endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = There is no End of Transfer interrupt request for endpoint xx. 1 = There is an End of Transfer Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(28,28),Register::ReadWriteAccess,unsigned> eptxintst28{}; ///Endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = There is no End of Transfer interrupt request for endpoint xx. 1 = There is an End of Transfer Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,29),Register::ReadWriteAccess,unsigned> eptxintst29{}; ///Endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = There is no End of Transfer interrupt request for endpoint xx. 1 = There is an End of Transfer Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(30,30),Register::ReadWriteAccess,unsigned> eptxintst30{}; ///Endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = There is no End of Transfer interrupt request for endpoint xx. 1 = There is an End of Transfer Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,31),Register::ReadWriteAccess,unsigned> eptxintst31{}; } namespace UsbEotintclr{ ///<USB End of Transfer Interrupt Clear using Addr = Register::Address<0x2008c2a4,0x00000000,0x00000000,unsigned>; ///Clear endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Clear the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> eptxintclr0{}; ///Clear endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Clear the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> eptxintclr1{}; ///Clear endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Clear the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> eptxintclr2{}; ///Clear endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Clear the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> eptxintclr3{}; ///Clear endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Clear the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> eptxintclr4{}; ///Clear endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Clear the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> eptxintclr5{}; ///Clear endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Clear the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> eptxintclr6{}; ///Clear endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Clear the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> eptxintclr7{}; ///Clear endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Clear the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> eptxintclr8{}; ///Clear endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Clear the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> eptxintclr9{}; ///Clear endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Clear the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> eptxintclr10{}; ///Clear endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Clear the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> eptxintclr11{}; ///Clear endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Clear the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,unsigned> eptxintclr12{}; ///Clear endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Clear the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,unsigned> eptxintclr13{}; ///Clear endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Clear the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,unsigned> eptxintclr14{}; ///Clear endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Clear the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> eptxintclr15{}; ///Clear endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Clear the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,unsigned> eptxintclr16{}; ///Clear endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Clear the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,17),Register::ReadWriteAccess,unsigned> eptxintclr17{}; ///Clear endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Clear the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,18),Register::ReadWriteAccess,unsigned> eptxintclr18{}; ///Clear endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Clear the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,19),Register::ReadWriteAccess,unsigned> eptxintclr19{}; ///Clear endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Clear the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::ReadWriteAccess,unsigned> eptxintclr20{}; ///Clear endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Clear the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,21),Register::ReadWriteAccess,unsigned> eptxintclr21{}; ///Clear endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Clear the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::ReadWriteAccess,unsigned> eptxintclr22{}; ///Clear endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Clear the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,23),Register::ReadWriteAccess,unsigned> eptxintclr23{}; ///Clear endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Clear the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,24),Register::ReadWriteAccess,unsigned> eptxintclr24{}; ///Clear endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Clear the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,25),Register::ReadWriteAccess,unsigned> eptxintclr25{}; ///Clear endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Clear the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(26,26),Register::ReadWriteAccess,unsigned> eptxintclr26{}; ///Clear endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Clear the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,27),Register::ReadWriteAccess,unsigned> eptxintclr27{}; ///Clear endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Clear the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(28,28),Register::ReadWriteAccess,unsigned> eptxintclr28{}; ///Clear endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Clear the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,29),Register::ReadWriteAccess,unsigned> eptxintclr29{}; ///Clear endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Clear the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(30,30),Register::ReadWriteAccess,unsigned> eptxintclr30{}; ///Clear endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Clear the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,31),Register::ReadWriteAccess,unsigned> eptxintclr31{}; } namespace UsbEotintset{ ///<USB End of Transfer Interrupt Set using Addr = Register::Address<0x2008c2a8,0x00000000,0x00000000,unsigned>; ///Set endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Set the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> eptxintset0{}; ///Set endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Set the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> eptxintset1{}; ///Set endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Set the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> eptxintset2{}; ///Set endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Set the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> eptxintset3{}; ///Set endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Set the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> eptxintset4{}; ///Set endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Set the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> eptxintset5{}; ///Set endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Set the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> eptxintset6{}; ///Set endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Set the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> eptxintset7{}; ///Set endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Set the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> eptxintset8{}; ///Set endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Set the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> eptxintset9{}; ///Set endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Set the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> eptxintset10{}; ///Set endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Set the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> eptxintset11{}; ///Set endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Set the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,unsigned> eptxintset12{}; ///Set endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Set the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,unsigned> eptxintset13{}; ///Set endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Set the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,unsigned> eptxintset14{}; ///Set endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Set the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> eptxintset15{}; ///Set endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Set the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,unsigned> eptxintset16{}; ///Set endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Set the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,17),Register::ReadWriteAccess,unsigned> eptxintset17{}; ///Set endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Set the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,18),Register::ReadWriteAccess,unsigned> eptxintset18{}; ///Set endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Set the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,19),Register::ReadWriteAccess,unsigned> eptxintset19{}; ///Set endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Set the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::ReadWriteAccess,unsigned> eptxintset20{}; ///Set endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Set the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,21),Register::ReadWriteAccess,unsigned> eptxintset21{}; ///Set endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Set the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::ReadWriteAccess,unsigned> eptxintset22{}; ///Set endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Set the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,23),Register::ReadWriteAccess,unsigned> eptxintset23{}; ///Set endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Set the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,24),Register::ReadWriteAccess,unsigned> eptxintset24{}; ///Set endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Set the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,25),Register::ReadWriteAccess,unsigned> eptxintset25{}; ///Set endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Set the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(26,26),Register::ReadWriteAccess,unsigned> eptxintset26{}; ///Set endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Set the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,27),Register::ReadWriteAccess,unsigned> eptxintset27{}; ///Set endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Set the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(28,28),Register::ReadWriteAccess,unsigned> eptxintset28{}; ///Set endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Set the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,29),Register::ReadWriteAccess,unsigned> eptxintset29{}; ///Set endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Set the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(30,30),Register::ReadWriteAccess,unsigned> eptxintset30{}; ///Set endpoint xx (2 <= xx <= 31) End of Transfer Interrupt request. 0 = No effect. 1 = Set the EPxx End of Transfer Interrupt request in the USBEoTIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,31),Register::ReadWriteAccess,unsigned> eptxintset31{}; } namespace UsbNddrintst{ ///<USB New DD Request Interrupt Status using Addr = Register::Address<0x2008c2ac,0x00000000,0x00000000,unsigned>; ///Endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = There is no new DD interrupt request for endpoint xx. 1 = There is a new DD interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> epnddintst0{}; ///Endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = There is no new DD interrupt request for endpoint xx. 1 = There is a new DD interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> epnddintst1{}; ///Endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = There is no new DD interrupt request for endpoint xx. 1 = There is a new DD interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> epnddintst2{}; ///Endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = There is no new DD interrupt request for endpoint xx. 1 = There is a new DD interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> epnddintst3{}; ///Endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = There is no new DD interrupt request for endpoint xx. 1 = There is a new DD interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> epnddintst4{}; ///Endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = There is no new DD interrupt request for endpoint xx. 1 = There is a new DD interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> epnddintst5{}; ///Endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = There is no new DD interrupt request for endpoint xx. 1 = There is a new DD interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> epnddintst6{}; ///Endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = There is no new DD interrupt request for endpoint xx. 1 = There is a new DD interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> epnddintst7{}; ///Endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = There is no new DD interrupt request for endpoint xx. 1 = There is a new DD interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> epnddintst8{}; ///Endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = There is no new DD interrupt request for endpoint xx. 1 = There is a new DD interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> epnddintst9{}; ///Endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = There is no new DD interrupt request for endpoint xx. 1 = There is a new DD interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> epnddintst10{}; ///Endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = There is no new DD interrupt request for endpoint xx. 1 = There is a new DD interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> epnddintst11{}; ///Endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = There is no new DD interrupt request for endpoint xx. 1 = There is a new DD interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,unsigned> epnddintst12{}; ///Endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = There is no new DD interrupt request for endpoint xx. 1 = There is a new DD interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,unsigned> epnddintst13{}; ///Endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = There is no new DD interrupt request for endpoint xx. 1 = There is a new DD interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,unsigned> epnddintst14{}; ///Endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = There is no new DD interrupt request for endpoint xx. 1 = There is a new DD interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> epnddintst15{}; ///Endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = There is no new DD interrupt request for endpoint xx. 1 = There is a new DD interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,unsigned> epnddintst16{}; ///Endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = There is no new DD interrupt request for endpoint xx. 1 = There is a new DD interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,17),Register::ReadWriteAccess,unsigned> epnddintst17{}; ///Endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = There is no new DD interrupt request for endpoint xx. 1 = There is a new DD interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,18),Register::ReadWriteAccess,unsigned> epnddintst18{}; ///Endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = There is no new DD interrupt request for endpoint xx. 1 = There is a new DD interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,19),Register::ReadWriteAccess,unsigned> epnddintst19{}; ///Endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = There is no new DD interrupt request for endpoint xx. 1 = There is a new DD interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::ReadWriteAccess,unsigned> epnddintst20{}; ///Endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = There is no new DD interrupt request for endpoint xx. 1 = There is a new DD interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,21),Register::ReadWriteAccess,unsigned> epnddintst21{}; ///Endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = There is no new DD interrupt request for endpoint xx. 1 = There is a new DD interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::ReadWriteAccess,unsigned> epnddintst22{}; ///Endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = There is no new DD interrupt request for endpoint xx. 1 = There is a new DD interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,23),Register::ReadWriteAccess,unsigned> epnddintst23{}; ///Endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = There is no new DD interrupt request for endpoint xx. 1 = There is a new DD interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,24),Register::ReadWriteAccess,unsigned> epnddintst24{}; ///Endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = There is no new DD interrupt request for endpoint xx. 1 = There is a new DD interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,25),Register::ReadWriteAccess,unsigned> epnddintst25{}; ///Endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = There is no new DD interrupt request for endpoint xx. 1 = There is a new DD interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(26,26),Register::ReadWriteAccess,unsigned> epnddintst26{}; ///Endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = There is no new DD interrupt request for endpoint xx. 1 = There is a new DD interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,27),Register::ReadWriteAccess,unsigned> epnddintst27{}; ///Endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = There is no new DD interrupt request for endpoint xx. 1 = There is a new DD interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(28,28),Register::ReadWriteAccess,unsigned> epnddintst28{}; ///Endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = There is no new DD interrupt request for endpoint xx. 1 = There is a new DD interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,29),Register::ReadWriteAccess,unsigned> epnddintst29{}; ///Endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = There is no new DD interrupt request for endpoint xx. 1 = There is a new DD interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(30,30),Register::ReadWriteAccess,unsigned> epnddintst30{}; ///Endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = There is no new DD interrupt request for endpoint xx. 1 = There is a new DD interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,31),Register::ReadWriteAccess,unsigned> epnddintst31{}; } namespace UsbNddrintclr{ ///<USB New DD Request Interrupt Clear using Addr = Register::Address<0x2008c2b0,0x00000000,0x00000000,unsigned>; ///Clear endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Clear the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> epnddintclr0{}; ///Clear endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Clear the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> epnddintclr1{}; ///Clear endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Clear the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> epnddintclr2{}; ///Clear endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Clear the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> epnddintclr3{}; ///Clear endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Clear the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> epnddintclr4{}; ///Clear endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Clear the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> epnddintclr5{}; ///Clear endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Clear the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> epnddintclr6{}; ///Clear endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Clear the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> epnddintclr7{}; ///Clear endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Clear the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> epnddintclr8{}; ///Clear endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Clear the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> epnddintclr9{}; ///Clear endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Clear the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> epnddintclr10{}; ///Clear endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Clear the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> epnddintclr11{}; ///Clear endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Clear the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,unsigned> epnddintclr12{}; ///Clear endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Clear the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,unsigned> epnddintclr13{}; ///Clear endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Clear the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,unsigned> epnddintclr14{}; ///Clear endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Clear the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> epnddintclr15{}; ///Clear endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Clear the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,unsigned> epnddintclr16{}; ///Clear endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Clear the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,17),Register::ReadWriteAccess,unsigned> epnddintclr17{}; ///Clear endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Clear the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,18),Register::ReadWriteAccess,unsigned> epnddintclr18{}; ///Clear endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Clear the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,19),Register::ReadWriteAccess,unsigned> epnddintclr19{}; ///Clear endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Clear the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::ReadWriteAccess,unsigned> epnddintclr20{}; ///Clear endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Clear the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,21),Register::ReadWriteAccess,unsigned> epnddintclr21{}; ///Clear endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Clear the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::ReadWriteAccess,unsigned> epnddintclr22{}; ///Clear endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Clear the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,23),Register::ReadWriteAccess,unsigned> epnddintclr23{}; ///Clear endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Clear the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,24),Register::ReadWriteAccess,unsigned> epnddintclr24{}; ///Clear endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Clear the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,25),Register::ReadWriteAccess,unsigned> epnddintclr25{}; ///Clear endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Clear the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(26,26),Register::ReadWriteAccess,unsigned> epnddintclr26{}; ///Clear endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Clear the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,27),Register::ReadWriteAccess,unsigned> epnddintclr27{}; ///Clear endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Clear the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(28,28),Register::ReadWriteAccess,unsigned> epnddintclr28{}; ///Clear endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Clear the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,29),Register::ReadWriteAccess,unsigned> epnddintclr29{}; ///Clear endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Clear the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(30,30),Register::ReadWriteAccess,unsigned> epnddintclr30{}; ///Clear endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Clear the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,31),Register::ReadWriteAccess,unsigned> epnddintclr31{}; } namespace UsbNddrintset{ ///<USB New DD Request Interrupt Set using Addr = Register::Address<0x2008c2b4,0x00000000,0x00000000,unsigned>; ///Set endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Set the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> epnddintset0{}; ///Set endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Set the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> epnddintset1{}; ///Set endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Set the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> epnddintset2{}; ///Set endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Set the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> epnddintset3{}; ///Set endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Set the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> epnddintset4{}; ///Set endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Set the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> epnddintset5{}; ///Set endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Set the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> epnddintset6{}; ///Set endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Set the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> epnddintset7{}; ///Set endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Set the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> epnddintset8{}; ///Set endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Set the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> epnddintset9{}; ///Set endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Set the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> epnddintset10{}; ///Set endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Set the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> epnddintset11{}; ///Set endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Set the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,unsigned> epnddintset12{}; ///Set endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Set the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,unsigned> epnddintset13{}; ///Set endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Set the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,unsigned> epnddintset14{}; ///Set endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Set the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> epnddintset15{}; ///Set endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Set the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,unsigned> epnddintset16{}; ///Set endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Set the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,17),Register::ReadWriteAccess,unsigned> epnddintset17{}; ///Set endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Set the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,18),Register::ReadWriteAccess,unsigned> epnddintset18{}; ///Set endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Set the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,19),Register::ReadWriteAccess,unsigned> epnddintset19{}; ///Set endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Set the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::ReadWriteAccess,unsigned> epnddintset20{}; ///Set endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Set the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,21),Register::ReadWriteAccess,unsigned> epnddintset21{}; ///Set endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Set the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::ReadWriteAccess,unsigned> epnddintset22{}; ///Set endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Set the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,23),Register::ReadWriteAccess,unsigned> epnddintset23{}; ///Set endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Set the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,24),Register::ReadWriteAccess,unsigned> epnddintset24{}; ///Set endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Set the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,25),Register::ReadWriteAccess,unsigned> epnddintset25{}; ///Set endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Set the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(26,26),Register::ReadWriteAccess,unsigned> epnddintset26{}; ///Set endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Set the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,27),Register::ReadWriteAccess,unsigned> epnddintset27{}; ///Set endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Set the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(28,28),Register::ReadWriteAccess,unsigned> epnddintset28{}; ///Set endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Set the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,29),Register::ReadWriteAccess,unsigned> epnddintset29{}; ///Set endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Set the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(30,30),Register::ReadWriteAccess,unsigned> epnddintset30{}; ///Set endpoint xx (2 <= xx <= 31) new DD interrupt request. 0 = No effect. 1 = Set the EPxx new DD interrupt request in the USBNDDRIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,31),Register::ReadWriteAccess,unsigned> epnddintset31{}; } namespace UsbSyserrintst{ ///<USB System Error Interrupt Status using Addr = Register::Address<0x2008c2b8,0x00000000,0x00000000,unsigned>; ///Endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = There is no System Error Interrupt request for endpoint xx. 1 = There is a System Error Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> eperrintst0{}; ///Endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = There is no System Error Interrupt request for endpoint xx. 1 = There is a System Error Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> eperrintst1{}; ///Endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = There is no System Error Interrupt request for endpoint xx. 1 = There is a System Error Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> eperrintst2{}; ///Endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = There is no System Error Interrupt request for endpoint xx. 1 = There is a System Error Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> eperrintst3{}; ///Endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = There is no System Error Interrupt request for endpoint xx. 1 = There is a System Error Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> eperrintst4{}; ///Endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = There is no System Error Interrupt request for endpoint xx. 1 = There is a System Error Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> eperrintst5{}; ///Endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = There is no System Error Interrupt request for endpoint xx. 1 = There is a System Error Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> eperrintst6{}; ///Endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = There is no System Error Interrupt request for endpoint xx. 1 = There is a System Error Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> eperrintst7{}; ///Endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = There is no System Error Interrupt request for endpoint xx. 1 = There is a System Error Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> eperrintst8{}; ///Endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = There is no System Error Interrupt request for endpoint xx. 1 = There is a System Error Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> eperrintst9{}; ///Endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = There is no System Error Interrupt request for endpoint xx. 1 = There is a System Error Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> eperrintst10{}; ///Endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = There is no System Error Interrupt request for endpoint xx. 1 = There is a System Error Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> eperrintst11{}; ///Endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = There is no System Error Interrupt request for endpoint xx. 1 = There is a System Error Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,unsigned> eperrintst12{}; ///Endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = There is no System Error Interrupt request for endpoint xx. 1 = There is a System Error Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,unsigned> eperrintst13{}; ///Endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = There is no System Error Interrupt request for endpoint xx. 1 = There is a System Error Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,unsigned> eperrintst14{}; ///Endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = There is no System Error Interrupt request for endpoint xx. 1 = There is a System Error Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> eperrintst15{}; ///Endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = There is no System Error Interrupt request for endpoint xx. 1 = There is a System Error Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,unsigned> eperrintst16{}; ///Endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = There is no System Error Interrupt request for endpoint xx. 1 = There is a System Error Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,17),Register::ReadWriteAccess,unsigned> eperrintst17{}; ///Endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = There is no System Error Interrupt request for endpoint xx. 1 = There is a System Error Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,18),Register::ReadWriteAccess,unsigned> eperrintst18{}; ///Endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = There is no System Error Interrupt request for endpoint xx. 1 = There is a System Error Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,19),Register::ReadWriteAccess,unsigned> eperrintst19{}; ///Endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = There is no System Error Interrupt request for endpoint xx. 1 = There is a System Error Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::ReadWriteAccess,unsigned> eperrintst20{}; ///Endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = There is no System Error Interrupt request for endpoint xx. 1 = There is a System Error Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,21),Register::ReadWriteAccess,unsigned> eperrintst21{}; ///Endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = There is no System Error Interrupt request for endpoint xx. 1 = There is a System Error Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::ReadWriteAccess,unsigned> eperrintst22{}; ///Endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = There is no System Error Interrupt request for endpoint xx. 1 = There is a System Error Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,23),Register::ReadWriteAccess,unsigned> eperrintst23{}; ///Endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = There is no System Error Interrupt request for endpoint xx. 1 = There is a System Error Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,24),Register::ReadWriteAccess,unsigned> eperrintst24{}; ///Endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = There is no System Error Interrupt request for endpoint xx. 1 = There is a System Error Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,25),Register::ReadWriteAccess,unsigned> eperrintst25{}; ///Endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = There is no System Error Interrupt request for endpoint xx. 1 = There is a System Error Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(26,26),Register::ReadWriteAccess,unsigned> eperrintst26{}; ///Endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = There is no System Error Interrupt request for endpoint xx. 1 = There is a System Error Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,27),Register::ReadWriteAccess,unsigned> eperrintst27{}; ///Endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = There is no System Error Interrupt request for endpoint xx. 1 = There is a System Error Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(28,28),Register::ReadWriteAccess,unsigned> eperrintst28{}; ///Endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = There is no System Error Interrupt request for endpoint xx. 1 = There is a System Error Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,29),Register::ReadWriteAccess,unsigned> eperrintst29{}; ///Endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = There is no System Error Interrupt request for endpoint xx. 1 = There is a System Error Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(30,30),Register::ReadWriteAccess,unsigned> eperrintst30{}; ///Endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = There is no System Error Interrupt request for endpoint xx. 1 = There is a System Error Interrupt request for endpoint xx. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,31),Register::ReadWriteAccess,unsigned> eperrintst31{}; } namespace UsbSyserrintclr{ ///<USB System Error Interrupt Clear using Addr = Register::Address<0x2008c2bc,0x00000000,0x00000000,unsigned>; ///Clear endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Clear the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> eperrintclr0{}; ///Clear endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Clear the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> eperrintclr1{}; ///Clear endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Clear the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> eperrintclr2{}; ///Clear endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Clear the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> eperrintclr3{}; ///Clear endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Clear the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> eperrintclr4{}; ///Clear endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Clear the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> eperrintclr5{}; ///Clear endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Clear the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> eperrintclr6{}; ///Clear endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Clear the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> eperrintclr7{}; ///Clear endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Clear the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> eperrintclr8{}; ///Clear endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Clear the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> eperrintclr9{}; ///Clear endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Clear the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> eperrintclr10{}; ///Clear endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Clear the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> eperrintclr11{}; ///Clear endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Clear the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,unsigned> eperrintclr12{}; ///Clear endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Clear the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,unsigned> eperrintclr13{}; ///Clear endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Clear the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,unsigned> eperrintclr14{}; ///Clear endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Clear the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> eperrintclr15{}; ///Clear endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Clear the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,unsigned> eperrintclr16{}; ///Clear endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Clear the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,17),Register::ReadWriteAccess,unsigned> eperrintclr17{}; ///Clear endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Clear the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,18),Register::ReadWriteAccess,unsigned> eperrintclr18{}; ///Clear endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Clear the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,19),Register::ReadWriteAccess,unsigned> eperrintclr19{}; ///Clear endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Clear the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::ReadWriteAccess,unsigned> eperrintclr20{}; ///Clear endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Clear the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,21),Register::ReadWriteAccess,unsigned> eperrintclr21{}; ///Clear endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Clear the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::ReadWriteAccess,unsigned> eperrintclr22{}; ///Clear endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Clear the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,23),Register::ReadWriteAccess,unsigned> eperrintclr23{}; ///Clear endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Clear the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,24),Register::ReadWriteAccess,unsigned> eperrintclr24{}; ///Clear endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Clear the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,25),Register::ReadWriteAccess,unsigned> eperrintclr25{}; ///Clear endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Clear the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(26,26),Register::ReadWriteAccess,unsigned> eperrintclr26{}; ///Clear endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Clear the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,27),Register::ReadWriteAccess,unsigned> eperrintclr27{}; ///Clear endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Clear the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(28,28),Register::ReadWriteAccess,unsigned> eperrintclr28{}; ///Clear endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Clear the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,29),Register::ReadWriteAccess,unsigned> eperrintclr29{}; ///Clear endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Clear the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(30,30),Register::ReadWriteAccess,unsigned> eperrintclr30{}; ///Clear endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Clear the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,31),Register::ReadWriteAccess,unsigned> eperrintclr31{}; } namespace UsbSyserrintset{ ///<USB System Error Interrupt Set using Addr = Register::Address<0x2008c2c0,0x00000000,0x00000000,unsigned>; ///Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,unsigned> eperrintset0{}; ///Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,unsigned> eperrintset1{}; ///Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,unsigned> eperrintset2{}; ///Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,unsigned> eperrintset3{}; ///Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,unsigned> eperrintset4{}; ///Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> eperrintset5{}; ///Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> eperrintset6{}; ///Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> eperrintset7{}; ///Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> eperrintset8{}; ///Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> eperrintset9{}; ///Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,unsigned> eperrintset10{}; ///Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,unsigned> eperrintset11{}; ///Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(12,12),Register::ReadWriteAccess,unsigned> eperrintset12{}; ///Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(13,13),Register::ReadWriteAccess,unsigned> eperrintset13{}; ///Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(14,14),Register::ReadWriteAccess,unsigned> eperrintset14{}; ///Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,unsigned> eperrintset15{}; ///Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(16,16),Register::ReadWriteAccess,unsigned> eperrintset16{}; ///Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(17,17),Register::ReadWriteAccess,unsigned> eperrintset17{}; ///Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(18,18),Register::ReadWriteAccess,unsigned> eperrintset18{}; ///Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,19),Register::ReadWriteAccess,unsigned> eperrintset19{}; ///Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(20,20),Register::ReadWriteAccess,unsigned> eperrintset20{}; ///Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(21,21),Register::ReadWriteAccess,unsigned> eperrintset21{}; ///Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(22,22),Register::ReadWriteAccess,unsigned> eperrintset22{}; ///Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(23,23),Register::ReadWriteAccess,unsigned> eperrintset23{}; ///Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,24),Register::ReadWriteAccess,unsigned> eperrintset24{}; ///Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(25,25),Register::ReadWriteAccess,unsigned> eperrintset25{}; ///Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(26,26),Register::ReadWriteAccess,unsigned> eperrintset26{}; ///Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(27,27),Register::ReadWriteAccess,unsigned> eperrintset27{}; ///Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(28,28),Register::ReadWriteAccess,unsigned> eperrintset28{}; ///Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(29,29),Register::ReadWriteAccess,unsigned> eperrintset29{}; ///Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(30,30),Register::ReadWriteAccess,unsigned> eperrintset30{}; ///Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,31),Register::ReadWriteAccess,unsigned> eperrintset31{}; } namespace UsbI2cRx{ ///<I2C Receive using Addr = Register::Address<0x2008c300,0x00000000,0x00000000,unsigned>; ///Receive data. constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,0),Register::ReadWriteAccess,unsigned> rxData{}; ///Reserved. Read value is undefined, only zero should be written. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,8),Register::ReadWriteAccess,unsigned> reserved{}; } namespace UsbI2cTx{ ///<I2C Transmit using Addr = Register::Address<0x2008c300,0x00000000,0x00000000,unsigned>; ///Transmit data. constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,0),Register::ReadWriteAccess,unsigned> txdata{}; ///When 1, issue a START condition before transmitting this byte. constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,unsigned> start{}; ///When 1, issue a STOP condition after transmitting this byte. constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,unsigned> stop{}; ///Reserved. Read value is undefined, only zero should be written. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,10),Register::ReadWriteAccess,unsigned> reserved{}; } namespace UsbI2cSts{ ///<I2C Status using Addr = Register::Address<0x2008c304,0x00000000,0x00000000,unsigned>; ///Transaction Done Interrupt. This flag is set if a transaction completes successfully. It is cleared by writing a one to bit 0 of the status register. It is unaffected by slave transactions. enum class TdiVal { transactionHasNot=0x00000000, ///<Transaction has not completed. transactionComplete=0x00000001, ///<Transaction completed. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,TdiVal> tdi{}; namespace TdiValC{ constexpr Register::FieldValue<decltype(tdi)::Type,TdiVal::transactionHasNot> transactionHasNot{}; constexpr Register::FieldValue<decltype(tdi)::Type,TdiVal::transactionComplete> transactionComplete{}; } ///Arbitration Failure Interrupt. When transmitting, if the SDA is low when SDAOUT is high, then this I2C has lost the arbitration to another device on the bus. The Arbitration Failure bit is set when this happens. It is cleared by writing a one to bit 1 of the status register. enum class AfiVal { noArbitrationFailu=0x00000000, ///<No arbitration failure on last transmission. arbitrationFailure=0x00000001, ///<Arbitration failure occurred on last transmission. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,AfiVal> afi{}; namespace AfiValC{ constexpr Register::FieldValue<decltype(afi)::Type,AfiVal::noArbitrationFailu> noArbitrationFailu{}; constexpr Register::FieldValue<decltype(afi)::Type,AfiVal::arbitrationFailure> arbitrationFailure{}; } ///No Acknowledge Interrupt. After every byte of data is sent, the transmitter expects an acknowledge from the receiver. This bit is set if the acknowledge is not received. It is cleared when a byte is written to the master TX FIFO. enum class NaiVal { lastTransmissionRe=0x00000000, ///<Last transmission received an acknowledge. lastTransmissionDi=0x00000001, ///<Last transmission did not receive an acknowledge. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,NaiVal> nai{}; namespace NaiValC{ constexpr Register::FieldValue<decltype(nai)::Type,NaiVal::lastTransmissionRe> lastTransmissionRe{}; constexpr Register::FieldValue<decltype(nai)::Type,NaiVal::lastTransmissionDi> lastTransmissionDi{}; } ///Master Data Request Interrupt. Once a transmission is started, the transmitter must have data to transmit as long as it isn't followed by a stop condition or it will hold SCL low until more data is available. The Master Data Request bit is set when the master transmitter is data-starved. If the master TX FIFO is empty and the last byte did not have a STOP condition flag, then SCL is held low until the CPU writes another byte to transmit. This bit is cleared when a byte is written to the master TX FIFO. enum class DrmiVal { masterTransmitterD=0x00000000, ///<Master transmitter does not need data. masterTransmitterN=0x00000001, ///<Master transmitter needs data. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,DrmiVal> drmi{}; namespace DrmiValC{ constexpr Register::FieldValue<decltype(drmi)::Type,DrmiVal::masterTransmitterD> masterTransmitterD{}; constexpr Register::FieldValue<decltype(drmi)::Type,DrmiVal::masterTransmitterN> masterTransmitterN{}; } ///Slave Data Request Interrupt. Once a transmission is started, the transmitter must have data to transmit as long as it isn't followed by a STOP condition or it will hold SCL low until more data is available. The Slave Data Request bit is set when the slave transmitter is data-starved. If the slave TX FIFO is empty and the last byte transmitted was acknowledged, then SCL is held low until the CPU writes another byte to transmit. This bit is cleared when a byte is written to the slave Tx FIFO. enum class DrsiVal { slaveTransmitterDo=0x00000000, ///<Slave transmitter does not need data. slaveTransmitterNe=0x00000001, ///<Slave transmitter needs data. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,DrsiVal> drsi{}; namespace DrsiValC{ constexpr Register::FieldValue<decltype(drsi)::Type,DrsiVal::slaveTransmitterDo> slaveTransmitterDo{}; constexpr Register::FieldValue<decltype(drsi)::Type,DrsiVal::slaveTransmitterNe> slaveTransmitterNe{}; } ///Indicates whether the bus is busy. This bit is set when a START condition has been seen. It is cleared when a STOP condition is seen.. constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,unsigned> active{}; ///The current value of the SCL signal. constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,unsigned> scl{}; ///The current value of the SDA signal. constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,unsigned> sda{}; ///Receive FIFO Full (RFF). This bit is set when the RX FIFO is full and cannot accept any more data. It is cleared when the RX FIFO is not full. If a byte arrives when the Receive FIFO is full, the SCL is held low until the CPU reads the RX FIFO and makes room for it. enum class RffVal { rxFifoIsNotFull=0x00000000, ///<RX FIFO is not full rxFifoIsFull=0x00000001, ///<RX FIFO is full }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,RffVal> rff{}; namespace RffValC{ constexpr Register::FieldValue<decltype(rff)::Type,RffVal::rxFifoIsNotFull> rxFifoIsNotFull{}; constexpr Register::FieldValue<decltype(rff)::Type,RffVal::rxFifoIsFull> rxFifoIsFull{}; } ///Receive FIFO Empty. RFE is set when the RX FIFO is empty and is cleared when the RX FIFO contains valid data. enum class RfeVal { rxFifoContainsDat=0x00000000, ///<RX FIFO contains data. rxFifoIsEmpty=0x00000001, ///<RX FIFO is empty }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(9,9),Register::ReadWriteAccess,RfeVal> rfe{}; namespace RfeValC{ constexpr Register::FieldValue<decltype(rfe)::Type,RfeVal::rxFifoContainsDat> rxFifoContainsDat{}; constexpr Register::FieldValue<decltype(rfe)::Type,RfeVal::rxFifoIsEmpty> rxFifoIsEmpty{}; } ///Transmit FIFO Full. TFF is set when the TX FIFO is full and is cleared when the TX FIFO is not full. enum class TffVal { txFifoIsNotFull=0x00000000, ///<TX FIFO is not full. txFifoIsFull=0x00000001, ///<TX FIFO is full }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,10),Register::ReadWriteAccess,TffVal> tff{}; namespace TffValC{ constexpr Register::FieldValue<decltype(tff)::Type,TffVal::txFifoIsNotFull> txFifoIsNotFull{}; constexpr Register::FieldValue<decltype(tff)::Type,TffVal::txFifoIsFull> txFifoIsFull{}; } ///Transmit FIFO Empty. TFE is set when the TX FIFO is empty and is cleared when the TX FIFO contains valid data. enum class TfeVal { txFifoContainsVal=0x00000000, ///<TX FIFO contains valid data. txFifoIsEmpty=0x00000001, ///<TX FIFO is empty }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(11,11),Register::ReadWriteAccess,TfeVal> tfe{}; namespace TfeValC{ constexpr Register::FieldValue<decltype(tfe)::Type,TfeVal::txFifoContainsVal> txFifoContainsVal{}; constexpr Register::FieldValue<decltype(tfe)::Type,TfeVal::txFifoIsEmpty> txFifoIsEmpty{}; } ///Reserved. Read value is undefined, only zero should be written. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,12),Register::ReadWriteAccess,unsigned> reserved{}; } namespace UsbI2cCtl{ ///<I2C Control using Addr = Register::Address<0x2008c308,0x00000000,0x00000000,unsigned>; ///Transmit Done Interrupt Enable. This enables the TDI interrupt signalling that this I2C issued a STOP condition. enum class TdieVal { disableTheTdiInte=0x00000000, ///<Disable the TDI interrupt. enableTheTdiInter=0x00000001, ///<Enable the TDI interrupt. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,TdieVal> tdie{}; namespace TdieValC{ constexpr Register::FieldValue<decltype(tdie)::Type,TdieVal::disableTheTdiInte> disableTheTdiInte{}; constexpr Register::FieldValue<decltype(tdie)::Type,TdieVal::enableTheTdiInter> enableTheTdiInter{}; } ///Transmitter Arbitration Failure Interrupt Enable. This enables the AFI interrupt which is asserted during transmission when trying to set SDA high, but the bus is driven low by another device. enum class AfieVal { disableTheAfi=0x00000000, ///<Disable the AFI. enableTheAfi=0x00000001, ///<Enable the AFI. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,AfieVal> afie{}; namespace AfieValC{ constexpr Register::FieldValue<decltype(afie)::Type,AfieVal::disableTheAfi> disableTheAfi{}; constexpr Register::FieldValue<decltype(afie)::Type,AfieVal::enableTheAfi> enableTheAfi{}; } ///Transmitter No Acknowledge Interrupt Enable. This enables the NAI interrupt signalling that transmitted byte was not acknowledged. enum class NaieVal { disableTheNai=0x00000000, ///<Disable the NAI. enableTheNai=0x00000001, ///<Enable the NAI. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,NaieVal> naie{}; namespace NaieValC{ constexpr Register::FieldValue<decltype(naie)::Type,NaieVal::disableTheNai> disableTheNai{}; constexpr Register::FieldValue<decltype(naie)::Type,NaieVal::enableTheNai> enableTheNai{}; } ///Master Transmitter Data Request Interrupt Enable. This enables the DRMI interrupt which signals that the master transmitter has run out of data, has not issued a STOP, and is holding the SCL line low. enum class DrmieVal { disableTheDrmiInt=0x00000000, ///<Disable the DRMI interrupt. enableTheDrmiInte=0x00000001, ///<Enable the DRMI interrupt. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,DrmieVal> drmie{}; namespace DrmieValC{ constexpr Register::FieldValue<decltype(drmie)::Type,DrmieVal::disableTheDrmiInt> disableTheDrmiInt{}; constexpr Register::FieldValue<decltype(drmie)::Type,DrmieVal::enableTheDrmiInte> enableTheDrmiInte{}; } ///Slave Transmitter Data Request Interrupt Enable. This enables the DRSI interrupt which signals that the slave transmitter has run out of data and the last byte was acknowledged, so the SCL line is being held low. enum class DrsieVal { disableTheDrsiInt=0x00000000, ///<Disable the DRSI interrupt. enableTheDrsiInte=0x00000001, ///<Enable the DRSI interrupt. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,DrsieVal> drsie{}; namespace DrsieValC{ constexpr Register::FieldValue<decltype(drsie)::Type,DrsieVal::disableTheDrsiInt> disableTheDrsiInt{}; constexpr Register::FieldValue<decltype(drsie)::Type,DrsieVal::enableTheDrsiInte> enableTheDrsiInte{}; } ///Receive FIFO Full Interrupt Enable. This enables the Receive FIFO Full interrupt to indicate that the receive FIFO cannot accept any more data. enum class RefieVal { disableTheRffi=0x00000000, ///<Disable the RFFI. enableTheRffi=0x00000001, ///<Enable the RFFI. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(5,5),Register::ReadWriteAccess,RefieVal> refie{}; namespace RefieValC{ constexpr Register::FieldValue<decltype(refie)::Type,RefieVal::disableTheRffi> disableTheRffi{}; constexpr Register::FieldValue<decltype(refie)::Type,RefieVal::enableTheRffi> enableTheRffi{}; } ///Receive Data Available Interrupt Enable. This enables the DAI interrupt to indicate that data is available in the receive FIFO (i.e. not empty). enum class RfdaieVal { disableTheDai=0x00000000, ///<Disable the DAI. enableTheDai=0x00000001, ///<Enable the DAI. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(6,6),Register::ReadWriteAccess,RfdaieVal> rfdaie{}; namespace RfdaieValC{ constexpr Register::FieldValue<decltype(rfdaie)::Type,RfdaieVal::disableTheDai> disableTheDai{}; constexpr Register::FieldValue<decltype(rfdaie)::Type,RfdaieVal::enableTheDai> enableTheDai{}; } ///Transmit FIFO Not Full Interrupt Enable. This enables the Transmit FIFO Not Full interrupt to indicate that the more data can be written to the transmit FIFO. Note that this is not full. It is intended help the CPU to write to the I2C block only when there is room in the FIFO and do this without polling the status register. enum class TffieVal { disableTheTffi=0x00000000, ///<Disable the TFFI. enableTheTffi=0x00000001, ///<Enable the TFFI. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,7),Register::ReadWriteAccess,TffieVal> tffie{}; namespace TffieValC{ constexpr Register::FieldValue<decltype(tffie)::Type,TffieVal::disableTheTffi> disableTheTffi{}; constexpr Register::FieldValue<decltype(tffie)::Type,TffieVal::enableTheTffi> enableTheTffi{}; } ///Soft reset. This is only needed in unusual circumstances. If a device issues a start condition without issuing a stop condition. A system timer may be used to reset the I2C if the bus remains busy longer than the time-out period. On a soft reset, the Tx and Rx FIFOs are flushed, I2C_STS register is cleared, and all internal state machines are reset to appear idle. The I2C_CLKHI, I2C_CLKLO and I2C_CTL (except Soft Reset Bit) are NOT modified by a soft reset. enum class SrstVal { seeTheText=0x00000000, ///<See the text. resetTheI2cToIdl=0x00000001, ///<Reset the I2C to idle state. Self clearing. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(8,8),Register::ReadWriteAccess,SrstVal> srst{}; namespace SrstValC{ constexpr Register::FieldValue<decltype(srst)::Type,SrstVal::seeTheText> seeTheText{}; constexpr Register::FieldValue<decltype(srst)::Type,SrstVal::resetTheI2cToIdl> resetTheI2cToIdl{}; } ///Reserved. Read value is undefined, only zero should be written. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,9),Register::ReadWriteAccess,unsigned> reserved{}; } namespace UsbI2cClkhi{ ///<I2C Clock High using Addr = Register::Address<0x2008c30c,0x00000000,0x00000000,unsigned>; ///Clock divisor high. This value is the number of 48 MHz clocks the serial clock (SCL) will be high. constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,0),Register::ReadWriteAccess,unsigned> cdhi{}; ///Reserved. Read value is undefined, only zero should be written. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,8),Register::ReadWriteAccess,unsigned> reserved{}; } namespace UsbI2cClklo{ ///<I2C Clock Low using Addr = Register::Address<0x2008c310,0x00000000,0x00000000,unsigned>; ///Clock divisor low. This value is the number of 48 MHz clocks the serial clock (SCL) will be low. constexpr Register::FieldLocation<Addr,Register::maskFromRange(7,0),Register::ReadWriteAccess,unsigned> cdlo{}; ///Reserved. Read value is undefined, only zero should be written. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,8),Register::ReadWriteAccess,unsigned> reserved{}; } namespace UsbClkctrl{ ///<OTG clock controller using Addr = Register::Address<0x2008cff4,0x00000000,0x00000000,unsigned>; ///Host clock enable enum class HostclkenVal { disableTheHostClo=0x00000000, ///<Disable the Host clock. enableTheHostCloc=0x00000001, ///<Enable the Host clock. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,HostclkenVal> hostClkEn{}; namespace HostclkenValC{ constexpr Register::FieldValue<decltype(hostClkEn)::Type,HostclkenVal::disableTheHostClo> disableTheHostClo{}; constexpr Register::FieldValue<decltype(hostClkEn)::Type,HostclkenVal::enableTheHostCloc> enableTheHostCloc{}; } ///Device clock enable enum class DevclkenVal { disableTheDeviceC=0x00000000, ///<Disable the Device clock. enableTheDeviceCl=0x00000001, ///<Enable the Device clock. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,DevclkenVal> devClkEn{}; namespace DevclkenValC{ constexpr Register::FieldValue<decltype(devClkEn)::Type,DevclkenVal::disableTheDeviceC> disableTheDeviceC{}; constexpr Register::FieldValue<decltype(devClkEn)::Type,DevclkenVal::enableTheDeviceCl> enableTheDeviceCl{}; } ///I2C clock enable enum class I2cclkenVal { disableTheI2cCloc=0x00000000, ///<Disable the I2C clock. enableTheI2cClock=0x00000001, ///<Enable the I2C clock. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,I2cclkenVal> i2cClkEn{}; namespace I2cclkenValC{ constexpr Register::FieldValue<decltype(i2cClkEn)::Type,I2cclkenVal::disableTheI2cCloc> disableTheI2cCloc{}; constexpr Register::FieldValue<decltype(i2cClkEn)::Type,I2cclkenVal::enableTheI2cClock> enableTheI2cClock{}; } ///OTG clock enable. In device-only applications, this bit enables access to the PORTSEL register. enum class OtgclkenVal { disableTheOtgCloc=0x00000000, ///<Disable the OTG clock. enableTheOtgClock=0x00000001, ///<Enable the OTG clock. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,OtgclkenVal> otgClkEn{}; namespace OtgclkenValC{ constexpr Register::FieldValue<decltype(otgClkEn)::Type,OtgclkenVal::disableTheOtgCloc> disableTheOtgCloc{}; constexpr Register::FieldValue<decltype(otgClkEn)::Type,OtgclkenVal::enableTheOtgClock> enableTheOtgClock{}; } ///AHB master clock enable enum class AhbclkenVal { disableTheAhbCloc=0x00000000, ///<Disable the AHB clock. enableTheAhbClock=0x00000001, ///<Enable the AHB clock. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,AhbclkenVal> ahbClkEn{}; namespace AhbclkenValC{ constexpr Register::FieldValue<decltype(ahbClkEn)::Type,AhbclkenVal::disableTheAhbCloc> disableTheAhbCloc{}; constexpr Register::FieldValue<decltype(ahbClkEn)::Type,AhbclkenVal::enableTheAhbClock> enableTheAhbClock{}; } ///Reserved. Read value is undefined, only zero should be written. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,5),Register::ReadWriteAccess,unsigned> reserved{}; } namespace UsbOtgclkst{ ///<OTG clock status using Addr = Register::Address<0x2008cff8,0x00000000,0x00000000,unsigned>; ///Host clock status. enum class HostclkonVal { hostClockIsNotAv=0x00000000, ///<Host clock is not available. hostClockIsAvaila=0x00000001, ///<Host clock is available. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,HostclkonVal> hostClkOn{}; namespace HostclkonValC{ constexpr Register::FieldValue<decltype(hostClkOn)::Type,HostclkonVal::hostClockIsNotAv> hostClockIsNotAv{}; constexpr Register::FieldValue<decltype(hostClkOn)::Type,HostclkonVal::hostClockIsAvaila> hostClockIsAvaila{}; } ///Device clock status. enum class DevclkonVal { deviceClockIsNot=0x00000000, ///<Device clock is not available. deviceClockIsAvai=0x00000001, ///<Device clock is available. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,DevclkonVal> devClkOn{}; namespace DevclkonValC{ constexpr Register::FieldValue<decltype(devClkOn)::Type,DevclkonVal::deviceClockIsNot> deviceClockIsNot{}; constexpr Register::FieldValue<decltype(devClkOn)::Type,DevclkonVal::deviceClockIsAvai> deviceClockIsAvai{}; } ///I2C clock status. enum class I2cclkonVal { i2cClockIsNotAva=0x00000000, ///<I2C clock is not available. i2cClockIsAvailab=0x00000001, ///<I2C clock is available. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,I2cclkonVal> i2cClkOn{}; namespace I2cclkonValC{ constexpr Register::FieldValue<decltype(i2cClkOn)::Type,I2cclkonVal::i2cClockIsNotAva> i2cClockIsNotAva{}; constexpr Register::FieldValue<decltype(i2cClkOn)::Type,I2cclkonVal::i2cClockIsAvailab> i2cClockIsAvailab{}; } ///OTG clock status. enum class OtgclkonVal { otgClockIsNotAva=0x00000000, ///<OTG clock is not available. otgClockIsAvailab=0x00000001, ///<OTG clock is available. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(3,3),Register::ReadWriteAccess,OtgclkonVal> otgClkOn{}; namespace OtgclkonValC{ constexpr Register::FieldValue<decltype(otgClkOn)::Type,OtgclkonVal::otgClockIsNotAva> otgClockIsNotAva{}; constexpr Register::FieldValue<decltype(otgClkOn)::Type,OtgclkonVal::otgClockIsAvailab> otgClockIsAvailab{}; } ///AHB master clock status. enum class AhbclkonVal { ahbClockIsNotAva=0x00000000, ///<AHB clock is not available. ahbClockIsAvailab=0x00000001, ///<AHB clock is available. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(4,4),Register::ReadWriteAccess,AhbclkonVal> ahbClkOn{}; namespace AhbclkonValC{ constexpr Register::FieldValue<decltype(ahbClkOn)::Type,AhbclkonVal::ahbClockIsNotAva> ahbClockIsNotAva{}; constexpr Register::FieldValue<decltype(ahbClkOn)::Type,AhbclkonVal::ahbClockIsAvailab> ahbClockIsAvailab{}; } ///Reserved. Read value is undefined, only zero should be written. constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,5),Register::ReadWriteAccess,unsigned> reserved{}; } }
117.53263
518
0.721419
cjsmeele
e165bab0a9f27073927ad49271fd4f58cabe94cd
21,943
cc
C++
src/developer/memory/monitor/monitor.cc
re995/fuchsia
02cb86f760af2aac974ba654186b73af8c16638f
[ "BSD-2-Clause" ]
1
2021-12-23T01:55:48.000Z
2021-12-23T01:55:48.000Z
src/developer/memory/monitor/monitor.cc
re995/fuchsia
02cb86f760af2aac974ba654186b73af8c16638f
[ "BSD-2-Clause" ]
1
2020-01-07T00:50:54.000Z
2020-03-28T03:56:01.000Z
src/developer/memory/monitor/monitor.cc
re995/fuchsia
02cb86f760af2aac974ba654186b73af8c16638f
[ "BSD-2-Clause" ]
1
2021-12-23T06:22:27.000Z
2021-12-23T06:22:27.000Z
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/developer/memory/monitor/monitor.h" #include <errno.h> #include <fcntl.h> #include <lib/async/cpp/task.h> #include <lib/async/cpp/time.h> #include <lib/async/default.h> #include <lib/inspect/cpp/inspect.h> #include <lib/syslog/cpp/macros.h> #include <lib/trace/event.h> #include <lib/vfs/cpp/internal/file.h> #include <lib/vfs/cpp/vmo_file.h> #include <lib/zx/time.h> #include <lib/zx/vmo.h> #include <string.h> #include <zircon/status.h> #include <zircon/types.h> #include <filesystem> #include <iostream> #include <iterator> #include <memory> #include <soc/aml-common/aml-ram.h> #include <trace-vthread/event_vthread.h> #include "fuchsia/mem/cpp/fidl.h" #include "src/developer/memory/metrics/bucket_match.h" #include "src/developer/memory/metrics/capture.h" #include "src/developer/memory/metrics/printer.h" #include "src/developer/memory/monitor/high_water.h" #include "src/developer/memory/monitor/memory_metrics_registry.cb.h" #include "src/lib/fsl/vmo/file.h" #include "src/lib/fsl/vmo/sized_vmo.h" #include "src/lib/fxl/command_line.h" #include "src/lib/fxl/strings/string_number_conversions.h" namespace monitor { using namespace memory; const char Monitor::kTraceName[] = "memory_monitor"; namespace { // Path to the configuration file for buckets. const std::string kBucketConfigPath = "/config/data/buckets.json"; const zx::duration kHighWaterPollFrequency = zx::sec(10); const uint64_t kHighWaterThreshold = 10 * 1024 * 1024; const zx::duration kMetricsPollFrequency = zx::min(5); const char kTraceNameHighPrecisionBandwidth[] = "memory_monitor:high_precision_bandwidth"; const char kTraceNameHighPrecisionBandwidthCamera[] = "memory_monitor:high_precision_bandwidth_camera"; constexpr uint64_t kMaxPendingBandwidthMeasurements = 4; constexpr uint64_t kMemCyclesToMeasure = 792000000 / 20; // 50 ms on sherlock constexpr uint64_t kMemCyclesToMeasureHighPrecision = 792000000 / 1000; // 1 ms // TODO(fxbug.dev/48254): Get default channel information through the FIDL API. struct RamChannel { const char* name; uint64_t mask; }; constexpr RamChannel kRamDefaultChannels[] = { {.name = "cpu", .mask = aml_ram::kDefaultChannelCpu}, {.name = "gpu", .mask = aml_ram::kDefaultChannelGpu}, {.name = "vdec", .mask = aml_ram::kDefaultChannelVDec}, {.name = "vpu", .mask = aml_ram::kDefaultChannelVpu}, }; constexpr RamChannel kRamCameraChannels[] = { {.name = "cpu", .mask = aml_ram::kDefaultChannelCpu}, {.name = "isp", .mask = aml_ram::kPortIdMipiIsp}, {.name = "gdc", .mask = aml_ram::kPortIdGDC}, {.name = "ge2d", .mask = aml_ram::kPortIdGe2D}, }; uint64_t CounterToBandwidth(uint64_t counter, uint64_t frequency, uint64_t cycles) { return counter * frequency / cycles; } zx_ticks_t TimestampToTicks(zx_time_t timestamp) { __uint128_t temp = static_cast<__uint128_t>(timestamp) * zx_ticks_per_second() / ZX_SEC(1); return static_cast<zx_ticks_t>(temp); } fuchsia::hardware::ram::metrics::BandwidthMeasurementConfig BuildConfig( uint64_t cycles_to_measure, bool use_camera_channels = false) { fuchsia::hardware::ram::metrics::BandwidthMeasurementConfig config = {}; config.cycles_to_measure = cycles_to_measure; size_t num_channels = std::size(kRamDefaultChannels); const auto* channels = kRamDefaultChannels; if (use_camera_channels) { num_channels = std::size(kRamCameraChannels); channels = kRamCameraChannels; } for (size_t i = 0; i < num_channels; i++) { config.channels[i] = channels[i].mask; } return config; } uint64_t TotalReadWriteCycles(const fuchsia::hardware::ram::metrics::BandwidthInfo& info) { uint64_t total_readwrite_cycles = 0; for (auto& channel : info.channels) { total_readwrite_cycles += channel.readwrite_cycles; } return total_readwrite_cycles; } std::vector<memory::BucketMatch> CreateBucketMatchesFromConfigData() { if (!std::filesystem::exists(kBucketConfigPath)) { FX_LOGS(WARNING) << "Bucket configuration file not found; no buckets will be available."; return {}; } std::string configuration_str; FX_CHECK(files::ReadFileToString(kBucketConfigPath, &configuration_str)); auto bucket_matches = memory::BucketMatch::ReadBucketMatchesFromConfig(configuration_str); FX_CHECK(bucket_matches.has_value()) << "Unable to read configuration: " << configuration_str; return std::move(*bucket_matches); } } // namespace Monitor::Monitor(std::unique_ptr<sys::ComponentContext> context, const fxl::CommandLine& command_line, async_dispatcher_t* dispatcher, bool send_metrics, bool watch_memory_pressure, bool send_critical_pressure_crash_reports) : prealloc_size_(0), logging_(command_line.HasOption("log")), tracing_(false), delay_(zx::sec(1)), dispatcher_(dispatcher), component_context_(std::move(context)), inspector_(component_context_.get()), logger_( dispatcher_, [this](Capture* c) { return GetCapture(c); }, [this](const Capture& c, Digest* d) { GetDigest(c, d); }), level_(Level::kNumLevels) { auto bucket_matches = CreateBucketMatchesFromConfigData(); digester_ = std::make_unique<Digester>(Digester(bucket_matches)); high_water_ = std::make_unique<HighWater>( "/cache", kHighWaterPollFrequency, kHighWaterThreshold, dispatcher, [this](Capture* c, CaptureLevel l) { return Capture::GetCapture(c, capture_state_, l); }, [this](const Capture& c, Digest* d) { digester_->Digest(c, d); }); auto s = Capture::GetCaptureState(&capture_state_); if (s != ZX_OK) { FX_LOGS(ERROR) << "Error getting capture state: " << zx_status_get_string(s); exit(EXIT_FAILURE); } if (send_metrics) CreateMetrics(bucket_matches); // Expose lazy values under the root, populated from the Inspect method. inspector_.root().CreateLazyValues( "memory_measurements", [this, bucket_matches = std::move(bucket_matches)] { return fit::make_result_promise(fit::ok(Inspect(bucket_matches))); }, &inspector_); component_context_->outgoing()->AddPublicService(bindings_.GetHandler(this)); if (command_line.HasOption("help")) { PrintHelp(); exit(EXIT_SUCCESS); } std::string delay_as_string; if (command_line.GetOptionValue("delay", &delay_as_string)) { unsigned delay_as_int; if (!fxl::StringToNumberWithError<unsigned>(delay_as_string, &delay_as_int)) { FX_LOGS(ERROR) << "Invalid value for delay: " << delay_as_string; exit(-1); } delay_ = zx::msec(delay_as_int); } std::string prealloc_as_string; if (command_line.GetOptionValue("prealloc", &prealloc_as_string)) { FX_LOGS(INFO) << "prealloc_string: " << prealloc_as_string; if (!fxl::StringToNumberWithError<uint64_t>(prealloc_as_string, &prealloc_size_)) { FX_LOGS(ERROR) << "Invalid value for prealloc: " << prealloc_as_string; exit(-1); } prealloc_size_ *= (1024 * 1024); auto status = zx::vmo::create(prealloc_size_, 0, &prealloc_vmo_); if (status != ZX_OK) { FX_LOGS(ERROR) << "zx::vmo::create() returns " << zx_status_get_string(status); exit(-1); } prealloc_vmo_.get_size(&prealloc_size_); uintptr_t prealloc_addr = 0; status = zx::vmar::root_self()->map(ZX_VM_PERM_READ, 0, prealloc_vmo_, 0, prealloc_size_, &prealloc_addr); if (status != ZX_OK) { FX_LOGS(ERROR) << "zx::vmar::map() returns " << zx_status_get_string(status); exit(-1); } status = prealloc_vmo_.op_range(ZX_VMO_OP_COMMIT, 0, prealloc_size_, NULL, 0); if (status != ZX_OK) { FX_LOGS(ERROR) << "zx::vmo::op_range() returns " << zx_status_get_string(status); exit(-1); } } trace_observer_.Start(dispatcher_, [this] { UpdateState(); }); if (logging_) { Capture capture; auto s = Capture::GetCapture(&capture, capture_state_, KMEM); if (s != ZX_OK) { FX_LOGS(ERROR) << "Error getting capture: " << zx_status_get_string(s); exit(EXIT_FAILURE); } const auto& kmem = capture.kmem(); FX_LOGS(INFO) << "Total: " << kmem.total_bytes << " Wired: " << kmem.wired_bytes << " Total Heap: " << kmem.total_heap_bytes; } pressure_notifier_ = std::make_unique<PressureNotifier>( watch_memory_pressure, send_critical_pressure_crash_reports, component_context_.get(), dispatcher, [this](Level l) { PressureLevelChanged(l); }); memory_debugger_ = std::make_unique<MemoryDebugger>(component_context_.get(), pressure_notifier_.get()); SampleAndPost(); } Monitor::~Monitor() {} void Monitor::SetRamDevice(fuchsia::hardware::ram::metrics::DevicePtr ptr) { ram_device_ = std::move(ptr); if (ram_device_.is_bound()) PeriodicMeasureBandwidth(); } void Monitor::CreateMetrics(const std::vector<memory::BucketMatch>& bucket_matches) { // Connect to the cobalt fidl service provided by the environment. fuchsia::cobalt::LoggerFactorySyncPtr factory; component_context_->svc()->Connect(factory.NewRequest()); if (!factory) { FX_LOGS(ERROR) << "Unable to get cobalt.LoggerFactory."; return; } // Create a Cobalt Logger. The ID name is the one we specified in the // Cobalt metrics registry. fuchsia::cobalt::Status status = fuchsia::cobalt::Status::INTERNAL_ERROR; factory->CreateLoggerFromProjectId(cobalt_registry::kProjectId, cobalt_logger_.NewRequest(), &status); if (status != fuchsia::cobalt::Status::OK) { FX_LOGS(ERROR) << "Unable to get cobalt.Logger from factory."; return; } metrics_ = std::make_unique<Metrics>( bucket_matches, kMetricsPollFrequency, dispatcher_, &inspector_, cobalt_logger_.get(), [this](Capture* c) { return GetCapture(c); }, [this](const Capture& c, Digest* d) { GetDigest(c, d); }); } void Monitor::Watch(fidl::InterfaceHandle<fuchsia::memory::Watcher> watcher) { fuchsia::memory::WatcherPtr watcher_proxy = watcher.Bind(); fuchsia::memory::Watcher* proxy_raw_ptr = watcher_proxy.get(); watcher_proxy.set_error_handler( [this, proxy_raw_ptr](zx_status_t status) { ReleaseWatcher(proxy_raw_ptr); }); watchers_.push_back(std::move(watcher_proxy)); SampleAndPost(); } void Monitor::ReleaseWatcher(fuchsia::memory::Watcher* watcher) { auto predicate = [watcher](const auto& target) { return target.get() == watcher; }; watchers_.erase(std::remove_if(watchers_.begin(), watchers_.end(), predicate)); } void Monitor::NotifyWatchers(const zx_info_kmem_stats_t& kmem_stats) { fuchsia::memory::Stats stats{ .total_bytes = kmem_stats.total_bytes, .free_bytes = kmem_stats.free_bytes, .wired_bytes = kmem_stats.wired_bytes, .total_heap_bytes = kmem_stats.total_heap_bytes, .free_heap_bytes = kmem_stats.free_heap_bytes, .vmo_bytes = kmem_stats.vmo_bytes, .mmu_overhead_bytes = kmem_stats.mmu_overhead_bytes, .ipc_bytes = kmem_stats.ipc_bytes, .other_bytes = kmem_stats.other_bytes, }; for (auto& watcher : watchers_) { watcher->OnChange(stats); } } void Monitor::PrintHelp() { std::cout << "memory_monitor [options]" << std::endl; std::cout << "Options:" << std::endl; std::cout << " --log" << std::endl; std::cout << " --prealloc=kbytes" << std::endl; std::cout << " --delay=msecs" << std::endl; } inspect::Inspector Monitor::Inspect(const std::vector<memory::BucketMatch>& bucket_matches) { inspect::Inspector inspector(inspect::InspectSettings{.maximum_size = 1024 * 1024}); auto& root = inspector.GetRoot(); Capture capture; Capture::GetCapture(&capture, capture_state_, VMO); Summary summary(capture, Summary::kNameMatches); std::ostringstream summary_stream; Printer summary_printer(summary_stream); summary_printer.PrintSummary(summary, VMO, SORTED); auto current_string = summary_stream.str(); auto high_water_string = high_water_->GetHighWater(); auto previous_high_water_string = high_water_->GetPreviousHighWater(); if (!current_string.empty()) { root.CreateString("current", current_string, &inspector); } if (!high_water_string.empty()) { root.CreateString("high_water", high_water_string, &inspector); } if (!previous_high_water_string.empty()) { root.CreateString("high_water_previous_boot", previous_high_water_string, &inspector); } // Expose raw values for downstream computation. auto values = root.CreateChild("values"); values.CreateUint("free_bytes", capture.kmem().free_bytes, &inspector); values.CreateUint("free_heap_bytes", capture.kmem().free_heap_bytes, &inspector); values.CreateUint("ipc_bytes", capture.kmem().ipc_bytes, &inspector); values.CreateUint("mmu_overhead_bytes", capture.kmem().mmu_overhead_bytes, &inspector); values.CreateUint("other_bytes", capture.kmem().other_bytes, &inspector); values.CreateUint("total_bytes", capture.kmem().total_bytes, &inspector); values.CreateUint("total_heap_bytes", capture.kmem().total_heap_bytes, &inspector); values.CreateUint("vmo_bytes", capture.kmem().vmo_bytes, &inspector); values.CreateUint("wired_bytes", capture.kmem().wired_bytes, &inspector); inspector.emplace(std::move(values)); Digest digest; digester_->Digest(capture, &digest); std::ostringstream digest_stream; Printer digest_printer(digest_stream); digest_printer.PrintDigest(digest); auto current_digest_string = digest_stream.str(); auto high_water_digest_string = high_water_->GetHighWaterDigest(); auto previous_high_water_digest_string = high_water_->GetPreviousHighWaterDigest(); if (!current_digest_string.empty()) { root.CreateString("current_digest", current_digest_string, &inspector); } if (!high_water_digest_string.empty()) { root.CreateString("high_water_digest", high_water_digest_string, &inspector); } if (!previous_high_water_digest_string.empty()) { root.CreateString("high_water_digest_previous_boot", previous_high_water_digest_string, &inspector); } return inspector; } void Monitor::SampleAndPost() { if (logging_ || tracing_ || watchers_.size() > 0) { Capture capture; auto s = Capture::GetCapture(&capture, capture_state_, KMEM); if (s != ZX_OK) { FX_LOGS(ERROR) << "Error getting capture: " << zx_status_get_string(s); return; } const auto& kmem = capture.kmem(); if (logging_) { FX_LOGS(INFO) << "Free: " << kmem.free_bytes << " Free Heap: " << kmem.free_heap_bytes << " VMO: " << kmem.vmo_bytes << " MMU: " << kmem.mmu_overhead_bytes << " IPC: " << kmem.ipc_bytes; } if (tracing_) { TRACE_COUNTER(kTraceName, "allocated", 0, "vmo", kmem.vmo_bytes, "mmu_overhead", kmem.mmu_overhead_bytes, "ipc", kmem.ipc_bytes); TRACE_COUNTER(kTraceName, "free", 0, "free", kmem.free_bytes, "free_heap", kmem.free_heap_bytes); } NotifyWatchers(kmem); async::PostDelayedTask( dispatcher_, [this] { SampleAndPost(); }, delay_); } } void Monitor::MeasureBandwidthAndPost() { // Bandwidth measurements are cheap but they take some time to // perform as they run over a number of memory cycles. In order to // support a relatively small cycle count for measurements, we keep // multiple requests in-flight. This gives us results with high // granularity and relatively good coverage. while (tracing_ && pending_bandwidth_measurements_ < kMaxPendingBandwidthMeasurements) { uint64_t cycles_to_measure = kMemCyclesToMeasure; bool trace_high_precision = trace_is_category_enabled(kTraceNameHighPrecisionBandwidth); bool trace_high_precision_camera = trace_is_category_enabled(kTraceNameHighPrecisionBandwidthCamera); if (trace_high_precision && trace_high_precision_camera) { FX_LOGS(ERROR) << kTraceNameHighPrecisionBandwidth << " and " << kTraceNameHighPrecisionBandwidthCamera << " are mutually exclusive categories."; } if (trace_high_precision || trace_high_precision_camera) { cycles_to_measure = kMemCyclesToMeasureHighPrecision; } ++pending_bandwidth_measurements_; ram_device_->MeasureBandwidth( BuildConfig(cycles_to_measure, trace_high_precision_camera), [this, cycles_to_measure, trace_high_precision_camera]( fuchsia::hardware::ram::metrics::Device_MeasureBandwidth_Result result) { --pending_bandwidth_measurements_; if (result.is_err()) { FX_LOGS(ERROR) << "Bad bandwidth measurement result: " << result.err(); } else { const auto& info = result.response().info; uint64_t total_readwrite_cycles = TotalReadWriteCycles(info); uint64_t other_readwrite_cycles = (info.total.readwrite_cycles > total_readwrite_cycles) ? info.total.readwrite_cycles - total_readwrite_cycles : 0; static_assert(std::size(kRamDefaultChannels) == std::size(kRamCameraChannels)); const auto* channels = trace_high_precision_camera ? kRamCameraChannels : kRamDefaultChannels; TRACE_VTHREAD_COUNTER( kTraceName, "bandwidth_usage", "membw" /*vthread_literal*/, 1 /*vthread_id*/, 0 /*counter_id*/, TimestampToTicks(info.timestamp), channels[0].name, CounterToBandwidth(info.channels[0].readwrite_cycles, info.frequency, cycles_to_measure) * info.bytes_per_cycle, channels[1].name, CounterToBandwidth(info.channels[1].readwrite_cycles, info.frequency, cycles_to_measure) * info.bytes_per_cycle, channels[2].name, CounterToBandwidth(info.channels[2].readwrite_cycles, info.frequency, cycles_to_measure) * info.bytes_per_cycle, channels[3].name, CounterToBandwidth(info.channels[3].readwrite_cycles, info.frequency, cycles_to_measure) * info.bytes_per_cycle, "other", CounterToBandwidth(other_readwrite_cycles, info.frequency, cycles_to_measure) * info.bytes_per_cycle); TRACE_VTHREAD_COUNTER(kTraceName, "bandwidth_free", "membw" /*vthread_literal*/, 1 /*vthread_id*/, 0 /*counter_id*/, TimestampToTicks(info.timestamp), "value", CounterToBandwidth(cycles_to_measure - total_readwrite_cycles - other_readwrite_cycles, info.frequency, cycles_to_measure) * info.bytes_per_cycle); } async::PostTask(dispatcher_, [this] { MeasureBandwidthAndPost(); }); }); } } void Monitor::PeriodicMeasureBandwidth() { std::chrono::seconds seconds_to_sleep = std::chrono::seconds(1); async::PostDelayedTask( dispatcher_, [this]() { PeriodicMeasureBandwidth(); }, zx::sec(seconds_to_sleep.count())); // Will not do measurement when tracing if (tracing_) return; uint64_t cycles_to_measure = kMemCyclesToMeasure; ram_device_->MeasureBandwidth( BuildConfig(cycles_to_measure), [this, cycles_to_measure](fuchsia::hardware::ram::metrics::Device_MeasureBandwidth_Result result) { if (result.is_err()) { FX_LOGS(ERROR) << "Bad bandwidth measurement result: " << result.err(); } else { const auto& info = result.response().info; uint64_t total_readwrite_cycles = TotalReadWriteCycles(info); total_readwrite_cycles = std::max(total_readwrite_cycles, info.total.readwrite_cycles); uint64_t memory_bandwidth_reading = CounterToBandwidth(total_readwrite_cycles, info.frequency, cycles_to_measure) * info.bytes_per_cycle; if (metrics_) metrics_->NextMemoryBandwidthReading(memory_bandwidth_reading, info.timestamp); } }); } void Monitor::UpdateState() { if (trace_state() == TRACE_STARTED) { if (trace_is_category_enabled(kTraceName)) { FX_LOGS(INFO) << "Tracing started"; if (!tracing_) { Capture capture; auto s = Capture::GetCapture(&capture, capture_state_, KMEM); if (s != ZX_OK) { FX_LOGS(ERROR) << "Error getting capture: " << zx_status_get_string(s); return; } const auto& kmem = capture.kmem(); TRACE_COUNTER(kTraceName, "fixed", 0, "total", kmem.total_bytes, "wired", kmem.wired_bytes, "total_heap", kmem.total_heap_bytes); tracing_ = true; if (!logging_) { SampleAndPost(); } if (ram_device_.is_bound()) { MeasureBandwidthAndPost(); } } } } else { if (tracing_) { FX_LOGS(INFO) << "Tracing stopped"; tracing_ = false; } } } zx_status_t Monitor::GetCapture(memory::Capture* capture) { return Capture::GetCapture(capture, capture_state_, VMO); } void Monitor::GetDigest(const memory::Capture& capture, memory::Digest* digest) { digester_->Digest(capture, digest); } void Monitor::PressureLevelChanged(Level level) { if (level == level_) { return; } FX_LOGS(INFO) << "Memory pressure level changed from " << kLevelNames[level_] << " to " << kLevelNames[level]; level_ = level; logger_.SetPressureLevel(level_); } } // namespace monitor
41.168856
99
0.679078
re995
e166894a5a2548d5cc36aac6acc9e3e7d3dac503
2,409
cpp
C++
src/old/class/command.class.cpp
lucabertoni/Telegram-SocialNetworkBot
9f65ae5f80a24caea182acd8ab25712dbee68f79
[ "MIT" ]
null
null
null
src/old/class/command.class.cpp
lucabertoni/Telegram-SocialNetworkBot
9f65ae5f80a24caea182acd8ab25712dbee68f79
[ "MIT" ]
null
null
null
src/old/class/command.class.cpp
lucabertoni/Telegram-SocialNetworkBot
9f65ae5f80a24caea182acd8ab25712dbee68f79
[ "MIT" ]
null
null
null
#include "command.class.h" #include "facebookApi.class.h" #include "../include/common.h" using namespace std; Command::Command(){ // Imposto di defaul che l'id dell'utente che ha in uso la sessione è 0 nUserId = 0; // Creo il vettore con la lista di comandi ammessi this->aCommandList.push_back("/start"); this->aCommandList.push_back("/login"); this->aCommandList.push_back("/help"); // Associo ad un comando la sua guida this->oApiFB = new FacebookApi(); this->stRisposte.start = "Welcome in SocialNetworkBot. Use /help to see what command you can use."; this->stRisposte.login = "/login <social-network-name>\nLogin into your social network using this command followed by SocialNetwork name (ex: facebook,twitter...)"; this->stRisposte.facebookOAuthUrl = "Click on the following link to authenticate this app in Facebook "+this->oApiFB->getOAuthUrl(this->nUserId); this->stRisposte.unknownCommand = "This is an unknown command, please read the manual using /help command"; } // Cosa fa : Estrapola il messaggio associato ad una determinata chiave, per poi essere usato // nei metodi che utilizzano questa classe (es: quello per inviare i messaggi all'utente) // Ritorna : string Command::getMessage(string sKey){ if(sKey == "start") return this->stRisposte.start; else if(sKey == "login") return this->stRisposte.login; else if(sKey == "facebookOAuthUrl") return this->stRisposte.facebookOAuthUrl; else if(sKey == "unknownCommand") return this->stRisposte.unknownCommand; else return this->stRisposte.unknownCommand; } // Cosa fa : Controlla se il comando è valido (se è presente nel vettore con la lista dei comandi) // sComando : stringa, comando, es: /start oppure /login // Ritorna : bRet -> true se il comando è ammesso, altrimenti false bool Command::isAllowedCommand(string sComando){ bool bRet = false; // Cosa fa : Verifica se un elemento stringa è presente in un vettore di stringhe // aVector : vettore di stringhe, vettore nel quale cercare l'elemento // sElement : stringa, elemento da cercare nel vettore // Ritorna : bRet -> logico, true se l'elemento è presente nel vettore, altrimenti false if(isInStringVector(this->aCommandList, sComando)){ bRet = true; } return bRet; } // Cosa fa : Imposta l'id dell'utente che ha in uso la "sessione" void Command::setUserId(int nUserId){ this->nUserId = nUserId; }
45.45283
165
0.729348
lucabertoni
e1674fa339511da7bcb7819c1c8e4c31a55a65c2
10,313
cpp
C++
stutterhold/Source/PhaseVocodeur/PhaseVocodeur.cpp
maxsolomonhenry/stutterhold
2fa02da5ddb2c010a8bd0fa098d7054cb3a97a19
[ "MIT" ]
null
null
null
stutterhold/Source/PhaseVocodeur/PhaseVocodeur.cpp
maxsolomonhenry/stutterhold
2fa02da5ddb2c010a8bd0fa098d7054cb3a97a19
[ "MIT" ]
null
null
null
stutterhold/Source/PhaseVocodeur/PhaseVocodeur.cpp
maxsolomonhenry/stutterhold
2fa02da5ddb2c010a8bd0fa098d7054cb3a97a19
[ "MIT" ]
null
null
null
/* ============================================================================== PhaseVocodeur.cpp Created: 9 Dec 2020 9:19:32pm Author: Julian Vanasse By `push`ing into this class, the input is distributed among overlapping buffers, this permits a frequency-domain processing and reconstruction. Sound goes in via `push(float)` Sound comes out via `read_sum()` You can specify your own processing by overwriting the (?) method. ============================================================================== */ #include "PhaseVocodeur.h" /* ============================================================================== Constructors ============================================================================== */ PhaseVocodeur::PhaseVocodeur() { init(); } PhaseVocodeur::PhaseVocodeur(int frame_size, int hop_size) { this->frame_size = frame_size; this->hop_size = hop_size; this->ola_size = frame_size; this->n_fft = frame_size; this->num_bins = (frame_size / 2) + 1; init(); } PhaseVocodeur::PhaseVocodeur(int frame_size, int hop_size, int n_fft) { this->frame_size = frame_size; this->hop_size = hop_size; this->ola_size = n_fft; this->n_fft = n_fft; this->num_bins = (n_fft / 2) + 1; init(); } PhaseVocodeur::PhaseVocodeur(int frame_size, int hop_size, int ola_size, int n_fft) { this->frame_size = frame_size; this->hop_size = hop_size; this->ola_size = ola_size; this->n_fft = n_fft; this->num_bins = (n_fft / 2) + 1; init(); } /* ============================================================================== Methods for initialization ============================================================================== */ void PhaseVocodeur::init() { /* Call all init subroutines */ init_ola(); init_window(); init_fft(); } void PhaseVocodeur::init_ola() { /* Initialize Overlap-Add (OLA) containers and rw positions */ // assign number of frames based on overlap num_ola_frames = ceil(static_cast<float>(ola_size) / static_cast<float>(hop_size)); // allocate memory ola_in = juce::AudioBuffer<float> (num_ola_frames, ola_size); ola_out = juce::AudioBuffer<float> (num_ola_frames, ola_size); // clear ola_in.clear(); ola_out.clear(); // initialize rw positions int pos = 0; rw.clear(); for (int i = 0; i < num_ola_frames; i++) { rw.push_back(pos); pos += (hop_size % ola_size); } } void PhaseVocodeur::init_window() { /* Initialize Hann window buffer. */ // Hann window is computed using the 'periodic' method. // allocate memory and clear window = juce::AudioBuffer<float>(1, frame_size); window.clear(); // fill using Hann function auto w = window.getWritePointer(0); float N = static_cast<float>(frame_size); for (int n = 0; n < frame_size; n++) { float fn = static_cast<float>(n); w[n] = pow(sin(M_PI * fn / N), 2.0f); } } void PhaseVocodeur::init_fft() { /* Initialize spectral containers and routines */ // allocate space for input and output fft_in = new kiss_fft_cpx[n_fft]; fft_out = new kiss_fft_cpx[n_fft]; // initialize data storage // Set the memory of (`fft_in`) to 0, specifying in bytes. memset(fft_in, 0, n_fft * sizeof(kiss_fft_cpx)); memset(fft_out, 0, n_fft * sizeof(kiss_fft_cpx)); // initialize plans fft_forward = kiss_fft_alloc(n_fft, 0, 0, 0); fft_inverse = kiss_fft_alloc(n_fft, 1, 0, 0); } /* ============================================================================== Destructor. ============================================================================== */ PhaseVocodeur::~PhaseVocodeur() { /* free spectral resources */ kiss_fft_free(fft_forward); kiss_fft_free(fft_inverse); delete[] fft_in; delete[] fft_out; } /* ============================================================================== Writing and reading. ============================================================================== */ void PhaseVocodeur::push(float input_sample) { // Takes input sample and writes it into all the write buffers. auto ola_in_w = ola_in.getArrayOfWritePointers(); for (int b = 0; b < num_ola_frames; b++) { ola_in_w[b][rw[b]] = input_sample; // IF rw[b] is at the end of a frame THEN process. if (rw[b] == ola_size-1) { spectral_routine(b); } } } float PhaseVocodeur::read_sum() { /* sum to output */ float s = 0.0f; auto r = ola_out.getArrayOfReadPointers(); for (int b = 0; b < num_ola_frames; b++) { s += r[b][rw[b]]; } return s; } void PhaseVocodeur::advance() { /* advances rw positions */ for (int k = 0; k < rw.size(); k++) { rw[k] = (rw[k] + 1) % ola_size; } } /* ============================================================================== Spectral processing. ============================================================================== */ // Shell for spectral processing: transfers to and from spectral domain. void PhaseVocodeur::spectral_routine(int b) { // pointers auto ola_out_w = ola_out.getWritePointer(b); auto ola_out_r = ola_out.getReadPointer(b); // copy from ola_in ola_out.copyFrom(b, 0, ola_in, b, 0, frame_size); // apply window apply_window(ola_out_r, ola_out_w); // copy into spectral buffers clear_cpx(); copy_to_cpx(ola_out_r, fft_in, frame_size); // transform kiss_fft(fft_forward, fft_in, fft_out); /* DO SOMETHING */ spectral_processing(); /* ------------ */ /* BACK TO TIME-DOMAIN */ kiss_fft(fft_inverse, fft_out, fft_in); // copy into ola_out copy_to_bfr(ola_out_w, fft_in, n_fft); } // Processing in the frequency domain. void PhaseVocodeur::spectral_processing() { // bins: DC, 1, 2, ..., Nyquist int num_bins = (n_fft / 2) + 1; // transform to polar float magnitude[num_bins]; float phase[num_bins]; car2pol(fft_out, magnitude, phase, num_bins); /* DO SOMETHING */ /* filter example */ for (int k = 0; k < num_bins; k++) { magnitude[k] *= exp(-(float)(k+1) / 15.0f); } /* return to cartesian */ pol2car(fft_out, magnitude, phase, num_bins); // std::ofstream out; // out.open("post_fft.csv", std::ios::app); // for (int n = 0; n < n_fft; n++) // { // std::string s = "+"; // if (fft_out[n].i < 0) // s = ""; // out << fft_out[n].r << s << fft_out[n].i << "i"; // if (n == n_fft - 1) // out << "\n"; // else // out << ", "; // } } void PhaseVocodeur::apply_window(const float *r, float *w) { /* apply window to a buffer */ auto win = window.getReadPointer(0); for (int n = 0; n < frame_size; n++) { w[n] = r[n] * win[n]; } } /* ============================================================================== Spectral utility. ============================================================================== */ /* coordinate conversion */ void PhaseVocodeur::car2pol(kiss_fft_cpx *cpx_out, float *r, float *p, int len) { for (int k = 0; k < len; k++) { r[k] = mag(cpx_out[k].r, cpx_out[k].i); p[k] = ang(cpx_out[k].r, cpx_out[k].i); } } void PhaseVocodeur::pol2car(kiss_fft_cpx *cpx_out, float *r, float *p, int len) { for (int k = 0; k < len; k++) { cpx_out[k].r = cos(p[k])*r[k]*2.0f; cpx_out[k].i = sin(p[k])*r[k]*2.0f; } // negative frequencies int m = num_bins-2; for (int k = num_bins; k < n_fft; k++) { cpx_out[k].r = cpx_out[m].r; cpx_out[k].i = -cpx_out[m].i; m--; } } /* ============================================================================== Copying/Clearing Buffers. ============================================================================== */ void PhaseVocodeur::clear_cpx() { /* clear complex kiss_fft buffers */ for (int n = 0; n < n_fft; n++) { fft_in[n].r = 0.0f; fft_in[n].i = 0.0f; fft_out[n].r = 0.0f; fft_out[n].i = 0.0f; } } void PhaseVocodeur::copy_to_cpx(float *arr, kiss_fft_cpx *cpx_in, int len) { const float *r = const_cast<float *>(arr); copy_to_cpx(r, cpx_in, len); } void PhaseVocodeur::copy_to_cpx(const float *r, kiss_fft_cpx *cpx_in, int len) { /* copy into real part of fft_in */ for (int n = 0; n < len; n++) { cpx_in[n].r = r[n]; } } void PhaseVocodeur::copy_to_bfr(float *w, kiss_fft_cpx *cpx_in, int len) { /* copy real cpx_in to buffer and scale */ float fN = static_cast<float>(n_fft); for (int n = 0; n < len; n++) { w[n] = cpx_in[n].r / fN; } } /* ============================================================================== Class utility. ============================================================================== */ void PhaseVocodeur::print() { printf("Phase Vocodeur:\n"); // print parameters printf("\tframe_size:\n"); printf("\t\t%d\n", frame_size); printf("\thop_size:\n"); printf("\t\t%d\n", hop_size); printf("\tn_fft:\n"); printf("\t\t%d\n", n_fft); // print ola container dimensions printf("\tola_in:\n"); printf("\t\tsize = [%d, %d]\n", ola_in.getNumChannels(), ola_in.getNumSamples()); printf("\tola_out:\n"); printf("\t\tsize = [%d, %d]\n", ola_out.getNumChannels(), ola_out.getNumSamples()); printf("\trw:\n"); // print rw positions printf("\t\t"); print_int_vector(rw); printf("\n"); // print window dimensions printf("\twindow:\n"); printf("\t\tsize = [%d, %d]\n", window.getNumChannels(), window.getNumSamples()); }
26.648579
88
0.482983
maxsolomonhenry
e1680133af0d371938f05aa57b548f2d844bbdab
905
cpp
C++
more-memories/learning/Sizeof()/Sizeof().cpp
TareqNewazShahriar/my-cpp-works
3009daf23e8c4cbd489ee76c874127028bde8181
[ "MIT" ]
null
null
null
more-memories/learning/Sizeof()/Sizeof().cpp
TareqNewazShahriar/my-cpp-works
3009daf23e8c4cbd489ee76c874127028bde8181
[ "MIT" ]
null
null
null
more-memories/learning/Sizeof()/Sizeof().cpp
TareqNewazShahriar/my-cpp-works
3009daf23e8c4cbd489ee76c874127028bde8181
[ "MIT" ]
null
null
null
// By --------- Alauddin ----------- #include<stdio.h> #include<iostream> #include<time.h> #include<BigInt_Al.h> /*===========================MAIN=============================*/ #define Size 1000 void main() { int i; char bignum[1010]=""; BigInt N; for(i=0;i<1000;i++) bignum[i]='9'; cout<<"sizeof(BigInt_Al)= "<<sizeof(BigInt)<<"\n"; N.digits=bignum; cout<<"sizeof(BigInt N.1000digit)= "<<sizeof(N)<<"\n"; puts(N.digits.c_str()); encode(N); cout<<"sizeof(Enconded N)= "<<sizeof(N)<<"\n"; decode(N); cout<<"sizeof(Decoded N)= "<<sizeof(N)<<"\n"; puts(N.digits.c_str()); cout<<"\n"<<"sizeof(__int64) = "<<sizeof(__int64)<<"\n"; cout<<"sizeof( int ) = "<<sizeof(int)<<"\n"; cout<<"sizeof( long ) = "<<sizeof(long)<<"\n"; cout<<"sizeof( short ) = "<<sizeof(short)<<"\n"; cout<<"sizeof( char ) = "<<sizeof(char)<<"\n"; cout<<"sizeof(clock_t) = "<<sizeof(clock_t)<<"\n"; }
25.857143
64
0.528177
TareqNewazShahriar
e16c1cf96f616715f825c5b3b38800fd7c3a9356
71,965
cc
C++
lib/transforms/inst_simplify.cc
xuhongyao/heterogeneity-aware-lowering-and-optimization
295fe33f0484947432343aaa453b89fb58fa206b
[ "Apache-2.0" ]
null
null
null
lib/transforms/inst_simplify.cc
xuhongyao/heterogeneity-aware-lowering-and-optimization
295fe33f0484947432343aaa453b89fb58fa206b
[ "Apache-2.0" ]
null
null
null
lib/transforms/inst_simplify.cc
xuhongyao/heterogeneity-aware-lowering-and-optimization
295fe33f0484947432343aaa453b89fb58fa206b
[ "Apache-2.0" ]
null
null
null
//===- inst_simplify.cc ---------------------------------------------------===// // // Copyright (C) 2019-2020 Alibaba Group Holding Limited. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ============================================================================= #include "halo/lib/transforms/inst_simplify.h" #include <algorithm> #include <numeric> #include <random> #include <string> #include <unordered_set> #include "halo/api/halo_data.h" #include "halo/lib/framework/common.h" #include "halo/lib/framework/data_layout.h" #include "halo/lib/framework/global_context.h" #include "halo/lib/ir/common_cast_instructions.h" #include "halo/lib/ir/common_instructions.h" #include "halo/lib/ir/common_reduction_instructions.h" #include "halo/lib/ir/ir_builder.h" #include "halo/lib/ir/math_instructions.h" #include "halo/lib/ir/nn_cnn_instructions.h" #include "halo/lib/transforms/transforms_util.h" #include "halo/lib/transforms/type_legalizer.h" namespace halo { template <typename T> static Constant* RunConstantFoldingOnMathBinary(const std::string& name, const Type& ret_type, Def op0, Def op1, OpCode opcode, KindPredicate pred) { if (!IsA<Constant>(op0.GetOwner()) || !IsA<Constant>(op1.GetOwner()) || op0.GetType().GetTotalNumOfElements() != op1.GetType().GetTotalNumOfElements()) { return nullptr; } if (opcode == OpCode::CMP) { if (pred == KindPredicate::GE) { pred = KindPredicate::LT; std::swap(op0, op1); } else if (pred == KindPredicate::GT) { pred = KindPredicate::LE; std::swap(op0, op1); } } Constant* c_lhs = DynCast<Constant>(op0.GetOwner()); Constant* c_rhs = DynCast<Constant>(op1.GetOwner()); size_t num_elements = op0.GetType().GetTotalNumOfElements(); Constant* c_ret = nullptr; ConstantBuilder cb(DynCast<Function>(c_lhs->GetParent())); std::vector<T> ret; ret.reserve(num_elements); switch (opcode) { case OpCode::ADD: { for (size_t i = 0; i < num_elements; ++i) { ret.push_back(c_lhs->GetData<T>(i) + c_rhs->GetData<T>(i)); } c_ret = cb.CreateConstant(name, ret_type, ret.data()); break; } case OpCode::MUL: { for (size_t i = 0; i < num_elements; ++i) { ret.push_back(c_lhs->GetData<T>(i) * c_rhs->GetData<T>(i)); } c_ret = cb.CreateConstant(name, ret_type, ret.data()); break; } case OpCode::DIV: { for (size_t i = 0; i < num_elements; ++i) { ret.push_back(c_lhs->GetData<T>(i) / c_rhs->GetData<T>(i)); } c_ret = cb.CreateConstant(name, ret_type, ret.data()); break; } case OpCode::CMP: { std::vector<int8_t> ret; switch (pred) { case KindPredicate::LT: { for (size_t i = 0; i < num_elements; ++i) { if (c_lhs->GetData<T>(i) < c_rhs->GetData<T>(i)) { ret.push_back(1); } else { ret.push_back(0); } } c_ret = cb.CreateConstant(name, ret_type, ret.data()); break; } default: { break; } } break; } default: { break; } } return c_ret; } template <typename T> static T* FuseToConvDeConv(const T* conv, OpCode opc, const Constant* c) { HLCHECK(IsA<Constant>(conv->GetOperand(1))); const auto kernel = DynCast<Constant>(conv->GetOperand(1)); const auto& kernel_type = kernel->GetResultType(); const auto& info = ImageAxisInfo::GetImageAxisInfo(conv->GetDataFormat(), conv->GetFilterFormat()); auto group = conv->GetGroup(); if (group < 1 || !conv->GetResultType().IsValid()) { return nullptr; } unsigned output_dim = info.kernel_output_axis; auto output_ch = conv->GetResultType().GetNumOfElementsInDim(info.data_channel_axis); bool has_valid_bias = conv->GetNumOfOperands() == 2 || (conv->GetNumOfOperands() == 3 && IsA<Constant>(conv->GetOperand(2)) && conv->GetOperand(2).GetType().GetTotalNumOfElements() == output_ch); if (!has_valid_bias) { return nullptr; } ConstantBuilder cb(conv->GetParent()->GetParent()); IRBuilder builder(conv->GetParent()); builder.SetInsertAfter(conv); auto n = c->GetResultType().GetTotalNumOfElements(); if (!has_valid_bias || output_ch != n) { return nullptr; } auto ops = conv->GetOperands(); const Constant* op_bias = conv->GetNumOfOperands() == 3 ? DynCast<Constant>(conv->GetOperand(2)) : nullptr; if (opc == OpCode::MUL) { std::vector<float> data(kernel_type.GetTotalNumOfElements()); size_t extend = 1; for (auto i = kernel_type.GetNumOfDims() - 1; i > output_dim; --i) { extend *= kernel_type.GetNumOfElementsInDim(i); } for (size_t i = 0, e = data.size(); i < e; ++i) { auto idx = (i / extend) % n; data[i] = kernel->template GetData<float>(i) * c->GetData<float>(idx); } auto new_kernel = cb.CreateConstant(kernel->GetName(), kernel_type, data.data()); ops[1] = *new_kernel; if (op_bias != nullptr) { std::vector<float> data(output_ch); for (int i = 0; i < output_ch; ++i) { data[i] = op_bias->GetData<float>(i) * c->GetData<float>(i); } auto new_bias = cb.CreateConstant(op_bias->GetName(), op_bias->GetResultType(), data.data()); ops[2] = *new_bias; } } else { std::vector<int64_t> shape(kernel_type.GetNumOfDims(), 1); shape[info.data_channel_axis] = n; halo::Type ty{kernel_type.GetDataType(), shape}; std::vector<float> data(output_ch); for (int i = 0; i < output_ch; ++i) { data[i] = (op_bias == nullptr ? 0 : op_bias->GetData<float>(i)) + c->GetData<float>(i); } auto new_bias = cb.CreateConstant(c->GetName(), ty, data.data()); if (ops.size() == 3) { ops.pop_back(); } ops.push_back(*new_bias); } auto new_conv = builder.Clone(*conv, ops); return DynCast<T>(new_conv); } static std::pair<Def, Def> RunOnMathBinaryInstruction(Instruction* binary_inst, bool disable_broadcasting, bool fuse_conv_bias) { Def orig_def{binary_inst, 0}; auto op0 = binary_inst->GetOperand(0); auto op1 = binary_inst->GetOperand(1); bool has_swapped = false; if (IsA<Constant>(op0)) { std::swap(op0, op1); has_swapped = true; } // MUL(x, 1) ==> x. if (binary_inst->GetOpCode() == OpCode::MUL && IsA<Constant>(op1)) { const Constant* c = DynCast<Constant>(op1); if (c->HasSameValueOf(1)) { return {orig_def, op0}; } } ConstantBuilder cb(binary_inst->GetParent()->GetParent()); IRBuilder builder(binary_inst->GetParent()); builder.SetInsertAfter(binary_inst); // Fuse mul/add into conv. auto opc = binary_inst->GetOpCode(); if ((opc == OpCode::MUL || (fuse_conv_bias && opc == OpCode::ADD)) && IsA<Constant>(op1)) { const Constant* c = DynCast<Constant>(op1); // check if mul can be fused with conv auto op0_opc = IsA<Instruction>(op0) ? DynCast<Instruction>(op0)->GetOpCode() : OpCode::INVALID; Instruction* new_inst = nullptr; if (op0_opc == OpCode::CONV2D) { new_inst = FuseToConvDeConv(DynCast<Conv2DInst>(op0), opc, c); } else if (op0_opc == OpCode::CONV2DTRANSPOSE) { new_inst = FuseToConvDeConv(DynCast<Conv2DTransposeInst>(op0), opc, c); } if (new_inst != nullptr) { return {orig_def, *new_inst}; } } const auto& op0_type = op0.GetType(); const auto& op1_type = op1.GetType(); OpCode opcode = binary_inst->GetOpCode(); /* // Handle scalar constant if (IsA<Constant>(op1.GetOwner())) { Constant* c_op1 = DynCast<Constant>(op1.GetOwner()); Type ret_type = binary_inst->GetResultsTypes()[0]; HLCHECK(ret_type.IsValid()); if (c_op1->IsScalarZero()) { if (opcode == OpCode::ADD) { return {orig_def, op0}; } if (opcode == OpCode::MUL) { Constant* c_zero = cb.SplatConstantZero(binary_inst->GetName(), ret_type); return {orig_def, *c_zero}; } } if (c_op1->IsScalarOne()) { if (opcode == OpCode::MUL) { return {orig_def, op0}; } } }*/ const int64_t folding_threshold = 10; // Both operands are constant, do constant folding if (IsA<Constant>(op0) && IsA<Constant>(op1) && op0_type.GetTotalNumOfElements() == op1_type.GetTotalNumOfElements() && op0_type.GetTotalNumOfElements() < folding_threshold) { Type ret_type = binary_inst->GetResultsTypes()[0]; HLCHECK(ret_type.IsValid()); KindPredicate pred = KindPredicate::INVALID; if (opcode == OpCode::CMP) { pred = static_cast<CmpInst*>(binary_inst)->GetPredicator(); // NOLINT } if (has_swapped) { std::swap(op0, op1); } Constant* c_ret = nullptr; switch (op0_type.GetDataType()) { case DataType::INT32: { c_ret = RunConstantFoldingOnMathBinary<int>( binary_inst->GetName() + "_folding", ret_type, op0, op1, opcode, pred); break; } case DataType::INT64: { c_ret = RunConstantFoldingOnMathBinary<int64_t>( binary_inst->GetName() + "_folding", ret_type, op0, op1, opcode, pred); break; } case DataType::FLOAT32: { c_ret = RunConstantFoldingOnMathBinary<float>( binary_inst->GetName() + "_folding", ret_type, op0, op1, opcode, pred); break; } default: c_ret = nullptr; } if (c_ret != nullptr) { return {orig_def, *c_ret}; } return {orig_def, orig_def}; } // Do offline broadcasting. if (!disable_broadcasting && op0_type.IsValid() && IsA<Constant>(op1) && op0_type.GetNumOfDims() != op1_type.GetNumOfDims() && op0_type.GetTotalNumOfElements() >= op1_type.GetTotalNumOfElements() && op0_type.GetNumOfElementsInDim(op0_type.GetNumOfDims() - 1) != 1) { size_t lhs_cnt = op0_type.GetTotalNumOfElements(); size_t rhs_cnt = op1_type.GetTotalNumOfElements(); auto orig_addend = DynCast<Constant>(op1.GetOwner()); HLCHECK(lhs_cnt % rhs_cnt == 0); HLCHECK(op1_type.GetDataType() == op0_type.GetDataType()); auto copies = lhs_cnt / rhs_cnt; size_t copy_size = rhs_cnt * orig_addend->GetElementSizeInBytes(); std::vector<char> buf(copies * copy_size); for (size_t i = 0; i < copies; ++i) { memcpy(&buf[copy_size * i], orig_addend->GetRawDataPtr(), copy_size); } auto addend = cb.CreateConstant(orig_addend->GetName() + "_broadcasted_" + std::to_string(binary_inst->GetId()), op0_type, buf.data()); auto new_add = has_swapped ? builder.CreateBinary(binary_inst->GetName(), *addend, op0, opcode) : builder.CreateBinary(binary_inst->GetName(), op0, *addend, opcode); new_add->GetResultsTypes()[0] = binary_inst->GetResultsTypes()[0]; return {orig_def, *new_add}; } if (op0_type.IsValid() && IsA<Constant>(op1) && IsA<Instruction>(op0) && op1_type.BroadcastableTo(op0_type)) { Instruction* op0_inst = DynCast<Instruction>(op0.GetDef()); if (op0_inst->GetOpCode() == OpCode::TRANSPOSE && !IsA<Argument>(op0_inst->GetOperand(0))) { // Add(transpose(op0), op1) ==> transpose(add(op0, transpose'(op1)) TransposeInst* orig_transpose = DynCast<TransposeInst>(op0_inst); IRBuilder builder(binary_inst->GetParent()); builder.SetInsertAfter(binary_inst); const auto& orig_perm = orig_transpose->GetPermutation(); Instruction* new_op1 = nullptr; if (op1_type.GetSqueezedNumOfDims() == 1) { auto dims = std::vector<int64_t>(op0_type.GetNumOfDims(), 1); int64_t op1_vector_axis = op0_type.GetNumOfDims() - 1; for (auto n = op1_type.GetTotalNumOfElements(); op1_vector_axis >= 0; --op1_vector_axis) { if (op0_type.GetNumOfElementsInDim(op1_vector_axis) == n) { break; } } dims[orig_perm[op1_vector_axis]] = op1_type.GetTotalNumOfElements(); ConstantBuilder cb(binary_inst->GetParent()->GetParent()); Constant* c_shape = cb.CreateConstant( op1.GetDef()->GetName() + "_shape", halo::Type{DataType::INT64, {static_cast<int64_t>(dims.size())}}, dims.data()); auto new_addend = builder.CreateReshape(op1.GetDef()->GetName() + "_r", {op1, *c_shape}); new_op1 = new_addend; new_addend->GetResultsTypes()[0] = Type{op1.GetType().GetDataType(), dims}; } else { auto reverse_perm = orig_perm; for (int i = 0, e = orig_perm.size(); i < e; ++i) { reverse_perm[orig_perm[i]] = i; } auto new_addend = builder.CreateTranspose(op1.GetDef()->GetName() + "_t", {op1}); new_addend->SetPermutation(reverse_perm); new_op1 = new_addend; } auto new_binary = builder.CreateBinary(binary_inst->GetName(), op0.GetDef()->GetOperand(0), *new_op1, opcode); TransposeInst* new_transpose = builder.CreateTranspose("t_" + binary_inst->GetName(), {*new_binary}); new_transpose->SetPermutation(orig_perm); return {orig_def, *new_transpose}; } } // add(transpose(v0), transpose(v1)) => transpose(v0, v1) if (IsA<Instruction>(op0) && IsA<Instruction>(op1)) { const Instruction* op0_inst = DynCast<Instruction>(op0); const Instruction* op1_inst = DynCast<Instruction>(op1); if (op0_inst->GetOpCode() == OpCode::TRANSPOSE && op1_inst->GetOpCode() == OpCode::TRANSPOSE) { const TransposeInst* tr0 = DynCast<const TransposeInst>(op0_inst); const TransposeInst* tr1 = DynCast<const TransposeInst>(op1_inst); if (tr0->GetPermutation() == tr1->GetPermutation()) { IRBuilder builder(binary_inst->GetParent()); builder.SetInsertAfter(binary_inst); auto new_binary = builder.CreateAdd( binary_inst->GetName(), tr0->GetOperand(0), tr1->GetOperand(0)); TransposeInst* new_tr = builder.CreateTranspose( binary_inst->GetName() + "_t", {*new_binary}); new_tr->SetPermutation(tr0->GetPermutation()); return {orig_def, *new_tr}; } } } return {orig_def, orig_def}; } template <typename ReduceInstTy, typename Build> static std::pair<Def, Def> EliminateTranspose(ReduceInstTy* inst, Build build) { Def orig_def{inst, 0}; std::pair<Def, Def> ret{orig_def, orig_def}; // ReduceMean(tranpose(x, {t0, t1, t2, t3}, {a0, a1, a2...}) => ReduceMean(x, // permed_axis) Def op0 = inst->GetOperand(0); if (IsA<Instruction>(op0.GetOwner()) && DynCast<Instruction>(op0.GetOwner())->GetOpCode() == OpCode::TRANSPOSE) { IRBuilder builder(inst->GetParent()); builder.SetInsertAfter(inst); const TransposeInst* transpose = DynCast<TransposeInst>(op0.GetOwner()); const auto& perm = transpose->GetPermutation(); const auto& orig_axes = inst->GetAxis(); std::vector<int> new_axes(orig_axes.size()); std::transform(orig_axes.begin(), orig_axes.end(), new_axes.begin(), [&perm](int x) { return perm[x]; }); ReduceInstTy* new_inst = build(builder, inst->GetName(), transpose->GetOperand(0)); new_inst->SetAxis(new_axes); ret.second = *new_inst; return ret; } return ret; } static std::pair<Def, Def> RunOnCommonReductionInstruction(Instruction* inst) { Def orig_def{inst, 0}; auto op0 = inst->GetOperand(0); const Type& dst_type = inst->GetResultsTypes()[0]; const Type& op0_type = op0.GetType(); OpCode opcode = inst->GetOpCode(); // Move the constant axis into attribute. if (inst->GetNumOfOperands() > 1 && IsA<Constant>(inst->GetOperand(1))) { const Constant* data = DynCast<Constant>(inst->GetOperand(1).GetOwner()); const Type& ty = data->GetResultType(); if (ty.GetDataType() == DataType::INT32) { const int32_t* ptr = data->GetDataPtr<int32_t>(); std::vector<int> axis(ptr, ptr + ty.GetTotalNumOfElements()); // NOLINT IRBuilder builder(inst->GetParent()); builder.SetInsertAfter(inst); Instruction* ret = nullptr; switch (opcode) { case OpCode::REDUCEMEAN: { ReduceMeanInst* new_inst = DynCast<ReduceMeanInst>( builder.Clone(*inst, {inst->GetOperand(0)})); new_inst->SetAxis(axis); ret = new_inst; break; } case OpCode::ARGMAX: { ArgmaxInst* new_inst = DynCast<ArgmaxInst>(builder.Clone(*inst, {inst->GetOperand(0)})); new_inst->SetAxis(axis.at(0)); ret = new_inst; break; } default: { break; } } if (ret != nullptr) { ret->GetResultsTypes()[0] = inst->GetResultType(); return {orig_def, *ret}; } } } if (inst->GetNumOfOperands() == 1) { std::pair<Def, Def> ret{orig_def, orig_def}; switch (opcode) { case OpCode::REDUCEMIN: { ret = EliminateTranspose( DynCast<ReduceMinInst>(inst), [](IRBuilder& builder, const std::string& name, const Def& def) { return builder.CreateReduceMin(name, {def}); }); break; } case OpCode::REDUCEMAX: { ret = EliminateTranspose( DynCast<ReduceMaxInst>(inst), [](IRBuilder& builder, const std::string& name, const Def& def) { return builder.CreateReduceMax(name, {def}); }); break; } case OpCode::REDUCEMEAN: { ret = EliminateTranspose( DynCast<ReduceMeanInst>(inst), [](IRBuilder& builder, const std::string& name, const Def& def) { return builder.CreateReduceMean(name, {def}); }); break; } case OpCode::REDUCEPRODUCT: { ret = EliminateTranspose( DynCast<ReduceProductInst>(inst), [](IRBuilder& builder, const std::string& name, const Def& def) { return builder.CreateReduceProduct(name, {def}); }); break; } default: { break; } } if (ret.first != ret.second) { return ret; } } if (!dst_type.IsValid() || !IsA<Constant>(op0.GetOwner()) || op0_type.GetNumOfDims() > 1) { return {orig_def, orig_def}; } ConstantBuilder cb(inst->GetParent()->GetParent()); Constant* c_input = DynCast<Constant>(op0.GetOwner()); DataType dt = op0_type.GetDataType(); if (op0_type.GetTotalNumOfElements() == 1) { Constant* c_ret = nullptr; if (opcode == OpCode::ARGMAX || opcode == OpCode::ARGMIN) { int ret = 0; c_ret = cb.CreateConstant(inst->GetName() + "_folding", dst_type, &ret); } else { c_ret = cb.CreateConstant(inst->GetName() + "_folding", dst_type, c_input->GetRawDataPtr()); } return {orig_def, *c_ret}; } if (dt == DataType::INT32) { switch (opcode) { case OpCode::REDUCEMIN: case OpCode::REDUCEMAX: case OpCode::ARGMAX: { int ret = std::numeric_limits<int32_t>::lowest(); int index = -1; for (int i = 0; i < op0_type.GetTotalNumOfElements(); ++i) { int data_i = c_input->GetData<int>(i); ret = std::max(ret, data_i); if (ret == data_i) { index = i; } } if (opcode == OpCode::REDUCEMAX || opcode == OpCode::REDUCEMIN) { auto new_def = cb.CreateConstant(inst->GetName() + "_folding", dst_type, &ret); return {orig_def, *new_def}; } // ARGMAX auto new_def = cb.CreateConstant(inst->GetName() + "_folding", dst_type, &index); return {orig_def, *new_def}; } case OpCode::REDUCEMEAN: case OpCode::REDUCESUM: { int ret = 0; for (int i = 0; i < op0_type.GetTotalNumOfElements(); ++i) { ret += c_input->GetData<int>(i); } if (opcode == OpCode::REDUCEMEAN) { ret /= op0_type.GetTotalNumOfElements(); } auto new_def = cb.CreateConstant(inst->GetName() + "_folding", dst_type, &ret); return {orig_def, *new_def}; } case OpCode::REDUCEPRODUCT: { int ret = 1; for (int i = 0; i < op0_type.GetTotalNumOfElements(); ++i) { ret *= c_input->GetData<int>(i); } auto new_def = cb.CreateConstant(inst->GetName() + "_folding", dst_type, &ret); return {orig_def, *new_def}; } default: { return {orig_def, orig_def}; } } } return {orig_def, orig_def}; } /// By default, nothing is updated. std::pair<Def, Def> InstSimplify::RunOnInstruction(Instruction* inst) { switch (inst->GetOpCode()) { case OpCode::ADD: case OpCode::MUL: case OpCode::DIV: case OpCode::SUB: case OpCode::CMP: { return RunOnMathBinaryInstruction(inst, disable_broadcasting_, fuse_conv_bias_); } case OpCode::REDUCEMAX: case OpCode::REDUCEMIN: case OpCode::REDUCEMEAN: case OpCode::REDUCESUM: case OpCode::REDUCEPRODUCT: case OpCode::ARGMAX: case OpCode::ARGMIN: { return RunOnCommonReductionInstruction(inst); } default: { return std::make_pair(Def{inst, 0}, Def{inst, 0}); } } } template <typename InstType, typename Builder> static std::pair<Def, Def> SinkTranspose(InstType& inst, Builder build) { std::pair<Def, Def> ret{Def{&inst, 0}, Def{&inst, 0}}; if (IsA<Instruction>(inst.GetOperand(0))) { // Inst(transpose(x)) -> transpose(Inst(x)), this exposes opportunites // to cancel out transposes. Instruction* op0_inst = DynCast<Instruction>(inst.GetOperand(0)); if (op0_inst->GetOpCode() == OpCode::TRANSPOSE) { const TransposeInst* orig_trans = DynCast<TransposeInst>(op0_inst); IRBuilder builder(inst.GetParent()); builder.SetInsertAfter(&inst); InstType* new_inst = build(builder, inst.GetName(), op0_inst->GetOperand(0)); TransposeInst* new_trans = builder.CreateTranspose(inst.GetName() + "_t", {*new_inst}); new_trans->SetPermutation(orig_trans->GetPermutation()); ret.second = *new_trans; return ret; } } return ret; } std::pair<Def, Def> InstSimplify::RunOnInstruction(LeakyReluInst* inst) { return SinkTranspose(*inst, [inst](IRBuilder& builder, const std::string& name, const Def& op) { auto new_inst = builder.CreateLeakyRelu(name, op); new_inst->SetAlpha(inst->GetAlpha()); return new_inst; }); } std::pair<Def, Def> InstSimplify::RunOnInstruction(PReluInst* inst) { auto op1 = inst->GetOperand(1); return SinkTranspose( *inst, [inst, &op1](IRBuilder& builder, const std::string& name, const Def& op) { return DynCast<PReluInst>(builder.Clone(*inst, {op, op1})); }); } template <typename T> static Constant* GetPermutedConstant(ConstantBuilder* cb, const Constant* orig, const std::vector<int32_t>& perm) { const auto& shape_type = orig->GetResultType(); auto ranks = shape_type.GetTotalNumOfElements(); std::vector<T> data(ranks); for (int64_t i = 0; i < ranks; ++i) { data[perm[i]] = orig->GetData<T>(i); } return cb->CreateConstant(orig->GetName(), shape_type, data.data()); } std::pair<Def, Def> InstSimplify::RunOnInstruction(ResizeInst* inst) { Def orig_def{inst, 0}; auto op_shape = inst->GetOperand(1); if (IsA<Instruction>(inst->GetOperand(0))) { Instruction* op0_inst = DynCast<Instruction>(inst->GetOperand(0).GetOwner()); if (auto op1 = inst->GetOperand(1); op0_inst->GetOpCode() == OpCode::TRANSPOSE && IsA<Constant>(op1)) { Constant* shape = DynCast<Constant>(op1); const auto& shape_type = shape->GetResultType(); ConstantBuilder cb(inst->GetParent()->GetParent()); auto orig_perm = DynCast<TransposeInst>(op0_inst)->GetPermutation(); Constant* new_shape = nullptr; switch (shape_type.GetDataType()) { case DataType::INT32: { new_shape = GetPermutedConstant<int32_t>(&cb, shape, orig_perm); break; } case DataType::INT64: { new_shape = GetPermutedConstant<int64_t>(&cb, shape, orig_perm); break; } case DataType::FLOAT32: { new_shape = GetPermutedConstant<float>(&cb, shape, orig_perm); break; } default: HLCHECK(0 && "Invalid resize shape type"); } new_shape->SetName(inst->GetName() + "_resize_shape"); return SinkTranspose( *inst, [new_shape, inst](IRBuilder& builder, const std::string& name, const Def& op) { auto new_inst = builder.CreateResize(name, {op, *new_shape}); new_inst->CopyAttrsFrom(*inst); return new_inst; }); } } return {orig_def, orig_def}; } std::pair<Def, Def> InstSimplify::RunOnInstruction(Relu6Inst* inst) { return SinkTranspose( *inst, [](IRBuilder& builder, const std::string& name, const Def& op) { return builder.CreateRelu6(name, op); }); } std::pair<Def, Def> InstSimplify::RunOnInstruction(SigmoidInst* inst) { return SinkTranspose( *inst, [](IRBuilder& builder, const std::string& name, const Def& op) { return builder.CreateSigmoid(name, op); }); } std::pair<Def, Def> InstSimplify::RunOnInstruction(ReluInst* inst) { return SinkTranspose( *inst, [](IRBuilder& builder, const std::string& name, const Def& op) { return builder.CreateRelu(name, op); }); } std::pair<Def, Def> InstSimplify::RunOnInstruction(Conv2DInst* inst) { std::pair<Def, Def> ret{Def{inst, 0}, Def{inst, 0}}; if (!inst->GetResultType().IsValid()) { return ret; } Def op_input = inst->GetOperand(0); Def op_kernel = inst->GetOperand(1); IRBuilder builder(inst->GetParent()); builder.SetInsertAfter(inst); // Convert conv(pad(x, amt), kernel) to conv(x, kernel) to eliminate // pad op. if (IsA<Instruction>(op_input) && DynCast<Instruction>(op_input)->GetOpCode() == OpCode::PAD) { const PadInst* pad = DynCast<PadInst>(op_input); Def pad_op0 = pad->GetOperand(0); Def pad_op1 = pad->GetOperand(1); if (IsA<Constant>(pad_op1.GetOwner())) { const Constant* pad_amt = DynCast<Constant>(pad_op1); unsigned dims = pad_amt->GetResultType().GetNumOfDims(); if (dims == 2 && pad_amt->GetResultType().GetTotalNumOfElements() == 4 * dims) { std::vector<int32_t> vals( pad_amt->GetDataPtr<int32_t>(), pad_amt->GetDataPtr<int32_t>() + 4 * dims); // NOLINT if (vals[0] != 0 || vals[1] != 0) { return ret; } const auto& info = ImageAxisInfo::GetImageAxisInfo( inst->GetDataFormat(), inst->GetFilterFormat()); std::array<int, 4> indices_nc = {0, 1, info.data_channel_axis * 2, info.data_channel_axis * 2 + 1}; // No paddings on N & C. for (auto idx : indices_nc) { if (vals[idx] != 0) { return ret; } } std::array<int, 4> indices_hw = { info.data_height_axis * 2, info.data_height_axis * 2 + 1, info.data_width_axis * 2, info.data_width_axis + 1}; Conv2DInst* new_inst = builder.CreateConv2D(inst->GetName(), {pad_op0, op_kernel}); new_inst->SetDataFormat(inst->GetDataFormat()); new_inst->SetFilterFormat(inst->GetFilterFormat()); new_inst->SetDilations(inst->GetDilations()); new_inst->SetStrides(inst->GetStrides()); new_inst->SetPaddingTop(inst->GetPaddingTop() + vals[indices_hw[0]]); new_inst->SetPaddingBottom(inst->GetPaddingBottom() + vals[indices_hw[1]]); new_inst->SetPaddingLeft(inst->GetPaddingLeft() + vals[indices_hw[2]]); new_inst->SetPaddingRight(inst->GetPaddingRight() + vals[indices_hw[3]]); new_inst->GetResultsTypes()[0] = inst->GetResultsTypes()[0]; new_inst->SetPadding(Padding::EXPLICIT); ret.second = Def(new_inst, 0); } } } // Convert Conv(add(x, c), k) => Conv(x, k') or Conv(mul(x, c), k) ==> // Conv(x, k') where k is a constant of scalar or channel-wise vector. if (IsA<Instruction>(op_input) && IsA<Constant>(op_kernel) && inst->GetGroup() == 1 && inst->GetResultType().IsValid() && (DynCast<Instruction>(op_input)->GetOpCode() == OpCode::ADD || DynCast<Instruction>(op_input)->GetOpCode() == OpCode::MUL)) { Instruction* binary_inst = DynCast<Instruction>(op_input); auto binary_op0 = binary_inst->GetOperand(0); if (IsA<Instruction>(binary_op0) && DynCast<Instruction>(binary_op0)->GetOpCode() == OpCode::CONV2D) { // For pattens like a = conv(); b = a + c; d = conv(b), prefer to fuse a // and b. return ret; } auto binary_op1 = binary_inst->GetOperand(1); if (!IsA<Constant>(binary_op1)) { return ret; } const auto& kernel_type = op_kernel.GetType(); Constant* c = DynCast<Constant>(binary_op1); if (kernel_type.GetDataType() != DataType::FLOAT32 || kernel_type.GetDataType() != c->GetResultType().GetDataType()) { return ret; } // match shape of C: expect [..,in_chs, 1, 1]. auto n_elems = c->GetResultType().GetTotalNumOfElements(); auto dims = c->GetResultType().GetDimSizes(); auto kernel_shape = kernel_type.GetDimSizes(); const auto& info = ImageAxisInfo::GetImageAxisInfo(inst->GetDataFormat(), inst->GetFilterFormat()); auto in_chs = kernel_shape[info.kernel_input_axis]; auto in_chs_dim_r = info.kernel_input_axis - kernel_shape.size(); // Dims in backwards. if (!(n_elems == in_chs && (dims.size() == 1 || (-in_chs_dim_r <= dims.size() && dims[dims.size() + in_chs_dim_r] == in_chs)))) { return ret; } bool has_padding = inst->GetPaddingBottom() != 0 || inst->GetPaddingLeft() != 0 || inst->GetPaddingTop() != 0 || inst->GetPaddingRight() != 0; Constant* kernel = DynCast<Constant>(op_kernel); ConstantBuilder cb(inst->GetParent()->GetParent()); std::vector<float> new_kernel_data(kernel_type.GetTotalNumOfElements()); auto operands = inst->GetOperands(); operands[0] = binary_op0; std::vector<size_t> strides(kernel_shape.size(), 1); for (int64_t i = kernel_shape.size() - 2; i >= 0; --i) { strides[i] = strides[i + 1] * kernel_shape[i + 1]; } if (binary_inst->GetOpCode() == OpCode::MUL) { for (size_t i = 0, e = kernel_type.GetTotalNumOfElements(); i < e; ++i) { size_t ch = (i / strides[info.kernel_input_axis]) % in_chs; new_kernel_data[i] = kernel->GetDataAsFloat32(i) * c->GetDataAsFloat32(ch); } auto new_kernel = cb.CreateConstant(kernel->GetName(), kernel_type, new_kernel_data); operands[1] = *new_kernel; ret.second = *builder.Clone(*inst, operands); } else if (!has_padding && (inst->GetNumOfOperands() == 2 || (inst->GetNumOfOperands() == 3 && IsA<Constant>(inst->GetOperand(2))))) { auto out_chs = kernel_shape[info.kernel_output_axis]; // Conv(x + c), k) ==> Conv(x, k) + c * k) // C is vector (len = in_chs), reshape k to (H * W, out_chs, in_chs) std::vector<float> new_bias(out_chs); std::string bias_name = inst->GetName() + "_bias"; if (inst->GetNumOfOperands() == 3) { auto orig_bias = DynCast<Constant>(inst->GetOperand(2)); bias_name = orig_bias->GetName() + "_fused"; HLCHECK(orig_bias->GetResultType().GetTotalNumOfElements() == out_chs); for (int i = 0; i < out_chs; ++i) { new_bias[i] = orig_bias->GetDataAsFloat32(i); } } auto hw = kernel_type.GetTotalNumOfElements() / in_chs / out_chs; auto stride_s = strides[info.kernel_width_axis]; auto stride_o = strides[info.kernel_output_axis]; auto stride_i = strides[info.kernel_input_axis]; for (int s = 0; s < hw; ++s) { for (int och = 0; och < out_chs; ++och) { std::vector<float> m(in_chs); float t = 0; for (int i = 0; i < in_chs; ++i) { t += kernel->GetDataAsFloat32(s * stride_s + och * stride_o + i * stride_i) * c->GetDataAsFloat32(i); } new_bias[och] += t; } } halo::Type type{kernel_type.GetDataType(), {out_chs}}; auto new_bias_op = cb.CreateConstant(bias_name, type, new_bias); if (operands.size() >= 3) { operands[2] = *new_bias_op; } else { operands.push_back(*new_bias_op); } ret.second = *builder.Clone(*inst, operands); } } return ret; } static void Pad(char* dst, const char* src, size_t elems_num, size_t elem_size, const std::vector<int64_t>& orig_shape, const std::vector<int64_t>& new_shape, const std::vector<int32_t>& padding_amt) { std::vector<size_t> pos(orig_shape.size()); std::vector<size_t> dst_strides(orig_shape.size(), 1); int dims = orig_shape.size(); for (int i = dims - 2; i >= 0; --i) { dst_strides[i] = dst_strides[i + 1] * new_shape[i + 1]; } for (size_t i = 0; i < elems_num; ++i) { auto dst_pos = pos; for (int j = 0; j < dims; ++j) { dst_pos[j] += padding_amt[j]; } size_t dst_offset = std::inner_product(dst_pos.begin(), dst_pos.end(), dst_strides.begin(), 0UL) * elem_size; std::copy(src, src + elem_size, dst + dst_offset); // NOLINT. src += elem_size; // NOLINT. int c = 1; for (int j = dims - 1; j >= 0 && c == 1; --j) { pos[j] += c; if (pos[j] >= static_cast<size_t>(orig_shape[j])) { pos[j] = 0; } else { c = 0; } } } } std::pair<Def, Def> InstSimplify::RunOnInstruction(PadInst* pad_inst) { Def orig_def{pad_inst, 0}; Def op0 = pad_inst->GetOperand(0); Def op1 = pad_inst->GetOperand(1); if (!IsA<Constant>(op0.GetOwner()) || !IsA<Constant>(op1.GetOwner()) || pad_inst->GetNumOfOperands() != 2 || pad_inst->GetMode() != PadMode::CONSTANT) { return {orig_def, orig_def}; } const Constant* data = DynCast<Constant>(op0.GetOwner()); const Constant* pad_amt = DynCast<Constant>(op1.GetOwner()); ConstantBuilder cb(pad_inst->GetParent()->GetParent()); auto dims = op0.GetType().GetNumOfDims(); std::vector<int64_t> shape(dims); std::vector<int32_t> paddings_before(dims); for (size_t i = 0; i < dims; ++i) { int32_t before = pad_amt->GetDataPtr<int32_t>()[i * 2]; // NOLINT int32_t after = pad_amt->GetDataPtr<int32_t>()[i * 2 + 1]; // NOLINT shape[i] = op0.GetType().GetNumOfElementsInDim(i) + before + after; paddings_before[i] = before; } halo::Type type{op0.GetType().GetDataType(), shape}; std::vector<char> w(type.GetTotalNumOfElements() * data->GetElementSizeInBytes()); std::vector<size_t> dim_sizes(dims); Pad(w.data(), static_cast<const char*>(data->GetRawDataPtr()), op0.GetType().GetTotalNumOfElements(), data->GetElementSizeInBytes(), op0.GetType().GetDimSizes(), shape, paddings_before); auto new_inst = cb.CreateConstant("folded_pad", type, w.data()); return {orig_def, Def{new_inst, 0}}; } std::pair<Def, Def> InstSimplify::RunOnInstruction(ReshapeInst* reshape_inst) { Def orig_def{reshape_inst, 0}; // for reshape(reshape(x, c0), c1), replace it with reshape(x, c1). auto op0 = reshape_inst->GetOperand(0).GetDef(); if (IsA<Instruction>(op0)) { const Instruction* op0_inst = Downcast<const Instruction>(op0); if (op0_inst->GetOpCode() == OpCode::RESHAPE) { IRBuilder builder(reshape_inst->GetParent()); builder.SetInsertAfter(reshape_inst); auto new_inst = builder.CreateReshape(reshape_inst->GetName(), op0_inst->GetOperand(0), reshape_inst->GetOperand(1)); new_inst->GetResultsTypes()[0] = reshape_inst->GetResultsTypes()[0]; return {orig_def, Def{new_inst, 0}}; } } const auto& input_type = op0->GetResultType(); const auto& ret_type = reshape_inst->GetResultType(); if (input_type.IsValid() && ret_type.IsValid() && input_type == ret_type) { return {orig_def, *op0}; } if (IsA<Constant>(op0) && reshape_inst->GetResultType().IsValid()) { Constant* src = DynCast<Constant>(op0); Constant* new_c = nullptr; if (op0->GetNumberOfUses() == 1) { new_c = src; } else { ConstantBuilder cb(reshape_inst->GetParent()->GetParent()); new_c = cb.Clone(*src); } new_c->GetResultsTypes()[0] = reshape_inst->GetResultType(); return {orig_def, *new_c}; } return {orig_def, orig_def}; } std::pair<Def, Def> InstSimplify::RunOnInstruction(ExpandDimsInst* inst) { HLCHECK(inst->GetNumOfOperands() == 2); auto input = inst->GetOperand(0); const auto& input_type = input.GetType(); Def orig_def{inst, 0}; if (!input_type.IsValid() || !IsA<Constant>(inst->GetOperand(1))) { return {orig_def, orig_def}; } const Constant* shape = DynCast<Constant>(inst->GetOperand(1)); auto input_elem = input_type.GetTotalNumOfElements(); HLCHECK(shape->GetResultType().GetNumOfDims() == 1); std::vector<int64_t> output_shape; std::vector<int64_t> output_extends; IRBuilder builder(inst->GetParent()); builder.SetInsertAfter(inst); int shape_rank = shape->GetResultType().GetTotalNumOfElements(); int input_rank = input_type.GetNumOfDims(); auto src_extends = GetExtends(input_type.GetDimSizes()); for (int i = 0, e = std::max(shape_rank, input_rank); i < e; ++i) { int input_idx = input_rank - 1 - i; int shape_idx = shape_rank - 1 - i; int64_t dim0 = (input_idx < 0) ? 1 : input_type.GetNumOfElementsInDim(input_idx); int64_t dim1 = (shape_idx < 0) ? 1 : shape->GetDataAsInt64(shape_idx); HLCHECK(dim0 == dim1 || dim0 == 1 || dim1 == 1); output_shape.push_back((dim0 == 1) ? dim1 : dim0); bool is_bs = dim0 == 1; output_extends.push_back(is_bs ? 0 : src_extends[input_idx]); } std::reverse(output_shape.begin(), output_shape.end()); std::reverse(output_extends.begin(), output_extends.end()); halo::Type ret_type{input_type.GetDataType(), output_shape}; auto ret_elem = ret_type.GetTotalNumOfElements(); ConstantBuilder cb(inst->GetParent()->GetParent()); if (input_elem == ret_elem) { Constant* c = cb.CreateConstant( inst->GetName() + "_expand", halo::Type{DataType::INT64, {static_cast<int64_t>(output_shape.size())}}, output_shape.data()); auto reshape = builder.CreateReshape(inst->GetName(), {inst->GetOperand(0), *c}); return {orig_def, *reshape}; } if (IsA<Constant>(inst->GetOperand(0))) { const Constant* src = DynCast<Constant>(input); DefaultDataLayout data_layout; size_t elem_size = data_layout.Bytes(input_type.GetDataType()); std::vector<unsigned char> buf(ret_elem * elem_size); const auto& dst_extends = GetExtends(output_shape); for (int64_t dst_idx = 0; dst_idx < ret_elem; ++dst_idx) { std::vector<int64_t> dst_dims(output_shape.size()); for (int64_t i = 0, e = dst_dims.size(), t = dst_idx; t >= 0 && i < e; ++i) { dst_dims[i] = t / dst_extends[i]; t -= dst_dims[i] * dst_extends[i]; } auto src_idx = std::inner_product( output_extends.begin(), output_extends.end(), dst_dims.begin(), 0L); const unsigned char* src_ptr = static_cast<const unsigned char*>(src->GetRawDataPtr()) + // NOLINT. src_idx * elem_size; std::copy_n(src_ptr, elem_size, buf.begin() + dst_idx * elem_size); } Constant* c = cb.CreateConstant(inst->GetName() + "_expand", ret_type, buf.data()); return {orig_def, *c}; } return {orig_def, orig_def}; } std::pair<Def, Def> InstSimplify::RunOnInstruction(BatchNormInst* inst) { Def orig_def{inst, 0}; int num_inputs = inst->GetNumOfOperands(); const auto& input_type = inst->GetResultType(); auto input = inst->GetOperand(0); // Not profitable if the mul cannot be fused. auto input_op = IsA<Instruction>(input) ? DynCast<Instruction>(input)->GetOpCode() : OpCode::INVALID; bool is_profitable = input_op == OpCode::CONV2D || input_op == OpCode::CONV2DTRANSPOSE; if (disable_conv_bn_ || !is_profitable || num_inputs <= 4 || !input_type.IsValid() || input_type.GetNumOfDims() != 4 || !IsA<Constant>(inst->GetOperand(3)) || !IsA<Constant>(inst->GetOperand(4))) { return {orig_def, orig_def}; } auto scale = DynCast<Constant>(inst->GetOperand(1)); auto offset = DynCast<Constant>(inst->GetOperand(2)); auto mean = DynCast<Constant>(inst->GetOperand(3)); auto variance = DynCast<Constant>(inst->GetOperand(4)); int ch_dim = inst->GetDataFormat() == DataFormat::NCHW ? 1 : 3; auto ch_num = input_type.GetNumOfElementsInDim(ch_dim); const auto& mean_type = mean->GetResultType(); if (mean_type.GetTotalNumOfElements() != ch_num || variance->GetResultType().GetTotalNumOfElements() != ch_num || mean_type.GetDataType() != DataType::FLOAT32) { return {orig_def, orig_def}; } std::vector<float> mul_buf(ch_num); std::vector<float> add_buf(ch_num); float eps = inst->GetEpsilon(); // Convert BN to Ax + B. for (int64_t i = 0; i < ch_num; ++i) { mul_buf[i] = 1.0F / std::sqrt(variance->GetData<float>(i) + eps); float s = scale->GetData<float>(i); mul_buf[i] *= s; float b = offset->GetData<float>(i); add_buf[i] = -mean->GetData<float>(i) * mul_buf[i] + b; } std::vector<int64_t> shape(input_type.GetNumOfDims(), 1); shape[ch_dim] = ch_num; halo::Type ty{mean_type.GetDataType(), shape}; ConstantBuilder cb(inst->GetParent()->GetParent()); auto new_scale = cb.CreateConstant(inst->GetName() + "_0", ty, mul_buf.data()); auto new_offset = cb.CreateConstant(inst->GetName() + "_1", ty, add_buf.data()); IRBuilder builder(inst->GetParent()); builder.SetInsertAfter(inst); auto new_mul = builder.CreateMul(inst->GetName() + "_mul", input, *new_scale); auto new_add = builder.CreateAdd(inst->GetName() + "_add", *new_mul, *new_offset); return {orig_def, *new_add}; } std::pair<Def, Def> InstSimplify::RunOnInstruction(StackInst* inst) { Def orig_def{inst, 0}; int num_inputs = inst->GetNumOfOperands(); if (inst->GetAxis() != 0) { return {orig_def, orig_def}; } for (int i = 0; i < num_inputs; ++i) { if (!IsA<Constant>(inst->GetOperand(i))) { return {orig_def, orig_def}; } } // convert to an array of constant const auto& input0_type = inst->GetOperand(0).GetType(); std::vector<int64_t> ret_shape(input0_type.GetDimSizes()); ret_shape.insert(ret_shape.begin(), num_inputs); ConstantBuilder cb(inst->GetParent()->GetParent()); auto count = input0_type.GetTotalNumOfElements(); Constant* c_input0 = DynCast<Constant>(inst->GetOperand(0).GetOwner()); size_t copy_size = count * c_input0->GetElementSizeInBytes(); std::vector<char> buf(num_inputs * copy_size); for (int i = 0; i < num_inputs; ++i) { Constant* c_input_i = DynCast<Constant>(inst->GetOperand(i).GetOwner()); memcpy(&buf[copy_size * i], c_input_i->GetRawDataPtr(), copy_size); } halo::Type result_type{input0_type.GetDataType(), ret_shape}; auto new_def = cb.CreateConstant(inst->GetName() + "_folding", result_type, buf.data()); return {orig_def, *new_def}; } std::pair<Def, Def> InstSimplify::RunOnInstruction(ZExtInst* inst) { Def orig_def{inst, 0}; DataType ret_dt = inst->GetDataType(); auto op0 = inst->GetOperand(0); const auto& op0_type = op0.GetType(); DataType src_dt = op0_type.GetDataType(); HLCHECK(halo::Type::IsIntegerType(src_dt) && halo::Type::IsIntegerType(ret_dt)); if (!op0_type.IsValid() || !IsA<Constant>(op0)) { return {orig_def, orig_def}; } ConstantBuilder cb(inst->GetParent()->GetParent()); Constant* c_src = DynCast<Constant>(op0.GetOwner()); if (ret_dt == DataType::INT32 && src_dt == DataType::BOOL) { std::vector<int> ret; ret.reserve(op0_type.GetTotalNumOfElements()); for (int i = 0; i < op0_type.GetTotalNumOfElements(); ++i) { ret.push_back(static_cast<int>(c_src->GetData<int8_t>(i))); } Constant* c_ret = cb.CreateConstant( inst->GetName(), halo::Type{ret_dt, op0_type.GetDimSizes()}, ret.data()); return {orig_def, *c_ret}; } if (ret_dt == DataType::INT32 && src_dt == DataType::INT64) { std::vector<int32_t> ret; ret.reserve(op0_type.GetTotalNumOfElements()); for (int i = 0, e = op0_type.GetTotalNumOfElements(); i != e; ++i) { ret.push_back(static_cast<int32_t>(c_src->GetData<int64_t>(i))); } Constant* c_ret = cb.CreateConstant( inst->GetName() + "_folding", halo::Type{ret_dt, op0_type.GetDimSizes()}, ret.data()); return {orig_def, *c_ret}; } if (ret_dt == DataType::INT64 && src_dt == DataType::INT32) { std::vector<int64_t> ret; ret.reserve(op0_type.GetTotalNumOfElements()); for (int i = 0, e = op0_type.GetTotalNumOfElements(); i != e; ++i) { ret.push_back(static_cast<int64_t>(c_src->GetData<int32_t>(i))); } Constant* c_ret = cb.CreateConstant( inst->GetName() + "_folding", halo::Type{ret_dt, op0_type.GetDimSizes()}, ret.data()); return {orig_def, *c_ret}; } return {orig_def, orig_def}; } std::pair<Def, Def> InstSimplify::RunOnInstruction(RangeInst* inst) { Def orig_def{inst, 0}; auto op0 = inst->GetOperand(0); auto op1 = inst->GetOperand(1); auto op2 = inst->GetOperand(2); DataType dt = op0.GetType().GetDataType(); if (!IsA<Constant>(op0.GetOwner()) || !IsA<Constant>(op1.GetOwner()) || !IsA<Constant>(op2.GetOwner()) || dt != DataType::INT32) { return {orig_def, orig_def}; } int64_t num_elements = 0; Constant* c_op0 = DynCast<Constant>(op0.GetOwner()); Constant* c_op1 = DynCast<Constant>(op1.GetOwner()); Constant* c_op2 = DynCast<Constant>(op2.GetOwner()); int begin = c_op0->GetData<int32_t>(0); int end = c_op1->GetData<int32_t>(0); int step = c_op2->GetData<int32_t>(0); num_elements = std::max(0, (end - begin) / step); HLCHECK(num_elements); std::vector<int> ret_data(num_elements); ret_data[0] = begin; for (int i = 1; i < num_elements; ++i) { ret_data[i] = ret_data[i - 1] + step; } ConstantBuilder cb(inst->GetParent()->GetParent()); Constant* c_ret = cb.CreateConstant(inst->GetName() + "_folding", halo::Type{dt, {num_elements}}, ret_data.data()); return {orig_def, *c_ret}; } std::pair<Def, Def> InstSimplify::RunOnInstruction(SetDiff1DInst* inst) { Def orig_def{inst, 0}; auto op0 = inst->GetOperand(0); auto op1 = inst->GetOperand(1); const auto& op0_type = op0.GetType(); const auto& op1_type = op1.GetType(); DataType dt = op0_type.GetDataType(); if (!IsA<Constant>(op0.GetOwner()) || !IsA<Constant>(op1.GetOwner()) || dt != DataType::INT32) { return {orig_def, orig_def}; } std::vector<int> ret_data; std::unordered_set<int> diff_set; Constant* c_op0 = DynCast<Constant>(op0.GetOwner()); Constant* c_op1 = DynCast<Constant>(op1.GetOwner()); for (int i = 0, e = op1_type.GetTotalNumOfElements(); i != e; ++i) { diff_set.emplace(c_op1->GetData<int>(i)); } for (int i = 0, e = op0_type.GetTotalNumOfElements(); i != e; ++i) { int data_i = c_op0->GetData<int>(i); if (diff_set.count(data_i) == 0) { ret_data.push_back(data_i); } } ConstantBuilder cb(inst->GetParent()->GetParent()); Constant* c_ret = cb.CreateConstant( inst->GetName() + "_folding", halo::Type{dt, {static_cast<int64_t>(ret_data.size())}}, ret_data.data()); return {orig_def, *c_ret}; } std::pair<Def, Def> InstSimplify::RunOnInstruction(GatherInst* inst) { Def orig_def{inst, 0}; int axis = inst->GetAxis(); const auto& dst_type = inst->GetResultsTypes()[0]; const auto& type_op0 = inst->GetOperand(0).GetType(); const auto& op1 = inst->GetOperand(1); // Gather(data, ZExt(index, int64)) ==> Gather(data, index) if (IsA<Instruction>(op1) && DynCast<Instruction>(op1)->GetOpCode() == OpCode::ZEXT) { IRBuilder builder(inst->GetParent()); ZExtInst* zext = DynCast<ZExtInst>(op1.GetDef()); builder.SetInsertAfter(inst); auto ops = inst->GetOperands(); ops[1] = zext->GetOperand(0); auto new_inst = builder.Clone(*inst, ops); return {orig_def, *new_inst}; } if (!type_op0.IsValid()) { return {orig_def, orig_def}; } if (axis < 0) { axis += type_op0.GetNumOfDims(); } HLCHECK(axis >= 0 && axis < static_cast<int>(type_op0.GetNumOfDims())); for (size_t i = 0; i < inst->GetNumOfOperands(); ++i) { if (!IsA<Constant>(inst->GetOperand(i).GetOwner())) { return {orig_def, orig_def}; } } if (!dst_type.IsValid()) { return {orig_def, orig_def}; } Constant* c_op0 = DynCast<Constant>(inst->GetOperand(0).GetOwner()); const auto& type_op1 = inst->GetOperand(1).GetType(); Constant* c_op1 = DynCast<Constant>(inst->GetOperand(1).GetOwner()); DataType dt = dst_type.GetDataType(); DefaultDataLayout data_layout; size_t byte_per_element = data_layout.Bytes(dt); size_t bytes = byte_per_element * dst_type.GetTotalNumOfElements(); std::vector<unsigned char> buf(bytes); size_t per_copy_bytes = byte_per_element; auto dst_extends = GetExtends(dst_type.GetDimSizes()); auto src_extends = GetExtends(type_op0.GetDimSizes()); auto idx_extends = GetExtends(type_op1.GetDimSizes()); int64_t dst_rank = dst_type.GetNumOfDims(); if (dst_rank == 0 && dst_type.GetTotalNumOfElements() == 1) { dst_rank = 1; } int op1_rank = type_op1.GetNumOfDims(); if (op1_rank == 0 && type_op1.GetTotalNumOfElements() == 1) { op1_rank = 1; } for (int64_t dst_idx = 0, e = dst_type.GetTotalNumOfElements(); dst_idx < e; ++dst_idx) { // map dst_idx to src_idx. std::vector<int64_t> dst_dims(dst_rank); for (int64_t i = 0, k = dst_idx; k > 0 && i < dst_rank; ++i) { dst_dims[i] = k / dst_extends[i]; k -= dst_dims[i] * dst_extends[i]; } std::vector<int64_t> src_dims(type_op0.GetNumOfDims()); for (int i = 0; i < dst_rank; ++i) { if (i < axis) { src_dims[i] = dst_dims[i]; } else if (i >= (axis + op1_rank)) { src_dims[i - op1_rank + 1] = dst_dims[i]; } else { int64_t idx = std::inner_product(idx_extends.begin(), idx_extends.end(), dst_dims.begin() + axis, 0L); src_dims[axis] = c_op1->GetDataAsInt64(idx); } } int64_t src_idx = std::inner_product(src_dims.begin(), src_dims.end(), src_extends.begin(), 0L); unsigned char* src_ptr = static_cast<unsigned char*>(c_op0->GetRawDataPtr()) + // NOLINT. src_idx * per_copy_bytes; std::copy_n(src_ptr, per_copy_bytes, buf.begin() + dst_idx * per_copy_bytes); } ConstantBuilder cb(inst->GetParent()->GetParent()); Constant* c_ret = cb.CreateConstant(inst->GetName() + "_folding", dst_type, buf.data()); return {orig_def, *c_ret}; } std::pair<Def, Def> InstSimplify::RunOnInstruction(ConcatInst* inst) { Def orig_def{inst, 0}; // Concat(Transpose(A), Transpose(B),...) => Transpose(Concat(A, B)) std::vector<int> perm; size_t n = inst->GetNumOfOperands(); std::vector<Def> tr_ops; tr_ops.reserve(n); for (size_t i = 0; i < n; ++i) { auto op = inst->GetOperand(i); if (!IsA<Instruction>(op)) { break; } const Instruction* op_inst = DynCast<Instruction>(op); if (op_inst->GetOpCode() != OpCode::TRANSPOSE) { break; } const TransposeInst* tr = DynCast<const TransposeInst>(op_inst); if (i == 0) { perm = tr->GetPermutation(); } else if (perm != tr->GetPermutation()) { break; } tr_ops.push_back(tr->GetOperand(0)); } if (tr_ops.size() == n) { IRBuilder builder(inst->GetParent()); builder.SetInsertAfter(inst); auto new_concat = builder.CreateConcat(inst->GetName(), tr_ops); new_concat->SetAxis(perm[inst->GetAxis()]); TransposeInst* new_tr = builder.CreateTranspose(new_concat->GetName() + "_t", {*new_concat}); new_tr->SetPermutation(perm); return {orig_def, *new_tr}; } for (size_t i = 0; i < inst->GetNumOfOperands(); ++i) { if (!IsA<Constant>(inst->GetOperand(i).GetOwner())) { return {orig_def, orig_def}; } } int num_inputs = inst->GetN(); int axis = inst->GetAxis(); const auto& dst_type = inst->GetResultsTypes()[0]; if (!dst_type.IsValid() || axis != 0) { return {orig_def, orig_def}; } // Constant propagating on axis = 0 DataType dt = dst_type.GetDataType(); DefaultDataLayout data_layout; size_t byte_per_element = data_layout.Bytes(dt); size_t bytes = byte_per_element * dst_type.GetTotalNumOfElements(); std::vector<unsigned char> buf(bytes); size_t offset = 0; for (int i = 0; i < num_inputs; ++i) { auto input = inst->GetOperand(i); Constant* c_input = DynCast<Constant>(input.GetOwner()); size_t num_elements = input.GetType().GetTotalNumOfElements(); size_t copy_bytes = num_elements * byte_per_element; std::copy_n(static_cast<unsigned char*>(c_input->GetRawDataPtr()), copy_bytes, buf.begin() + offset); offset += copy_bytes; } ConstantBuilder cb(inst->GetParent()->GetParent()); Constant* c_ret = cb.CreateConstant(inst->GetName() + "_folding", dst_type, buf.data()); return {orig_def, *c_ret}; } std::pair<Def, Def> InstSimplify::RunOnInstruction(TransposeInst* inst) { Def orig_def{inst, 0}; std::pair<Def, Def> ret{orig_def, orig_def}; const auto& input = inst->GetOperand(0); // Fold constant perm op into attribute. if (inst->GetNumOfOperands() == 2 && IsA<Constant>(inst->GetOperand(1))) { const Constant* data = DynCast<Constant>(inst->GetOperand(1)); const auto& ty = data->GetResultType(); if (ty.GetDataType() == DataType::INT32) { const int32_t* ptr = data->GetDataPtr<int32_t>(); std::vector<int> perms(ptr, ptr + ty.GetTotalNumOfElements()); // NOLINT IRBuilder builder(inst->GetParent()); builder.SetInsertAfter(inst); TransposeInst* new_inst = builder.CreateTranspose(inst->GetName(), {input}); new_inst->SetPermutation(perms); ret.second = *new_inst; return ret; } } const auto& perm = inst->GetPermutation(); auto input_type = (input.GetDef()->GetResultsTypes()[input.GetIdx()]); int dims = -1; std::vector<int64_t> new_shape; std::vector<size_t> perm_strides; std::vector<size_t> orig_strides; if (input_type.IsValid()) { const auto& orig_shape = input_type.GetDimSizes(); dims = orig_shape.size(); HLCHECK(orig_shape.size() == inst->GetPermutation().size()); orig_strides = std::vector<size_t>(dims, 1); for (int i = dims - 2; i >= 0; --i) { orig_strides[i] = orig_strides[i + 1] * orig_shape[i + 1]; } new_shape = orig_shape; perm_strides = orig_strides; for (int i = 0; i < dims; ++i) { new_shape[i] = orig_shape[perm[i]]; perm_strides[i] = orig_strides[perm[i]]; } } if (IsA<Constant>(input)) { // Do transpose at compile time. auto orig = DynCast<Constant>(input.GetOwner()); ConstantBuilder cb(inst->GetParent()->GetParent()); const auto& type = orig->GetResultType(); std::vector<int> pos(dims); // tracks the position of dst tensor. size_t elem_size = orig->GetElementSizeInBytes(); size_t elem_cnt = type.GetTotalNumOfElements(); std::vector<char> buf(elem_size * elem_cnt); for (size_t i = 0; i < elem_cnt; ++i) { size_t offset = std::inner_product(pos.begin(), pos.end(), perm_strides.begin(), 0UL) * elem_size; const char* src = static_cast<const char*>(orig->GetRawDataPtr()) + offset; // NOLINT memcpy(&buf[i * elem_size], src, elem_size); int c = 1; for (int i = dims - 1; i >= 0 && c == 1; --i) { pos[i] += c; if (pos[i] >= new_shape[i]) { pos[i] = 0; } else { c = 0; } } } auto new_c = cb.CreateConstant(orig->GetName() + "_T", halo::Type{type.GetDataType(), new_shape}, buf.data()); ret.second = *new_c; return ret; } if (remove_input_transpose_ && input.GetUses().size() == 1) { if (IsA<Argument>(input)) { Argument* arg = DynCast<Argument>(input); const auto& orig_dims = input.GetType().GetDimSizes(); const auto& perms = inst->GetPermutation(); auto new_dims = orig_dims; for (int i = 0, e = orig_dims.size(); i < e; ++i) { new_dims[i] = orig_dims[perms[i]]; } halo::Type ty{input.GetType().GetDataType(), new_dims}; arg->SetType(ty); ret.second = input; return ret; } } // Transpose(Transpose(in, perm0), perm1) => Transpose(in, perm2) if (IsA<Instruction>(input) && (DynCast<Instruction>(input))->GetOpCode() == OpCode::TRANSPOSE) { const TransposeInst* t0 = DynCast<TransposeInst>(input.GetOwner()); const auto& perm0 = t0->GetPermutation(); HLCHECK(perm0.size() == perm.size()); auto new_perm = perm0; for (int i = 0, e = perm0.size(); i < e; ++i) { new_perm[i] = perm[perm0[i]]; } IRBuilder builder(inst->GetParent()); builder.SetInsertAfter(inst); TransposeInst* new_trans = builder.CreateTranspose(inst->GetName(), {t0->GetOperand(0)}); new_trans->SetPermutation(new_perm); ret.second = *new_trans; return ret; } // Check if it is a redundant permute (all other dims are 1) const auto& type = input.GetType(); const auto& out_type = inst->GetResultType(); if (type.IsValid() && out_type.IsValid()) { unsigned non_ones = 0; for (auto& d : type.GetDimSizes()) { non_ones += d == 1 ? 0 : 1; } if (non_ones == 1) { IRBuilder builder(inst->GetParent()); builder.SetInsertAfter(inst); ConstantBuilder cb(inst->GetParent()->GetParent()); halo::Type reshape_ty{DataType::INT64, {static_cast<int64_t>(out_type.GetNumOfDims())}}; auto shape = cb.CreateConstant(inst->GetName() + "_reshape", reshape_ty, out_type.GetDimSizes().data()); ReshapeInst* reshape = builder.CreateReshape(inst->GetName(), {input, *shape}); reshape->GetResultsTypes()[0] = out_type; ret.second = *reshape; return ret; } } // Check if a permutaton is redundant. bool is_redundant = true; for (int i = 0, e = perm.size(); i < e; ++i) { if (perm[i] != i) { is_redundant = false; break; } } if (is_redundant) { ret.second = inst->GetOperand(0); return ret; } // Transpose => Reshape if its' like (N, 1, H, W) => (N, H, W, 1) if (dims > 0) { const auto& orig_shape = input_type.GetDimSizes(); auto new_perm = perm; for (int i = 0, a = 0; i < dims; ++i, ++a) { if (orig_shape[i] == 1) { for (auto& v : new_perm) { if (v == a) { v = -1; // skip the dim } if (v > a) { --v; } } --a; } } bool reshapable = true; for (int i = 0, c = 0; i < dims && reshapable; ++i) { if (new_perm[i] >= 0) { if (new_perm[i] != c++) { reshapable = false; } } } if (reshapable) { IRBuilder builder(inst->GetParent()); builder.SetInsertAfter(inst); ConstantBuilder cb(inst->GetParent()->GetParent()); Constant* c_shape = cb.CreateConstant( inst->GetName() + "_shape", halo::Type{DataType::INT64, std::vector<int64_t>{dims}}, new_shape.data()); auto reshape = builder.CreateReshape(inst->GetName(), {inst->GetOperand(0), *c_shape}); reshape->GetResultsTypes()[0] = inst->GetResultType(); ret.second = *reshape; return ret; } } return ret; } std::pair<Def, Def> InstSimplify::RunOnInstruction(ReturnInst* inst) { Def orig_def{inst, 0}; if (!remove_output_transpose_) { return {orig_def, orig_def}; } for (int i = 0, e = inst->GetNumOfOperands(); i < e; ++i) { const auto& op = inst->GetOperand(i); if (IsA<Instruction>(op) && DynCast<Instruction>(op)->GetOpCode() == OpCode::TRANSPOSE) { inst->ReplaceOperandWith(i, DynCast<Instruction>(op)->GetOperand(0)); } } return {orig_def, orig_def}; } std::pair<Def, Def> InstSimplify::RunOnInstruction(RandomUniformInst* inst) { Def orig_def{inst, 0}; const auto& dst_type = inst->GetResultsTypes()[0]; if (dst_type.IsValid() && dst_type.GetDataType() == DataType::FLOAT32) { auto noe = dst_type.GetTotalNumOfElements(); float max_val = inst->GetMaxval(); float min_val = inst->GetMinval(); // int seed = inst->GetSeed(); std::vector<float> ret(noe); // std::random_device rd; // std::mt19937 gen(rd()); std::mt19937 gen(1234); // NOLINT std::uniform_real_distribution<> dis(min_val, max_val); for (int i = 0; i < noe; ++i) { ret[i] = dis(gen); } ConstantBuilder cb(inst->GetParent()->GetParent()); Constant* c_ret = cb.CreateConstant(inst->GetName() + "_folding", dst_type, ret.data()); return {orig_def, *c_ret}; } return {orig_def, orig_def}; } std::pair<Def, Def> InstSimplify::RunOnInstruction(SliceInst* inst) { Def orig_def{inst, 0}; auto op2 = inst->GetOperand(2); const auto& dst_type = inst->GetResultsTypes()[0]; if (dst_type.IsValid() && IsA<Constant>(op2.GetOwner())) { Constant* c_size = DynCast<Constant>(op2.GetOwner()); if (op2.GetType().GetDataType() == DataType::INT32) { int dim = op2.GetType().GetTotalNumOfElements(); std::vector<int> size_adj(dim); bool new_size = false; for (int i = 0; i != dim; ++i) { int size_i = c_size->GetData<int>(i); if (size_i == -1) { size_adj[i] = dst_type.GetNumOfElementsInDim(i); new_size = true; } else { size_adj[i] = size_i; } } if (new_size) { ConstantBuilder cb(inst->GetParent()->GetParent()); Constant* c_new_size = cb.CreateConstant( op2.GetOwner()->GetName() + "_adj", op2.GetType(), size_adj.data()); IRBuilder builder(inst->GetParent()); builder.SetInsertAfter(inst); SliceInst* new_inst = builder.CreateSlice( inst->GetName(), {inst->GetOperand(0), inst->GetOperand(1), *c_new_size}); new_inst->GetResultsTypes()[0] = dst_type; return {orig_def, *new_inst}; } } } auto op0 = inst->GetOperand(0); auto op1 = inst->GetOperand(1); bool has_constant_steps = (inst->GetNumOfOperands() < 4 || IsA<Constant>(inst->GetOperand(3))); has_constant_steps &= (inst->GetNumOfOperands() <= 4 || IsA<Constant>(inst->GetOperand(4))); if (IsA<Constant>(op0) && IsA<Constant>(op1) && IsA<Constant>(op2) && inst->GetResultType().IsValid() && has_constant_steps) { Constant* input = DynCast<Constant>(op0); const auto& dt = inst->GetResultType(); std::vector<int64_t> data(dt.GetTotalNumOfElements()); auto starts = DynCast<Constant>(op1); auto lens = DynCast<Constant>(op2); // auto steps = DynCast<Constant>(op3); // auto axes = DynCast<Constant>(op4); auto rank = op0.GetType().GetNumOfDims(); if (rank == 1 && dt.GetDataType() == DataType::INT64) { auto idx = starts->GetData<int32_t>(0); auto len = lens->GetData<int32_t>(0); HLCHECK(static_cast<size_t>(len) == data.size()); for (int i = 0; i < len; ++i) { data[i] = input->GetData<int64_t>(idx + i); } ConstantBuilder cb(inst->GetParent()->GetParent()); auto c = cb.CreateConstant(inst->GetName(), dt, data.data()); return {orig_def, *c}; } } return {orig_def, orig_def}; } std::pair<Def, Def> InstSimplify::RunOnInstruction(FPtoSIInst* inst) { Def orig_def{inst, 0}; auto op0 = inst->GetOperand(0); if (IsA<Constant>(op0)) { auto src_ty = op0.GetType().GetDataType(); auto dst_ty = inst->GetResultType().GetDataType(); ConstantBuilder cb(inst->GetParent()->GetParent()); Constant* input = DynCast<Constant>(op0); auto n = op0.GetType().GetTotalNumOfElements(); if (src_ty == DataType::FLOAT32 && (dst_ty == DataType::INT32 || dst_ty == DataType::INT64 || dst_ty == DataType::UINT32)) { Constant* c = nullptr; if (dst_ty == DataType::INT32) { std::vector<int32_t> vals(n); for (int64_t i = 0; i < n; ++i) { vals[i] = input->GetData<float>(i); } c = cb.CreateConstant(inst->GetName(), inst->GetResultType(), vals.data()); } else if (dst_ty == DataType::UINT32) { std::vector<uint32_t> vals(n); for (int64_t i = 0; i < n; ++i) { vals[i] = input->GetData<float>(i); } c = cb.CreateConstant(inst->GetName(), inst->GetResultType(), vals.data()); } else { std::vector<int64_t> vals(n); for (int64_t i = 0; i < n; ++i) { vals[i] = input->GetData<float>(i); } c = cb.CreateConstant(inst->GetName(), inst->GetResultType(), vals.data()); } return {orig_def, *c}; } } return {orig_def, orig_def}; } std::pair<Def, Def> InstSimplify::RunOnInstruction(SItoFPInst* inst) { Def orig_def{inst, 0}; auto op0 = inst->GetOperand(0); if (IsA<Instruction>(op0.GetOwner())) { Instruction* reshape_inst = DynCast<Instruction>(op0.GetOwner()); if (reshape_inst->GetOpCode() == OpCode::RESHAPE && reshape_inst->GetNumberOfUses() == 1) { auto op_reshape = reshape_inst->GetOperand(0); if (IsA<Argument>(op_reshape.GetOwner())) { Argument* arg = DynCast<Argument>(op_reshape.GetOwner()); if (arg->GetNumberOfUses() == 1 && op_reshape.GetType().IsValid()) { arg->SetType(halo::Type{DataType::FLOAT32, op_reshape.GetType().GetDimSizes()}); return {orig_def, *reshape_inst}; } } } } else if (IsA<Argument>(op0.GetOwner()) && op0.GetType().IsValid() && DynCast<Argument>(op0.GetOwner())->GetNumberOfUses() == 1) { Argument* arg = DynCast<Argument>(op0.GetOwner()); arg->SetType(halo::Type{DataType::FLOAT32, op0.GetType().GetDimSizes()}); return {orig_def, *arg}; } else if (IsA<Constant>(op0)) { auto src_ty = op0.GetType().GetDataType(); Constant* input = DynCast<Constant>(op0); auto n = op0.GetType().GetTotalNumOfElements(); if (inst->GetDataType() == DataType::FLOAT32 && (src_ty == DataType::INT32 || src_ty == DataType::INT64)) { std::vector<float> vals(n); for (int64_t i = 0; i < n; ++i) { vals[i] = (src_ty == DataType::INT32) ? input->GetData<int32_t>(i) : input->GetData<int64_t>(i); } ConstantBuilder cb(inst->GetParent()->GetParent()); auto c = cb.CreateConstant(inst->GetName(), inst->GetResultType(), vals.data()); return {orig_def, *c}; } } return {orig_def, orig_def}; } std::pair<Def, Def> InstSimplify::RunOnInstruction(OneHotInst* inst) { Def orig_def{inst, 0}; // work around on cxx target when backend doens't support onehot. if (!simplify_for_preprocess_) { return {orig_def, orig_def}; } auto on_value = inst->GetOperand(2); auto off_value = inst->GetOperand(3); const auto& dst_type = inst->GetResultsTypes()[0]; if (!IsA<Constant>(on_value.GetOwner()) || !IsA<Constant>(off_value.GetOwner()) || !dst_type.IsValid()) { return {orig_def, orig_def}; } auto op0 = inst->GetOperand(0); if (IsA<Instruction>(op0.GetOwner())) { Instruction* reshape_inst = DynCast<Instruction>(op0.GetOwner()); if (reshape_inst->GetOpCode() == OpCode::RESHAPE && reshape_inst->GetNumberOfUses() == 1) { auto op_reshape = reshape_inst->GetOperand(0); if (IsA<Argument>(op_reshape.GetOwner())) { Argument* arg = DynCast<Argument>(op_reshape.GetOwner()); if (arg->GetNumberOfUses() == 1 && op_reshape.GetType().IsValid()) { arg->SetType(halo::Type{on_value.GetType().GetDataType(), dst_type.GetDimSizes()}); return {orig_def, *arg}; } } } } else if (IsA<Argument>(op0.GetOwner()) && op0.GetType().IsValid() && DynCast<Argument>(op0.GetOwner())->GetNumberOfUses() == 1) { Argument* arg = DynCast<Argument>(op0.GetOwner()); arg->SetType( halo::Type{on_value.GetType().GetDataType(), dst_type.GetDimSizes()}); return {orig_def, *arg}; } return {orig_def, orig_def}; } bool InstSimplify::RunOnBasicBlock(BasicBlock* bb) { bool changed = false; for (auto& inst_t : *bb) { Instruction* inst = inst_t.get(); if (inst->GetNumberOfUses() == 0) { if (inst->GetOpCode() == OpCode::RETURN) { RunOnInstruction(DynCast<ReturnInst>(inst)); } continue; } std::pair<Def, Def> ret{Def{inst, 0}, Def{inst, 0}}; switch (inst->GetOpCode()) { #define GET_INST_DOWNCAST_SWITCH_WITH_RETURN #include "halo/lib/ir/instructions_info.def" #undef GET_INST_DOWNCAST_SWITCH_WITH_RETURN default: { // skip extension instruction. continue; } } if (ret.first != ret.second) { changed |= true; if (ret.second.GetOwner() != nullptr) { // Replace all uses inst->ReplaceAllUsesWith(ret.first.GetIdx(), ret.second); } } } return changed; } } // end namespace halo
37.114492
80
0.604044
xuhongyao
e16fbd6bad4e3210e705d87fae229fa40a5a1b20
2,131
hpp
C++
include/agents.hpp
tomatenbrei/pomcpp
55522748369bc167420f3ca5b0ecde314ca2fee3
[ "MIT" ]
null
null
null
include/agents.hpp
tomatenbrei/pomcpp
55522748369bc167420f3ca5b0ecde314ca2fee3
[ "MIT" ]
2
2020-06-30T12:01:51.000Z
2021-05-14T13:57:48.000Z
include/agents.hpp
tomatenbrei/pomcpp
55522748369bc167420f3ca5b0ecde314ca2fee3
[ "MIT" ]
2
2020-06-30T10:23:43.000Z
2021-08-01T17:24:08.000Z
#ifndef RANDOM_AGENT_H #define RANDOM_AGENT_H #include <random> #include "bboard.hpp" #include "strategy.hpp" namespace agents { /** * Use this as an example to implement more sophisticated * agents. * * @brief Randomly selects actions */ struct RandomAgent : bboard::Agent { std::mt19937_64 rng; std::uniform_int_distribution<int> intDist; RandomAgent(); bboard::Move act(const bboard::State* state) override; }; /** * @brief Randomly selects actions that are not laying bombs */ struct HarmlessAgent : bboard::Agent { std::mt19937_64 rng; std::uniform_int_distribution<int> intDist; HarmlessAgent(); bboard::Move act(const bboard::State* state) override; }; /** * @brief Selects Idle for every action */ struct LazyAgent : bboard::Agent { bboard::Move act(const bboard::State* state) override; }; /** * @brief Handcrafted agent by m2q */ struct SimpleAgent : bboard::Agent { std::mt19937_64 rng; SimpleAgent(); SimpleAgent(long seed); ////////////// // Specific // ////////////// int danger = 0; bboard::strategy::RMap r; bboard::FixedQueue<bboard::Move, bboard::MOVE_COUNT> moveQueue; // capacity of recent positions static const int rpCapacity = 4; bboard::FixedQueue<bboard::Position, rpCapacity> recentPositions; virtual bboard::Move decide(const bboard::State* state); bboard::Move act(const bboard::State* state) override; void reset() override; void PrintDetailedInfo(); }; /** * @brief An improved version of SimpleAgent. Adds more randomization to get equal win rates and collects powerups. * Also includes adjustments of parameters to (hopefully) result in better gameplay. */ struct SimpleUnbiasedAgent : SimpleAgent { std::array<int, 4> agentAxis; std::array<bboard::Move, bboard::MOVE_COUNT> dirAxis; std::array<int, bboard::BOARD_SIZE> boardAxisX; std::array<int, bboard::BOARD_SIZE> boardAxisY; SimpleUnbiasedAgent(); SimpleUnbiasedAgent(long seed); bboard::Move decide(const bboard::State* state) override; void reset() override; }; } #endif
20.892157
115
0.686063
tomatenbrei
e170671ba42c63be5c176a98927ed605da6525e8
3,914
hpp
C++
SimpleDB/src/core/sql/pragma.hpp
caivao/SimpleDB
ff90245c5ffc96ea84cf046596d690866c1c8cb6
[ "MIT" ]
1
2021-01-05T17:01:31.000Z
2021-01-05T17:01:31.000Z
SimpleDB/src/core/sql/pragma.hpp
caivao/SimpleDB
ff90245c5ffc96ea84cf046596d690866c1c8cb6
[ "MIT" ]
null
null
null
SimpleDB/src/core/sql/pragma.hpp
caivao/SimpleDB
ff90245c5ffc96ea84cf046596d690866c1c8cb6
[ "MIT" ]
null
null
null
// // pragma.hpp // SimpleDB // // Created by lifeng on 2019/6/5. // Copyright © 2019 feng. All rights reserved. // #ifndef pragma_hpp #define pragma_hpp #include "declare.hpp" #include "describable.hpp" namespace SDB { class Pragma : public Describable { public: static const Pragma application_id; static const Pragma auto_vacuum; static const Pragma automatic_index; static const Pragma busy_timeout; static const Pragma cache_size; static const Pragma cache_spill; static const Pragma case_sensitive_like; static const Pragma cell_size_check; static const Pragma checkpoint_fullfsync; static const Pragma cipher; static const Pragma cipher_add_random; static const Pragma cipher_default_kdf_iter; static const Pragma cipher_default_page_size; static const Pragma cipher_page_size; static const Pragma cipher_default_use_hmac; static const Pragma cipher_migrate; static const Pragma cipher_profile; static const Pragma cipher_provider; static const Pragma cipher_provider_version; static const Pragma cipher_use_hmac; static const Pragma cipher_version; static const Pragma collation_list; static const Pragma compile_options; static const Pragma count_changes; static const Pragma data_store_directory; static const Pragma data_version; static const Pragma database_list; static const Pragma default_cache_size; static const Pragma defer_foreign_keys; static const Pragma empty_result_callbacks; static const Pragma encoding; static const Pragma foreign_key_check; static const Pragma foreign_key_list; static const Pragma foreign_keys; static const Pragma freelist_count; static const Pragma full_column_names; static const Pragma fullfsync; static const Pragma ignore_check_constraints; static const Pragma incremental_vacuum; static const Pragma index_info; static const Pragma index_list; static const Pragma index_xinfo; static const Pragma integrity_check; static const Pragma journal_mode; static const Pragma journal_size_limit; static const Pragma key; static const Pragma kdf_iter; static const Pragma legacy_file_format; static const Pragma locking_mode; static const Pragma max_page_count; static const Pragma mmap_size; static const Pragma page_count; static const Pragma page_size; static const Pragma parser_trace; static const Pragma query_only; static const Pragma quick_check; static const Pragma read_uncommitted; static const Pragma recursive_triggers; static const Pragma rekey; static const Pragma reverse_unordered_selects; static const Pragma schema_version; static const Pragma secure_delete; static const Pragma short_column_names; static const Pragma shrink_memory; static const Pragma soft_heap_limit; static const Pragma stats; static const Pragma synchronous; static const Pragma table_info; static const Pragma temp_store; static const Pragma temp_store_directory; static const Pragma threads; static const Pragma user_version; static const Pragma vdbe_addoptrace; static const Pragma vdbe_debug; static const Pragma vdbe_listing; static const Pragma vdbe_trace; static const Pragma wal_autocheckpoint; static const Pragma wal_checkpoint; static const Pragma writable_schema; const std::string &name(void) const; protected: Pragma(const char *name); }; } #endif /* pragma_hpp */
36.240741
54
0.692897
caivao
e174846f52e77d02b4bfa32f795c1b02d57c8f8e
9,465
hpp
C++
extlibs/include/Jopnal/Core/FileLoader.hpp
Jopnal/Jopmodel
cfd50b9fd24eaf63497bf5bed883f0b831d9ad65
[ "Zlib" ]
2
2016-07-16T17:21:10.000Z
2016-08-09T11:41:33.000Z
extlibs/include/Jopnal/Core/FileLoader.hpp
Jopnal/Jopmodel
cfd50b9fd24eaf63497bf5bed883f0b831d9ad65
[ "Zlib" ]
null
null
null
extlibs/include/Jopnal/Core/FileLoader.hpp
Jopnal/Jopmodel
cfd50b9fd24eaf63497bf5bed883f0b831d9ad65
[ "Zlib" ]
null
null
null
// Jopnal Engine C++ Library // Copyright (c) 2016 Team Jopnal // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgement in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. ////////////////////////////////////////////// #ifndef GP_FILELOADER_HPP #define GP_FILELOADER_HPP // Headers #include <Jopnal/Header.hpp> #include <Jopnal/Core/Subsystem.hpp> #include <string> #include <vector> ////////////////////////////////////////////// struct PHYSFS_File; namespace Assimp { class Importer; } namespace jop { class JOP_API FileSystemInitializer final : public Subsystem { private: JOP_DISALLOW_COPY_MOVE(FileSystemInitializer); friend class ModelLoader; static Assimp::Importer& getImporter(); public: FileSystemInitializer(const char* arg); ~FileSystemInitializer(); }; class JOP_API FileLoader { private: JOP_DISALLOW_COPY(FileLoader); public: /// Base directory for writing files /// enum class Directory { Executable, ///< Executable directory Resource, ///< Resource folder User ///< User folder }; public: /// \brief Default constructor /// /// Doesn't initialize any file handles. /// FileLoader(); /// \brief Overloaded constructor /// /// This will open the file for writing if found /// /// \param path Path to file to open /// /// \see isValid /// explicit FileLoader(const std::string& path); /// \brief Overloaded constructor /// /// This will open the file for writing if found. /// /// \param dir Base write directory /// \param path Path to file to open /// \param append Append to the file. False to clear the file before writing /// /// \see isValid /// FileLoader(const Directory dir, const std::string& path, const bool append); /// \brief Move constructor /// FileLoader(FileLoader&& other); /// \brief Move assignment operator /// /// \return Reference to self /// FileLoader& operator =(FileLoader&& other); /// \brief Destructor /// /// Will close the file handle if open. /// ~FileLoader(); /// \brief Open a file for reading /// /// \param path Path to the file /// /// \return True if opened successfully /// bool open(const std::string& path); /// \brief Open a file for writing /// /// \copydetails FileLoader(const Directory, const std::string&, const bool) /// /// \return True if opened successfully /// bool open(const Directory dir, const std::string& path, const bool append); /// \brief Flush the file handle if open /// void flush(); /// \brief Close the file handle if open /// /// When writing, calling this means saving the file. /// void close(); /// \brief Check if a file handle exists /// /// \return True if a valid file handle exists /// bool isValid() const; /// \brief Read data /// /// \param data Pointer to a pre-allocated data buffer /// \param size Amount of data to read /// /// \return Amount of data read in bytes /// /// \see getSize /// int64 read(void* data, const uint64 size); /// \brief Write data /// /// \param data Data to write /// \param size Amount of data to write in bytes /// /// \return Amount of data written in bytes /// int64 write(const void* data, const uint64 size); /// \brief Move the cursor to the given position /// /// \param position The cursor position to set /// /// \return True if successful /// bool seek(const uint64 position); /// \brief Get the current position of the cursor /// /// \return Current position of the file read/write cursor /// int64 tell(); /// \brief Get the size of the opened file /// /// \return Size of the file /// int64 getSize(); /// \copydoc isValid /// operator bool() const; /// \brief Check if a file exists /// /// \param path Path to the file to check /// /// \return True if the file exists /// static bool fileExists(const std::string& path); /// \brief Enumerate all files within a directory /// /// \param path Path to a directory /// \param list Reference to a list to fill with the file paths found /// /// \see listFilesRecursive /// static void listFiles(const std::string& path, std::vector<std::string>& list); /// \brief Enumerate all files within a directory recursively /// /// \param path Path to a directory /// \param list Reference to a list to fill with the file paths found /// /// \see listFiles /// static void listFilesRecursive(const std::string& path, std::vector<std::string>& list); /// \brief Delete a file /// /// \param file Path to the file /// /// \return True if file was deleted /// static bool deleteFile(const std::string& file); /// \brief Read a text file /// /// \param path Path to the file to read /// \param file Reference to a string to fill with the data /// /// \return True if successful /// static bool readTextfile(const std::string& path, std::string& file); /// \brief Read a binary file /// /// \param path Path to the file to read /// \param buffer Reference to a buffer to fill with the data /// /// \return True if successful /// static bool readBinaryfile(const std::string& path, std::vector<uint8>& buffer); /// \brief Write a text file /// /// \param dir The base write directory /// \param path The file path /// \param text The text to write /// \param append Append to file? /// /// \return True if successful /// static bool writeTextfile(const Directory dir, const std::string& path, const std::string& text, const bool append = false); /// \brief Write a binary file /// /// \param dir The base write directory /// \param path The file path /// \param data The binary data to write /// \param bytes amount of bytes to write /// \param append Append to file? /// /// \return True if successful /// static bool writeBinaryfile(const Directory dir, const std::string& path, const void* data, const std::size_t bytes, const bool append = false); /// \brief Create a directory /// /// If the directory already exists, this has no effect. /// /// \param path The directory to create /// /// \return True if successful /// static bool makeDirectory(const std::string& path); /// \brief Get a base directory as string /// /// \param dir The base directory /// /// \return Internal reference to the directory string /// static const std::string& getDirectory(const Directory dir); /// \brief Get the OS-specific directory separator /// /// \return The directory separator /// static char getDirectorySeparator(); /// \brief Read a resource file /// /// This is mostly used internally. /// /// \param id Identifier of the resource /// \param buffer The data buffer /// /// \return True if successful /// static bool readResource(const int id, std::vector<uint8>& buffer); /// \brief Enable/disable file system error checks /// /// \param enable True to enable /// static void enableErrorChecks(const bool enable); /// \brief Check if file system error checks are enabled /// /// \return True if enabled /// static bool errorChecksEnabled(); private: PHYSFS_File* m_file; ///< File handle }; } #endif
28.856707
152
0.55383
Jopnal
e174bb27f06f5c3215bc0dac6b91b42a1b116872
7,498
cpp
C++
components/protocols/onewire/onewire.cpp
thmalmeida/agro_mesh
fbce39d2e08d02495ecd3b55b2e826449b9dc3b7
[ "MIT" ]
2
2021-07-19T12:03:39.000Z
2021-07-22T18:37:45.000Z
components/protocols/onewire/onewire.cpp
thmalmeida/agro_mesh
fbce39d2e08d02495ecd3b55b2e826449b9dc3b7
[ "MIT" ]
null
null
null
components/protocols/onewire/onewire.cpp
thmalmeida/agro_mesh
fbce39d2e08d02495ecd3b55b2e826449b9dc3b7
[ "MIT" ]
1
2021-07-08T09:07:10.000Z
2021-07-08T09:07:10.000Z
#include "onewire.h" #include "hardware_defs.h" OneWire::OneWire(GPIO_Basic *gpio){ this->gpio = gpio; reset_search(); } // Perform the onewire reset function. We will wait up to 250uS for // the bus to come high, if it doesn't then it is broken or shorted // and we return a 0; // // Returns 1 if a device asserted a presence pulse, 0 otherwise. // uint8_t OneWire::reset(void){ uint8_t r; uint8_t retries = 125; gpio->mode(GPIO_MODE_INPUT); // wait until the wire is high... just in case do { if (--retries == 0) return 0; delay_us(2); } while ( !gpio->read()); disable_interrupts(); //Invertida as linhas abaixo gpio->mode(GPIO_MODE_OUTPUT); gpio->write(0); enable_interrupts(); delay_us(480); disable_interrupts(); gpio->mode(GPIO_MODE_INPUT); delay_us(70); r = !gpio->read(); enable_interrupts(); delay_us(410); return r; } // // Write a bit. Port and bit is used to cut lookup time and provide // more certain timing. // void OneWire::write_bit(uint8_t v) { if (v & 1) { disable_interrupts(); gpio->mode(GPIO_MODE_OUTPUT); gpio->write(0); delay_us(10); gpio->write(1); enable_interrupts(); delay_us(55); } else { disable_interrupts(); gpio->mode(GPIO_MODE_OUTPUT); gpio->write(0); delay_us(65); gpio->write(1); enable_interrupts(); delay_us(5); } } // // Read a bit. Port and bit is used to cut lookup time and provide // more certain timing. // uint8_t OneWire::read_bit(void) { uint8_t r; disable_interrupts(); gpio->mode(GPIO_MODE_OUTPUT); gpio->write(0); delay_us(3); gpio->mode(GPIO_MODE_INPUT); delay_us(10); r = gpio->read(); enable_interrupts(); delay_us(53); return r; } // // Write a byte. The writing code uses the active drivers to raise the // pin high, if you need power after the write (e.g. DS18S20 in // parasite power mode) then set 'power' to 1, otherwise the pin will // go tri-state at the end of the write to avoid heating in a short or // other mishap. // void OneWire::write(uint8_t v, uint8_t power /* = 0 */) { uint8_t bitMask; for (bitMask = 0x01; bitMask; bitMask <<= 1) { write_bit( (bitMask & v)?1:0); } if ( !power) { disable_interrupts(); gpio->mode(GPIO_MODE_INPUT); gpio->write(0); enable_interrupts(); } } void OneWire::write_bytes(const uint8_t *buf, uint16_t count, bool power /* = 0 */) { for (uint16_t i = 0 ; i < count ; i++) write(buf[i]); if (!power) { disable_interrupts(); gpio->mode(GPIO_MODE_INPUT); gpio->write(0); enable_interrupts(); } } // // Read a byte // uint8_t OneWire::read() { uint8_t bitMask; uint8_t r = 0; for (bitMask = 0x01; bitMask; bitMask <<= 1) { if ( OneWire::read_bit()) r |= bitMask; } return r; } void OneWire::read_bytes(uint8_t *buf, uint16_t count) { for (uint16_t i = 0 ; i < count ; i++) buf[i] = read(); } // // Do a ROM select // void OneWire::select(const uint8_t rom[8]){ uint8_t i; write(MATCH_ROM); // Choose ROM for (i = 0; i < 8; i++) write(rom[i]); } // // Do a ROM skip // void OneWire::skip(){ write(SKIP_ROM); // Skip ROM } void OneWire::depower(){ gpio->mode(GPIO_MODE_INPUT); } // // You need to use this function to start a search again from the beginning. // You do not need to do it for the first search, though you could. // void OneWire::reset_search() { // reset the search state LastDiscrepancy = 0; LastDeviceFlag = FALSE; LastFamilyDiscrepancy = 0; for(int i = 7; ; i--) { ROM_NO[i] = 0; if ( i == 0) break; } } // Setup the search to find the device type 'family_code' on the next call // to search(*newAddr) if it is present. // void OneWire::target_search(uint8_t family_code){ // set the search state to find SearchFamily type devices ROM_NO[0] = family_code; for (uint8_t i = 1; i < 8; i++) ROM_NO[i] = 0; LastDiscrepancy = 64; LastFamilyDiscrepancy = 0; LastDeviceFlag = FALSE; } // // Perform a search. If this function returns a '1' then it has // enumerated the next device and you may retrieve the ROM from the // OneWire::address variable. If there are no devices, no further // devices, or something horrible happens in the middle of the // enumeration then a 0 is returned. If a new device is found then // its address is copied to newAddr. Use OneWire::reset_search() to // start over. // // --- Replaced by the one from the Dallas Semiconductor web site --- //-------------------------------------------------------------------------- // Perform the 1-Wire Search Algorithm on the 1-Wire bus using the existing // search state. // Return TRUE : device found, ROM number in ROM_NO buffer // FALSE : device not found, end of search // uint8_t OneWire::search(uint8_t *newAddr) { uint8_t id_bit_number; uint8_t last_zero, rom_byte_number, search_result; uint8_t id_bit, cmp_id_bit; unsigned char rom_byte_mask, search_direction; // initialize for search id_bit_number = 1; last_zero = 0; rom_byte_number = 0; rom_byte_mask = 1; search_result = 0; // if the last call was not the last one if (!LastDeviceFlag){ // 1-Wire reset if (!reset()){ // reset the search LastDiscrepancy = 0; LastDeviceFlag = FALSE; LastFamilyDiscrepancy = 0; return FALSE; } // issue the search command write(SEARCH_ROM); // loop to do the search do{ // read a bit and its complement id_bit = read_bit(); cmp_id_bit = read_bit(); // check for no devices on 1-wire if ((id_bit == 1) && (cmp_id_bit == 1)) break; else{ // all devices coupled have 0 or 1 if (id_bit != cmp_id_bit) search_direction = id_bit; // bit write value for search else{ // if this discrepancy if before the Last Discrepancy // on a previous next then pick the same as last time if (id_bit_number < LastDiscrepancy) search_direction = ((ROM_NO[rom_byte_number] & rom_byte_mask) > 0); else // if equal to last pick 1, if not then pick 0 search_direction = (id_bit_number == LastDiscrepancy); // if 0 was picked then record its position in LastZero if (search_direction == 0){ last_zero = id_bit_number; // check for Last discrepancy in family if (last_zero < 9) LastFamilyDiscrepancy = last_zero; } } // set or clear the bit in the ROM byte rom_byte_number // with mask rom_byte_mask if (search_direction == 1) ROM_NO[rom_byte_number] |= rom_byte_mask; else ROM_NO[rom_byte_number] &= ~rom_byte_mask; // serial number search direction write bit write_bit(search_direction); // increment the byte counter id_bit_number // and shift the mask rom_byte_mask id_bit_number++; rom_byte_mask <<= 1; // if the mask is 0 then go to new SerialNum byte rom_byte_number and reset mask if (rom_byte_mask == 0){ rom_byte_number++; rom_byte_mask = 1; } } }while(rom_byte_number < 8); // loop until through all ROM bytes 0-7 // if the search was successful then if (!(id_bit_number < 65)){ // search successful so set LastDiscrepancy,LastDeviceFlag,search_result LastDiscrepancy = last_zero; // check for last device if (LastDiscrepancy == 0) LastDeviceFlag = TRUE; search_result = TRUE; } } // if no device found then reset counters so next 'search' will be like a first if (!search_result || !ROM_NO[0]){ LastDiscrepancy = 0; LastDeviceFlag = FALSE; LastFamilyDiscrepancy = 0; search_result = FALSE; } for (int i = 0; i < 8; i++) newAddr[i] = ROM_NO[i]; return search_result; }
23.803175
85
0.662443
thmalmeida
e17894aa7d464a7cf6880a7f155981729bdcfb8b
34,828
hpp
C++
src/axom/mint/mesh/Mesh.hpp
raineyeh/axom
57a6ef7ab50e113e4cf4b639657eb84ff10789c0
[ "BSD-3-Clause" ]
86
2019-04-12T20:39:37.000Z
2022-01-28T17:06:08.000Z
src/axom/mint/mesh/Mesh.hpp
raineyeh/axom
57a6ef7ab50e113e4cf4b639657eb84ff10789c0
[ "BSD-3-Clause" ]
597
2019-04-25T22:36:16.000Z
2022-03-31T20:21:54.000Z
src/axom/mint/mesh/Mesh.hpp
raineyeh/axom
57a6ef7ab50e113e4cf4b639657eb84ff10789c0
[ "BSD-3-Clause" ]
21
2019-06-27T15:53:08.000Z
2021-09-30T20:17:41.000Z
// Copyright (c) 2017-2021, Lawrence Livermore National Security, LLC and // other Axom Project Developers. See the top-level LICENSE file for details. // // SPDX-License-Identifier: (BSD-3-Clause) #ifndef MINT_MESH_HPP_ #define MINT_MESH_HPP_ #include "axom/core/Macros.hpp" // for Axom macros #include "axom/mint/mesh/CellTypes.hpp" // for CellType enum #include "axom/mint/config.hpp" // for mint compile-time type #include "axom/mint/mesh/FieldAssociation.hpp" // for FieldAssociation enum #include "axom/mint/mesh/FieldData.hpp" // for mint::FieldData #include "axom/mint/mesh/MeshCoordinates.hpp" // for mint::MeshCoordinates #include "axom/mint/mesh/MeshTypes.hpp" // for MeshType enum #include "axom/slic/interface/slic.hpp" // for SLIC macros namespace axom { /* Forward declarations */ #ifdef AXOM_MINT_USE_SIDRE namespace sidre { class Group; } #endif namespace mint { /* Forward declarations */ class Field; class Mesh; /// \name Free Methods /// @{ #ifdef AXOM_MINT_USE_SIDRE /*! * \brief Creates a mesh instance from the given Sidre group. * * \param [in] group pointer to the root group of the mesh in Sidre. * \param [in] topo topology associated with the requested mesh (optional) * * \return m pointer to a mesh instance corresponding to the specified group. * * \note If a topology name is not provided, the implementation will construct * a mesh based on the 1st topology group under the parent "topologies" * group. * * \note Ownership of the resulting mesh object is passed to the caller. * * \note When using Mint with Sidre, Sidre maintains ownership of the data. * Although the data can be modified via calls to Mint, groups and views * cannot be deleted. The data remains persistent in Sidre once the mesh * object goes out-of-scope. * * \pre group != nullptr * \pre blueprint::isValidRootGroup( group ) == true * \post m != nullptr */ Mesh* getMesh(sidre::Group* group, const std::string& topo = ""); #endif /// @} /*! * \class Mesh * * \brief Base class that defines the core API common to all Mesh types. * * A Mesh, \f$ \mathcal{M}(\Omega) \f$, provides an approximation of a physical * domain, \f$ \Omega \in \mathcal{R}^d \f$, where \f$ d \in [1,3] \f$ . The * Mesh is essentially a discrete representation of a problem and is used to * facilitate the analysis, e.g., FEA, CFD, etc. The solution domain is * approximated by dividing it into a finite number of <em> nodes </em> and * <em> cells </em> at which the variables of the underlying mathematical model * (i.e., a PDE) are then computed via a numerical method, such as, * Finite Difference (FD), Finite Volume (FV) or Finite Element (FE), chief * among them. * * There are a variety of mesh types. Mint supports the following mesh types: * * * <b> Structured (Curvilinear) Mesh </b> <br /> * * A <em> structured mesh </em> divides the solution domain according to a * logical grid where each node/cell of the mesh can be uniquely identified * by a corresponding logical ijk-index. The nodes of the mesh are found at * the intersection of the grid lines, but, are explicitly defined via a * mapping onto the physical Cartesian coordinate system of the domain. For * this reason, these types of meshes are also called <em> mapped </em> or * <em> body-fitted </em> meshes. * * However, the mesh topology (e.g., connectivity, neighbor information) is * implicitly defined by the logical indexing scheme. For example, a * structured mesh is composed of <em> quadrilateral </em> cells in 2-D and * <em> hexahedron </em> cells in 3-D. Given the logical index of a cell * one can compute the node indices of the cell and neighbor information by * performing simple shift operations on the associated index. * * * <b> Rectilinear Mesh </b> <br /> * * A <em> rectilinear mesh </em>, also known as a product mesh, is similar * to the <em> structured mesh </em> in that it is also defined according to * a logical indexing scheme and has implicit topology. * * However, the nodes and cells on a <em> rectilinear mesh </em> are arranged * on a regular lattice that is axis-aligned with the Cartesian coordinate * system. In contrast to the general <em> structured mesh </em>, the * <em> rectilinear mesh </em> does not explicitly define **all** the nodes * of the mesh. Instead, the nodes are only defined along each coordinate * axis and may have variable spacing between nodes. Given a logical index, * the corresponding physical position of a node can be evaluated by taking * the cartesian product of the corresponding coordinate along each * coordinate axis. * * * <b> Uniform Mesh </b> <br /> * * A <em> uniform mesh </em>, also called a regular mesh, subdivides the * domain in cells that have uniform spacing across each coordinate axis. * Similar to the <em> structured mesh </em>, a <em> uniform mesh </em> * adheres to the same logical indexing scheme and implicit topology * representation. Moreover, The nodes and cells of a <em> uniform </em> mesh * are arranged on a regular lattice as with the <em> rectilinear mesh </em>. * However, both topology and geometry is implicitly defined on a * <em> uniform mesh </em>. The geometry is solely defined by an origin, * \f$ \hat{x_0} \f$ and spacing, \f$ \hat{h} \f$, along each axis. The * coordinates of a node can be evaluated algebraically by the following: * \f$ \hat{p} = \hat{x_0} + \hat{i} \times \hat{h} \f$, where \f$\hat{i}\f$ * is the logical ijk-index of the corresponding node. * * * <b> Unstructured Mesh </b> <br /> * * An <em> unstructured mesh </em> stores both node and topology information * explicitly. This allows the flexibility of discretizing the solution * domain using a variety of cell types not just quadrilateral (in 2D) or * hexahedral (in 3D) cells. Due to this added flexibility, the use of * <em> unstructured meshes </em> is more common when dealing with complex * geometries. However, <em> unstructured meshes </em> require additional * storage and generally incur some performance penalty to store, create and * access mesh topology information respectively. * * Mint classifies <em> unstructured meshes </em> in two basic types based on * the underlying mesh topology: * * * <b> Single Cell Topology </b> * * In this case, the <em> unstructured mesh </em> consists of a single cell * type, e.g., a quad or triangle mesh in 2D, or, a hex or tet mesh in 3D. * In this case the underlying implementation is optimized for the * specified cell type (specified in the constructor). * * * <b> Mixed Cell Topology </b> * * When <em> mixed cell topology </em> is specified, the <em> unstructured * mesh </em> can be composed of any of the supported cell types, e.g., * a mesh consisting of both quads and triangles. This mode incurs * additional overhead for storage and access to mesh topology information, * since it requires indirection. * * The list of supported cell types for an <em> unstructured mesh </em> is * available in CellTypes.hpp * * * <b> Particle Mesh </b> <br /> * * A <em> particle mesh </em> discretizes the solution domain using * a set of discrete particle elements which correspond to the the nodes * of the mesh. There is no ordering imposed on the particles and the * coordinates of the particles are explicitly defined. A particle mesh * has no connectivity information connecting the particles, which is why * in literature methods using a particle discretization are also referred * to as <em> meshless </em> or <em> meshfree </em> methods. * * The Mesh class provides the means to create, access and remove fields on * a mesh given the field name and its association. The field association * designates the corresponding mesh entity at which the field is stored, e.g. * whether the field is stored at the nodes or cell centers. A Field may be a * scalar quantity, e.g., pressure, or a vector field, such as, velocity. * * \warning When using Sidre, field names have to be unique. For example, if * there exists a "pressure" node-centered field, there cannot be a * corresponding cell-centered field. * * \note Mesh is a base class and cannot be instantiated directly * * \note Typically, the computational mesh can be defined across one or more * <em> blocks </em>, e.g., for multi-block problems, where each block is * subsequently decomposed into several <em> partitions </em> for parallel * computation. A Mesh instance represents a <em> single </em> partition for * a given block. * * \see mint::UnstructuredMesh * \see mint::StructuredMesh * \see mint::CurvilinearMesh * \see mint::RectilinearMesh * \see mint::UniformMesh * \see mint::Field * \see mint::FieldData * \see mint::MeshTypes */ class Mesh { public: /*! * \brief Default constructor. Disabled. */ Mesh() = delete; /// \name Virtual methods /// @{ /*! * \brief Destructor. */ virtual ~Mesh(); /// \name Cells /// @{ /*! * \brief Returns the number of cells in this mesh instance. * \return N the number of cells * \post N >= 0 */ virtual IndexType getNumberOfCells() const = 0; /*! * \brief Returns the capacity for number of cell in this mesh instance. * \return N the cell capacity * \post N >= 0 */ virtual IndexType getCellCapacity() const { return getNumberOfCells(); } /*! * \brief Return the type of the given cell. * * \param [in] cellID the ID of the cell in question, this parameter is * ignored if hasMixedCellTypes() == false. * * \pre 0 <= cellID < getNumberOfCells() */ virtual CellType getCellType(IndexType cellID = 0) const = 0; /*! * \brief Return the number of nodes associated with the given cell. * * \param [in] cellID the ID of the cell in question, this parameter is * ignored unless hasMixedCellTypes() == true. * * \pre 0 <= cellID < getNumberOfCells() */ virtual IndexType getNumberOfCellNodes(IndexType cellID = 0) const = 0; /*! * \brief Copy the connectivity of the given cell into the provided buffer. * The buffer must be of length at least getNumberOfCellNodes( cellID ). * * \param [in] cellID the ID of the cell in question. * \param [out] nodes the buffer into which the connectivity is copied, must * be of length at least getNumberOfCellNodes( cellID ). * * \return The number of nodes for the given cell. * * \pre nodes != nullptr * \pre 0 <= cellID < getNumberOfCells() */ virtual IndexType getCellNodeIDs(IndexType AXOM_NOT_USED(cellID), IndexType* AXOM_NOT_USED(nodes)) const = 0; /*! * \brief Return the number of faces associated with the given cell. * * \param [in] cellID the ID of the cell in question. */ virtual IndexType getNumberOfCellFaces( IndexType AXOM_NOT_USED(cellID) = 0) const = 0; /*! * \brief Populates the given buffer with the IDs of the faces of the given * cell and returns the number of faces. * * \param [in] cellID the ID of the cellID in question. * \param [out] faces buffer to populate with the face IDs. Must be of length * at least getNumberOfCellFaces( cellID ). * * \pre faces != nullptr * \pre 0 <= cellID < getNumberOfCells() */ virtual IndexType getCellFaceIDs(IndexType AXOM_NOT_USED(cellID), IndexType* AXOM_NOT_USED(faces)) const = 0; /// @} /// \name Nodes /// @{ /*! * \brief Returns the number of nodes in this mesh instance. * \return N the number of nodes * \post N >= 0 */ virtual IndexType getNumberOfNodes() const = 0; /*! * \brief Returns the capacity for number of nodes in this mesh instance. * \return N the node capacity * \post N >= 0 */ virtual IndexType getNodeCapacity() const { return getNumberOfNodes(); } /*! * \brief Copy the coordinates of the given node into the provided buffer. * * \param [in] nodeID the ID of the node in question. * \param [in] coords the buffer to copy the coordinates into, of length at * least getDimension(). * * \pre 0 <= nodeID < getNumberOfNodes() * \pre coords != nullptr */ virtual void getNode(IndexType nodeID, double* node) const = 0; /*! * \brief Returns pointer to the requested mesh coordinate buffer. * * \param [in] dim the dimension of the requested coordinate buffer * \return ptr pointer to the coordinate buffer. * * \note if hasExplicitCoordinates() == true then the length of the returned * buffer is getNumberOfNodes(). Otherwise the UniformMesh returns * nullptr and the RectilinearMesh returns a pointer to the associated * dimension scale which is of length * static_cast< RectilinearMesh* >( this )->getNodeResolution(). * * \pre dim >= 0 && dim < dimension() * \pre dim == X_COORDINATE || dim == Y_COORDINATE || dim == Z_COORDINATE */ /// @{ virtual double* getCoordinateArray(int dim) = 0; virtual const double* getCoordinateArray(int dim) const = 0; /// @} /// @} /// \name Faces /// @{ /*! * \brief Returns the number of faces in this mesh instance. * \return N the number of faces * \post N >= 0 */ virtual IndexType getNumberOfFaces() const = 0; /*! * \brief Returns the capacity for number of faces in this mesh instance. * \return N the face capacity * \post N >= 0 */ virtual IndexType getFaceCapacity() const { return getNumberOfFaces(); } /*! * \brief Return the type of the given face. * * \param [in] faceID the ID of the face in question. */ virtual CellType getFaceType(IndexType AXOM_NOT_USED(faceID)) const = 0; /*! * \brief Return the number of nodes associated with the given face. * * \param [in] faceID the ID of the face in question. */ virtual IndexType getNumberOfFaceNodes(IndexType AXOM_NOT_USED(faceID)) const = 0; /*! * \brief Copy the IDs of the nodes that compose the given face into the * provided buffer. * * \param [in] faceID the ID of the face in question. * \param [out] nodes the buffer into which the node IDs are copied, must * be of length at least getNumberOfFaceNodes(). * * \return The number of nodes for the given face. * * \pre nodes != nullptr * \pre 0 <= faceID < getNumberOfFaces() */ virtual IndexType getFaceNodeIDs(IndexType AXOM_NOT_USED(faceID), IndexType* AXOM_NOT_USED(nodes)) const = 0; /*! * \brief Copy the IDs of the cells adjacent to the given face into the * provided indices. * * \param [in] faceID the ID of the face in question. * \param [out] cellIDOne the ID of the first cell. * \param [out] cellIDTwo the ID of the second cell. * * \note If no cell exists (the face is external) then the ID will be set to * -1. * * \pre 0 <= faceID < getNumberOfFaces() */ virtual void getFaceCellIDs(IndexType AXOM_NOT_USED(faceID), IndexType& AXOM_NOT_USED(cellIDOne), IndexType& AXOM_NOT_USED(cellIDTwo)) const = 0; /// @} /// \name Edges /// @{ /*! * \brief Returns the number of edges in this mesh instance. * \return N the number of edges * \post N >= 0 */ virtual IndexType getNumberOfEdges() const = 0; /*! * \brief Returns the capacity for number of edges in this mesh instance. * \return N the edge capacity * \post N >= 0 */ virtual IndexType getEdgeCapacity() const { return getNumberOfEdges(); } /*! * \brief Returns true iff the mesh was constructed with external arrays. * \return status true if the mesh points to external buffers, else, false. */ virtual bool isExternal() const = 0; /// @} /// @} /// \name Mesh Attribute get/set Methods /// @{ /*! * \brief Returns the dimension for this mesh instance. * \return ndims the dimension of this mesh instance. * \post ndims >= 1 && ndims <= 3 */ inline int getDimension() const { return m_ndims; } /*! * \brief Returns the ID of this mesh instance. * \return Id the ID of the mesh. */ inline int getBlockId() const { return m_block_idx; } /*! * \brief set the block ID of this mesh instance. * * \param [in] ID the new block ID. * * \post getBlockId() == ID */ void setBlockId(int ID); /*! * \brief Returns the partition ID of this mesh instance. * \return partitionId the partition ID of the mesh. */ inline int getPartitionId() const { return m_part_idx; } /*! * \brief set the partition ID of this mesh instance. * * \param [in] ID the new partition ID. * * \post getPartitionId() == ID */ void setPartitionId(int ID); /*! * \brief Returns the mesh type of this mesh instance. * \return meshType the mesh type * \see MeshType */ inline int getMeshType() const { return m_type; } /*! * \brief Checks if this mesh instance has explicit coordinates. * \return status true iff the mesh defines coordinates explicitly. */ inline bool hasExplicitCoordinates() const { return m_explicit_coords; } /*! * \brief Checks if this mesh instance has explicit connectivity. * \return status true iff the mesh defines cell connectivity explicitly. */ inline bool hasExplicitConnectivity() const { return m_explicit_connectivity; } /*! * \brief Checks if the mesh has mixed cell types, e.g., consisting of both * triangle and quad elements or hex,pyramid,prisms and tets in 3-D. * \return status true iff the mesh has mixed cell types. */ inline bool hasMixedCellTypes() const { return m_has_mixed_topology; } /*! * \brief Returns true if the mesh type is structured. * \return status true if the mesh type is structured, else, false. */ inline bool isStructured() const { return ((m_type == STRUCTURED_CURVILINEAR_MESH) || (m_type == STRUCTURED_RECTILINEAR_MESH) || (m_type == STRUCTURED_UNIFORM_MESH)); } /*! * \brief Returns true if the mesh type is unstructured. * \return status true if the mesh type is unstructured, else, false. */ inline bool isUnstructured() const { return (m_type == UNSTRUCTURED_MESH); } /*! * \brief Checks if this Mesh instance is associated with a Sidre Group. * \return status true if the Mesh is associated with a group in a Sidre * hierarchy, else, false. */ inline bool hasSidreGroup() const; #ifdef AXOM_MINT_USE_SIDRE /*! * \brief Return a pointer to the sidre::Group associated with this Mesh * instance or nullptr if none exists. */ inline sidre::Group* getSidreGroup() { return m_group; } /*! * \brief Return the name of the topology associated with this Mesh instance, * the return value is undefined if the mesh is not in sidre. */ inline const std::string& getTopologyName() const { return m_topology; } /*! * \brief Return the name of the coordset associated with this Mesh instance, * the return value is undefined if the mesh is not in sidre. */ inline const std::string& getCoordsetName() const { return m_coordset; } #endif /// @} /// \name Methods to Create, Access & Remove Fields from a Mesh /// @{ /*! * \brief Returns const pointer to the FieldData instance with the specified * mesh field association, e.g., NODE_CENTERED, CELL_CENTERED, etc. * * \param [in] association the specified mesh field association * \return fd pointer to the requested FieldData instance * * \pre association >= 0 && association < NUM_FIELD_ASSOCIATION * \post fd != nullptr * * \see FieldAssociation * \see FieldData */ inline const FieldData* getFieldData(int association) const; /*! * \brief Check if a field with the given name and association exists. * * \param [in] name the name of the field in query. * \param [in] association the field association (optional) * * \return status true if the field exists, else, false. * * \note If an association is not explicitly specified, the code will check * if a field by the given name exists in any available centeering. * * \pre name.empty()==false * \pre association >= 0 && association < NUM_FIELD_ASSOCIATION * * \see FieldAssociation */ inline bool hasField(const std::string& name, int association = ANY_CENTERING) const; /*! * \brief Creates a new field with the given name and specified mesh field * association, e.g., NODE_CENTERED, CELL_CENTERED, etc. * * \param [in] name the name of the new field. * \param [in] association the mesh field association. * \param [in] num_components number of components of the field (optional). * \param [in] storeInSidre indicates whether to store the field in the * corresponding Sidre group (optional). * \param [in] capacity * * \return ptr raw pointer to the data buffer of the new field. * * \note This method throws an error and aborts if any of the pre-conditions * is not satisfied. * * \pre name.empty() == false * \pre hasField( name ) == false * \pre association >= 0 && association < NUM_FIELD_ASSOCIATION * * \post ptr != nullptr * \post hasField( name ) == true * * \see FieldAssociation */ template <typename T> inline T* createField(const std::string& name, int association, IndexType num_components = 1, bool storeInSidre = true); /*! * \brief Creates a new field from an external buffer that has the given name * and specified mesh field association, e.g., NODE_CENTERED, CELL_CENTERED, * etc. * * \param [in] name the name of the new field. * \param [in] association the mesh field association. * \param [in] data pointer to the external data buffer. * \param [in] num_components number of components of the field (optional). * * \return ptr raw pointer to the data buffer of the new field. * * \note This method throws an error and aborts if any of the pre-conditions * is not satisfied. * * \pre name.empty() == false * \pre hasField( name ) == false * \pre data != nullptr * \pre association >= 0 && association < NUM_FIELD_ASSOCIATION * * \post ptr != nullptr * \post ptr == data * \post hasField( name ) == true * * \see FieldAssociation */ template <typename T> inline T* createField(const std::string& name, int association, T* data, IndexType num_components = 1, IndexType capacity = USE_DEFAULT); /*! * \brief Removes the field with the given name and specified association. * * \param [in] name the name of the field to remove. * \param [in] association the mesh field association. * * \return status true if the field is removed successfully, else, false. * * \pre name.emtpy() == false * \pre association >= 0 && association < NUM_FIELD_ASSOCIATION * * \see FieldAssociation */ inline bool removeField(const std::string& name, int association); /*! * \brief Returns pointer to buffer of the field with the given ane and * specified mesh field association. * * \param [in] name the name of the requested field. * \param [in] association the mesh field association. * \param [out] num_components the number of components per tuple (optional). * * \return ptr raw pointer to the data buffer of the requested field. * * \pre name.empty() == false * \pre hasField( name ) * \pre association >= 0 && association < NUM_FIELD_ASSOCIATION * * \see FieldAssociation */ /// @{ template <typename T> inline T* getFieldPtr(const std::string& name, int association, IndexType& num_components); template <typename T> inline T* getFieldPtr(const std::string& name, int association); template <typename T> inline const T* getFieldPtr(const std::string& name, int association, IndexType& num_components) const; template <typename T> inline const T* getFieldPtr(const std::string& name, int association) const; /// @} /// @} protected: /// \name Protected Members /// @{ int m_ndims; /*! mesh dimension */ int m_type; /*! the type of the mesh */ int m_block_idx; /*! the Block ID of the mesh */ int m_part_idx; /*! the partition ID of the mesh */ bool m_explicit_coords; bool m_explicit_connectivity; bool m_has_mixed_topology; FieldData* m_mesh_fields[NUM_FIELD_ASSOCIATIONS]; #ifdef AXOM_MINT_USE_SIDRE sidre::Group* m_group; std::string m_topology; std::string m_coordset; #endif /// @} /// \name Protected Constructors (used in derived classes ) /// @{ /*! * \brief Mesh Constructor. * * \param [in] ndims the number of dimensions * \param [in] type the mesh type. * \param [in] blockId the block ID for this mesh instance. * \param [in] partId the partition ID for this mesh instance. */ Mesh(int ndims, int type); #ifdef AXOM_MINT_USE_SIDRE /*! * \brief Constructor for use with a group that already has data. * * \param [in] group the sidre::Group to use. * \param [in] topo optional argument specifying the name of the topology * associated with this Mesh instance. * * \note If a topology name is not provided, the implementation will construct * a mesh based on the 1st topology group under the parent "topologies" * group. * * \pre group != nullptr. * \pre blueprint::isValidRootGroup( group ) == true * * \see sidre::Group */ Mesh(sidre::Group* group, const std::string& topo = ""); /*! * \brief Constructor for use with an empty group. * * \param [in] ndims the number of dimensions * \param [in] type the mesh type. * \param [in] group the sidre::Group to use. * \param [in] topo the name of the associated topology group. * \param [in] coordset the name of the associated coordset group. * * \note If a topology and coordset name is not provided a default name is * used by the implementation. * * \pre group != nullptr. * \pre group->getNumGroups() == 0 * \pre group->getNumViews() == 0 * \post blueprint::isValidRootGroup( group ) * * \see sidre::Group */ Mesh(int ndims, int type, sidre::Group* group, const std::string& topo, const std::string& coordset); /*! * \brief Helper method to return the associated coordset group. * \return coordset the associated coordset group. * * \pre m_group != nullptr * \pre blueprint::isValidRootGroup( m_group ) * \post blueprint::isValidCoordsetGroup( coordset ) */ sidre::Group* getCoordsetGroup(); /*! * \brief Helper method to return the associated topology group. * \return topology the associated topology group. * * \pre m_group != nullptr * \pre blueprint::isValidRootGroup( m_group ) * \post blueprint::isValidTopologyGroup( topology ) */ sidre::Group* getTopologyGroup(); #endif /// @} private: /*! * \brief Get the info corresponding to the given mesh field association. * * \param [in] association the mesh field association, e.g., NODE_CENTERED. * \param [out] num_tuples the number of tuples in the associated FieldData. * \param [out] capacity the capacity of the associated FieldData. */ void getFieldInfo(int association, IndexType& num_tuples, IndexType& capacity) const; /*! * \brief Helper method to check if the mesh type is valid. * \return status true if the mesh type is valie, else, false. */ inline bool validMeshType() const { return ((m_type >= 0) && (m_type < mint::NUM_MESH_TYPES)); } /*! * \brief Helper method to check if the mesh dimension is valid. * \return status true if the mesh dimension is valid, else, false. */ inline bool validDimension() const { return (m_ndims >= 1 && m_ndims <= 3); } /*! * \brief Allocates the FieldData internal data-structures. * \note Helper method that is called from the constructor. */ void allocateFieldData(); /*! * \brief Deallocates the FieldData internal data-structures. * \note Helper method that is called by the destructor. */ void deallocateFieldData(); DISABLE_COPY_AND_ASSIGNMENT(Mesh); DISABLE_MOVE_AND_ASSIGNMENT(Mesh); }; //------------------------------------------------------------------------------ // IMPLEMENTATION OF TEMPLATE & IN-LINE METHODS //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ inline bool Mesh::hasSidreGroup() const { #ifdef AXOM_MINT_USE_SIDRE return (m_group != nullptr); #else return false; #endif } //------------------------------------------------------------------------------ inline const FieldData* Mesh::getFieldData(int association) const { SLIC_ERROR_IF(association < 0 || association >= NUM_FIELD_ASSOCIATIONS, "invalid field association [" << association << "]"); SLIC_ERROR_IF(m_mesh_fields[association] == nullptr, "null field data object w/association [" << association << "]"); SLIC_ERROR_IF(m_type == PARTICLE_MESH && association != NODE_CENTERED, "a particle mesh may only store node-centered fields"); return m_mesh_fields[association]; } //------------------------------------------------------------------------------ inline bool Mesh::hasField(const std::string& name, int association) const { bool found = false; if(association == mint::ANY_CENTERING) { int N = (m_type == mint::PARTICLE_MESH) ? 1 : mint::NUM_FIELD_ASSOCIATIONS; for(int i = 0; !found && i < N; ++i) { const FieldData* fd = getFieldData(i); SLIC_ASSERT(fd != nullptr); found = fd->hasField(name); } } else { const FieldData* fd = getFieldData(association); SLIC_ASSERT(fd != nullptr); found = fd->hasField(name); } return (found); } //------------------------------------------------------------------------------ template <typename T> inline T* Mesh::createField(const std::string& name, int association, IndexType num_components, bool storeInSidre) { SLIC_ERROR_IF(hasField(name), "a field with the same name already exists!"); FieldData* fd = const_cast<FieldData*>(getFieldData(association)); SLIC_ASSERT(fd != nullptr); IndexType num_tuples, capacity; getFieldInfo(association, num_tuples, capacity); T* ptr = fd->createField<T>(name, num_tuples, num_components, capacity, storeInSidre); if(num_tuples > 0) { SLIC_ASSERT(ptr != nullptr); } return (ptr); } //------------------------------------------------------------------------------ template <typename T> inline T* Mesh::createField(const std::string& name, int association, T* data, IndexType num_components, IndexType capacity) { SLIC_ERROR_IF(hasField(name), "a field with the same name already exists!"); SLIC_ASSERT(data != nullptr); FieldData* fd = const_cast<FieldData*>(getFieldData(association)); SLIC_ASSERT(fd != nullptr); IndexType num_tuples, dummy1; getFieldInfo(association, num_tuples, dummy1); T* ptr = fd->createField<T>(name, data, num_tuples, num_components, capacity); SLIC_ASSERT(ptr == data); return (ptr); } //------------------------------------------------------------------------------ inline bool Mesh::removeField(const std::string& name, int association) { bool status = false; FieldData* fd = const_cast<FieldData*>(getFieldData(association)); const bool hasField = fd->hasField(name); SLIC_WARNING_IF(!hasField, "field [" << name << "] does not exist!"); if(hasField) { fd->removeField(name); status = true; } return (status); } //------------------------------------------------------------------------------ template <typename T> inline T* Mesh::getFieldPtr(const std::string& name, int association) { IndexType num_components = 0; return getFieldPtr<T>(name, association, num_components); } //------------------------------------------------------------------------------ template <typename T> inline T* Mesh::getFieldPtr(const std::string& name, int association, IndexType& num_components) { const Mesh* self = const_cast<const Mesh*>(this); const T* ptr = self->getFieldPtr<T>(name, association, num_components); return (const_cast<T*>(ptr)); } //------------------------------------------------------------------------------ template <typename T> inline const T* Mesh::getFieldPtr(const std::string& name, int association) const { IndexType num_components = 0; return getFieldPtr<T>(name, association, num_components); } //------------------------------------------------------------------------------ template <typename T> inline const T* Mesh::getFieldPtr(const std::string& name, int association, IndexType& num_components) const { const FieldData* fd = getFieldData(association); SLIC_ASSERT(fd != nullptr); IndexType num_tuples = 0; const T* ptr = fd->getFieldPtr<T>(name, num_tuples, num_components); SLIC_ASSERT(ptr != nullptr); return (ptr); } //------------------------------------------------------------------------------ inline void Mesh::getFieldInfo(int association, IndexType& num_tuples, IndexType& capacity) const { switch(association) { case NODE_CENTERED: num_tuples = getNumberOfNodes(); capacity = getNodeCapacity(); break; case CELL_CENTERED: num_tuples = getNumberOfCells(); capacity = getCellCapacity(); break; case FACE_CENTERED: num_tuples = getNumberOfFaces(); capacity = getFaceCapacity(); break; default: SLIC_ASSERT(association == EDGE_CENTERED); num_tuples = getNumberOfEdges(); capacity = getEdgeCapacity(); break; } // END switch } } /* namespace mint */ } /* namespace axom */ #endif /* MINT_MESH_HPP_ */
33.264565
84
0.639572
raineyeh
e17e3faa41d042f1f26d0d48a9cc7d51f7080dd5
12,100
cc
C++
mindspore/lite/tools/converter/legacy_optimizer/graph/batchnorm_convert_scale_pass.cc
GuoSuiming/mindspore
48afc4cfa53d970c0b20eedfb46e039db2a133d5
[ "Apache-2.0" ]
1
2021-01-28T11:08:20.000Z
2021-01-28T11:08:20.000Z
mindspore/lite/tools/converter/legacy_optimizer/graph/batchnorm_convert_scale_pass.cc
GuoSuiming/mindspore
48afc4cfa53d970c0b20eedfb46e039db2a133d5
[ "Apache-2.0" ]
null
null
null
mindspore/lite/tools/converter/legacy_optimizer/graph/batchnorm_convert_scale_pass.cc
GuoSuiming/mindspore
48afc4cfa53d970c0b20eedfb46e039db2a133d5
[ "Apache-2.0" ]
null
null
null
/** * Copyright 2020 Huawei Technologies Co., Ltd * * 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 "tools/converter/legacy_optimizer/graph/batchnorm_convert_scale_pass.h" #include <memory> #include <string> #include <utility> #include <vector> #include "tools/converter/converter_flags.h" #include "third_party/securec/include/securec.h" #include "src/common/log_adapter.h" #include "src/common/common.h" #include "tools/common/tensor_util.h" #include "include/errorcode.h" #include "schema/inner/model_generated.h" namespace mindspore { namespace lite { #define CAFFE_BATCHNORM_MEAN_INDEX 0 #define CAFFE_BATCHNORM_VARIANCE_INDEX 1 #define CAFFE_BATCHNORM_SCALE_INDEX 2 #define TF_BATCHNORM_SCALE_INDEX 0 #define TF_BATCHNORM_BIAS_INDEX 1 #define TF_BATCHNORM_MEAN_INDEX 2 #define TF_BATCHNORM_VARIANCE_INDEX 3 namespace { constexpr const float EPS = 1e-8; constexpr const float EPS_DEFAULT_FLOAT = 1e-8; constexpr const float POW_NUM = 0.5; } // namespace STATUS BatchNormConvertScalePass::Run(MetaGraphT *graph) { MS_ASSERT(graph != nullptr); for (auto iter = graph->nodes.begin(); iter != graph->nodes.end(); iter++) { auto &node = *iter; auto type = node->primitive->value.type; if (type != schema::PrimitiveType_FusedBatchNorm && type != schema::PrimitiveType_BatchNorm) { continue; } auto status = GenNewScaleTensor(graph, node); if (status != RET_OK) { MS_LOG(ERROR) << "GenNewScaleTensor failed: " << status; return status; } status = ConvertBNToScale(graph, node); if (status != RET_OK) { MS_LOG(ERROR) << "GenNewScaleTensor failed: " << status; return status; } } return RET_OK; } STATUS BatchNormConvertScalePass::ConvertBNToScale(MetaGraphT *graph, const std::unique_ptr<CNodeT> &bnNode) { MS_ASSERT(graph != nullptr); MS_ASSERT(bnNode != nullptr); bnNode->primitive->value.type = schema::PrimitiveType_Scale; std::unique_ptr<ScaleT> scaleParam(new (std::nothrow) ScaleT()); if (scaleParam == nullptr) { MS_LOG(ERROR) << "new scaleParam failed"; return RET_ERROR; } int32_t axis = (graph->allTensors.at(bnNode->inputIndex.at(1))->format == Format_NHWC) ? (int32_t)NHWC_C : (int32_t)NCHW_C; scaleParam->axis = axis; bnNode->primitive->value.value = scaleParam.release(); auto input0 = bnNode->inputIndex.at(0); bnNode->inputIndex.clear(); bnNode->inputIndex.push_back(input0); graph->allTensors.emplace_back(std::move(newScaleWeightTensor)); auto weightTensorIdx = graph->allTensors.size() - 1; graph->allTensors.emplace_back(std::move(newScaleBiasTensor)); auto biasTensorIdx = graph->allTensors.size() - 1; bnNode->inputIndex.push_back(weightTensorIdx); bnNode->inputIndex.push_back(biasTensorIdx); return RET_OK; } STATUS BatchNormConvertScalePass::GenNewScaleTensor(MetaGraphT *graph, const std::unique_ptr<CNodeT> &bnNode) { MS_ASSERT(graph != nullptr); MS_ASSERT(bnNode != nullptr); GetTransParam(graph, bnNode); newScaleWeightTensor = std::unique_ptr<TensorT>(new (std::nothrow) TensorT); if (newScaleWeightTensor == nullptr) { MS_LOG(ERROR) << "new weightTensor failed"; return RET_ERROR; } newScaleWeightTensor->dataType = bnMeanTensor->dataType; newScaleWeightTensor->format = bnMeanTensor->format; newScaleWeightTensor->refCount = schema::NodeType::NodeType_ValueNode; newScaleWeightTensor->dims = bnMeanTensor->dims; auto weightShapeSize = GetShapeSize(*bnMeanTensor); newScaleWeightTensor->data.resize(weightShapeSize * sizeof(float)); auto ret = memcpy_s(newScaleWeightTensor->data.data(), weightShapeSize * sizeof(float), transScale, weightShapeSize * sizeof(float)); if (ret != EOK) { MS_LOG(ERROR) << "memcpy error: " << ret; delete[] transScale; delete[] transBias; transScale = nullptr; transBias = nullptr; return RET_ERROR; } newScaleBiasTensor = std::unique_ptr<TensorT>(new (std::nothrow) TensorT); if (newScaleBiasTensor == nullptr) { MS_LOG(ERROR) << "new weightTensor failed"; return RET_ERROR; } newScaleBiasTensor->dataType = bnMeanTensor->dataType; newScaleBiasTensor->format = bnMeanTensor->format; newScaleBiasTensor->refCount = schema::NodeType::NodeType_ValueNode; newScaleBiasTensor->dims = bnMeanTensor->dims; weightShapeSize = GetShapeSize(*bnMeanTensor); newScaleBiasTensor->data.resize(weightShapeSize * sizeof(float)); ret = memcpy_s(newScaleBiasTensor->data.data(), weightShapeSize * sizeof(float), transBias, weightShapeSize * sizeof(float)); if (ret != EOK) { MS_LOG(ERROR) << "memcpy error: " << ret; delete[] transScale; delete[] transBias; transScale = nullptr; transBias = nullptr; return RET_ERROR; } delete[] transScale; delete[] transBias; transScale = nullptr; transBias = nullptr; return RET_OK; } STATUS BatchNormConvertScalePass::GetTransParam(MetaGraphT *graph, const std::unique_ptr<CNodeT> &bnNode) { MS_ASSERT(graph != nullptr); MS_ASSERT(bnNode != nullptr); BNWeightTensors bnWeightTensors; auto status = GetBnWeightTensors(graph, &bnWeightTensors, bnNode); if (status != RET_OK) { MS_LOG(ERROR) << "GetBnWeightTensors error"; return status; } auto *meanTensor = bnWeightTensors.meanTensor; auto *varianceTensor = bnWeightTensors.varianceTensor; auto *scaleTensor = bnWeightTensors.scaleTensor; auto *biasTensor = bnWeightTensors.biasTensor; auto *meanData = reinterpret_cast<float *>(meanTensor->data.data()); auto *varianceData = reinterpret_cast<float *>(varianceTensor->data.data()); eps = EPS_DEFAULT_FLOAT; status = GetBnEpsilon(bnNode); if (status != RET_OK) { MS_LOG(ERROR) << "GetBnEpsilon failed"; return status; } this->transScale = new (std::nothrow) float[bnChannel]; if (this->transScale == nullptr) { MS_LOG(ERROR) << "new transScale failed"; return RET_ERROR; } this->transBias = new (std::nothrow) float[bnChannel]; if (this->transBias == nullptr) { MS_LOG(ERROR) << "new transBias failed"; return RET_ERROR; } // cal transScale, tf : scale/sqrt(variance + eps); caffe : 1/sqrt(variance + eps) if (memcpy_s(transScale, bnChannel * sizeof(float), varianceData, bnChannel * sizeof(float)) != EOK) { MS_LOG(ERROR) << "memcpy_s transScale error"; delete[] transScale; delete[] transBias; transScale = nullptr; transBias = nullptr; return RET_ERROR; } // 1/sqrt(variance + eps) for (uint32_t i = 0; i < bnChannel; i++) { float tmp = transScale[i] + eps; tmp = pow(tmp, POW_NUM); if (tmp <= 0.0f) { MS_LOG(ERROR) << "divisor 'tmp' cannot be 0"; return RET_ERROR; } transScale[i] = 1 / tmp; } if (scaleTensor != nullptr) { auto *scaleData = reinterpret_cast<float *>(scaleTensor->data.data()); // scale/sqrt(variance + eps) for (uint32_t i = 0; i < bnChannel; i++) { transScale[i] *= scaleData[i]; } } // cal transBias, tf : -scale*mean/sqrt(variance + eps) + bias; caffe : -mean/sqrt(variance + eps) // -mean/sqrt(variance + eps) for (uint32_t i = 0; i < bnChannel; i++) { transBias[i] = -meanData[i] * transScale[i]; } if (biasTensor != nullptr) { auto *biasData = reinterpret_cast<float *>(biasTensor->data.data()); // -scale*mean/sqrt(variance + eps) + bias for (uint32_t i = 0; i < bnChannel; i++) { transBias[i] += biasData[i]; } } return RET_OK; } // BatchNorm weight Tensor definition: // caffe // estimated_mean --0 // estimated_variance --1 // tensorflow // scale -- 0 // bias --1 // estimated_mean --2 // estimated_variance --3 STATUS BatchNormConvertScalePass::GetBnWeightTensors(MetaGraphT *graph, BNWeightTensors *bnWeightTensors, const std::unique_ptr<CNodeT> &bnNode) { MS_ASSERT(graph != nullptr); MS_ASSERT(bnNode != nullptr); MS_ASSERT(bnWeightTensors != nullptr); MS_ASSERT(graph->allTensors.size() > bnNode->inputIndex.at(1)); auto bnWeightTensorIdxes = bnNode->inputIndex; bnWeightTensorIdxes.erase(bnWeightTensorIdxes.begin()); if (fmkType == converter::FmkType_CAFFE) { bnWeightTensors->meanTensor = graph->allTensors.at(bnWeightTensorIdxes[CAFFE_BATCHNORM_MEAN_INDEX]).get(); bnWeightTensors->varianceTensor = graph->allTensors.at(bnWeightTensorIdxes[CAFFE_BATCHNORM_VARIANCE_INDEX]).get(); auto scaleTensor = graph->allTensors.at(bnWeightTensorIdxes[CAFFE_BATCHNORM_SCALE_INDEX]).get(); // calibrate mean and variance float scale_factor_data = (reinterpret_cast<float *>(scaleTensor->data.data()))[0]; float scale_factor = scale_factor_data == 0 ? 0 : 1 / scale_factor_data; auto mean_data = reinterpret_cast<float *>(bnWeightTensors->meanTensor->data.data()); auto variance_data = reinterpret_cast<float *>(bnWeightTensors->varianceTensor->data.data()); for (size_t i = 0; i < GetShapeSize(*bnWeightTensors->meanTensor); i++) { mean_data[i] *= scale_factor; } for (size_t i = 0; i < GetShapeSize(*bnWeightTensors->varianceTensor); i++) { variance_data[i] *= scale_factor; } } else { bnWeightTensors->scaleTensor = graph->allTensors.at(bnWeightTensorIdxes[TF_BATCHNORM_SCALE_INDEX]).get(); bnWeightTensors->biasTensor = graph->allTensors.at(bnWeightTensorIdxes[TF_BATCHNORM_BIAS_INDEX]).get(); bnWeightTensors->meanTensor = graph->allTensors.at(bnWeightTensorIdxes[TF_BATCHNORM_MEAN_INDEX]).get(); bnWeightTensors->varianceTensor = graph->allTensors.at(bnWeightTensorIdxes[TF_BATCHNORM_VARIANCE_INDEX]).get(); } if (bnWeightTensors->meanTensor == nullptr) { MS_LOG(ERROR) << "BatchNorm's mean tensor is nullptr"; return RET_ERROR; } if (bnWeightTensors->varianceTensor == nullptr) { MS_LOG(ERROR) << "BatchNorm's variance tensor is nullptr"; return RET_ERROR; } bnChannel = bnWeightTensors->meanTensor->data.size() * sizeof(uint8_t) / sizeof(float); if (bnChannel <= 0) { MS_LOG(ERROR) << "BatchNorm's channel less or equal 0"; return RET_ERROR; } bnMeanTensor = bnWeightTensors->meanTensor; if (bnChannel != bnWeightTensors->varianceTensor->data.size() * sizeof(uint8_t) / sizeof(float)) { MS_LOG(ERROR) << "conv kernel num expected to be equal to variance size"; return RET_ERROR; } if (bnWeightTensors->scaleTensor != nullptr) { if (bnChannel != bnWeightTensors->scaleTensor->data.size() * sizeof(uint8_t) / sizeof(float)) { MS_LOG(ERROR) << "conv kernel num expected to be equal to scale size"; return RET_ERROR; } } if (bnWeightTensors->biasTensor != nullptr) { if (bnChannel != bnWeightTensors->biasTensor->data.size() * sizeof(uint8_t) / sizeof(float)) { MS_LOG(ERROR) << "conv kernel num expected to be equal to bias size"; return RET_ERROR; } } return RET_OK; } STATUS BatchNormConvertScalePass::GetBnEpsilon(const std::unique_ptr<CNodeT> &bnNode) { MS_ASSERT(graph != nullptr); MS_ASSERT(bnNode != nullptr); MS_ASSERT(bnNode->primitive != nullptr); if (bnNode->primitive->value.type == schema::PrimitiveType_FusedBatchNorm) { eps = bnNode->primitive->value.AsFusedBatchNorm()->epsilon; } else if (bnNode->primitive->value.type == schema::PrimitiveType_BatchNorm) { eps = bnNode->primitive->value.AsBatchNorm()->epsilon; } else { MS_LOG(ERROR) << "match pattern has error, not BatchNorm node"; return RET_ERROR; } if (eps < EPS) { eps = EPS_DEFAULT_FLOAT; } return RET_OK; } } // namespace lite } // namespace mindspore
37.694704
118
0.701653
GuoSuiming
e17f54e851cc7fe3538352f5a120229fd2f5b7fc
3,690
cpp
C++
src/condor_contrib/aviary/src/AviaryProviderFactory.cpp
bbockelm/condor-network-accounting
f0f41854fd418adaf24f430adf5217e514a044db
[ "Apache-2.0" ]
null
null
null
src/condor_contrib/aviary/src/AviaryProviderFactory.cpp
bbockelm/condor-network-accounting
f0f41854fd418adaf24f430adf5217e514a044db
[ "Apache-2.0" ]
null
null
null
src/condor_contrib/aviary/src/AviaryProviderFactory.cpp
bbockelm/condor-network-accounting
f0f41854fd418adaf24f430adf5217e514a044db
[ "Apache-2.0" ]
1
2021-08-29T14:03:03.000Z
2021-08-29T14:03:03.000Z
/*************************************************************** * * Copyright (C) 2009-2011 Red Hat, Inc. * * 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 "AviaryProvider.h" #include "EndpointPublisher.h" #include "Axis2SoapProvider.h" #include "Axis2SslProvider.h" #include "AviaryUtils.h" using namespace std; using namespace aviary; using namespace aviary::transport; using namespace aviary::soap; using namespace aviary::util; using namespace aviary::locator; AviaryProvider* AviaryProviderFactory::create(const string& log_file, const string& service_name, const string& major_type, const string& minor_type, const string& uri_suffix) { AviaryProvider* provider = NULL; string repo_path; int port; string axis_error; char *tmp = NULL; EndpointPublisher* ep = NULL; // config then env for our all-important axis2 repo dir if ((tmp = param("WSFCPP_HOME"))) { repo_path = tmp; free(tmp); } else if ((tmp = getenv("WSFCPP_HOME"))) { repo_path = tmp; } else { dprintf(D_ALWAYS,"No WSFCPP_HOME in config or env\n"); return NULL; } int level = getLogLevel(); int read_timeout = param_integer("AXIS2_READ_TIMEOUT",AXIS2_HTTP_DEFAULT_SO_TIMEOUT); // which flavor of transport bool have_ssl = param_boolean("AVIARY_SSL",FALSE); if (!have_ssl) { port = param_integer("HTTP_PORT",9000); } else { port = param_integer("HTTP_PORT",9443); } // see if we are using locator to publish our endpoint bool use_locator = param_boolean("AVIARY_PUBLISH_LOCATION",FALSE) && minor_type != LOCATOR; if (use_locator) { ep = new EndpointPublisher(service_name, major_type, minor_type); if (!ep->init(uri_suffix,have_ssl)) { dprintf(D_ALWAYS,"Aviary location endpoint config failed\n"); return NULL; } port = ep->getPort(); } if (!have_ssl) { Axis2SoapProvider* http = new Axis2SoapProvider(level,log_file.c_str(),repo_path.c_str()); if (!http->init(port,read_timeout,axis_error)) { dprintf(D_ALWAYS,"Axis2 HTTP configuration failed, check possible conflict on port %d\n",port); delete http; return NULL; } dprintf(D_ALWAYS,"UNSECURE Axis2 HTTP listener activated on port %d\n",port); provider = http; } #ifdef HAVE_EXT_OPENSSL else { Axis2SslProvider* https = new Axis2SslProvider(level,log_file.c_str(),repo_path.c_str()); if (!https->init(port,read_timeout,axis_error)) { dprintf(D_ALWAYS,"SSL/TLS requested but configuration failed\n"); dprintf(D_ALWAYS,"Check SSL config paths and possible conflict on port %d\n",port); delete https; return NULL; } dprintf(D_ALWAYS,"Axis2 HTTPS listener activated on port %d\n",port); provider = https; } #endif // ready to publish our endpoint if (ep) { // provider owns this now provider->setPublisher(ep); ep->start(param_integer("AVIARY_PUBLISH_INTERVAL", 10)); } return provider; }
32.368421
107
0.648509
bbockelm
e18342bcebf327def64cb9a88aa04b7e893c2857
2,200
cc
C++
src/atlas/grid/detail/spacing/gaussian/N80.cc
wdeconinck/atlas
8949d2b362b9b5431023a967bcf4ca84f6b8ce05
[ "Apache-2.0" ]
3
2021-08-17T03:08:45.000Z
2021-09-09T09:22:54.000Z
src/atlas/grid/detail/spacing/gaussian/N80.cc
pmarguinaud/atlas
7e0a1251685e07a5dcccc84f4d9251d5a066e2ee
[ "Apache-2.0" ]
62
2020-10-21T15:27:38.000Z
2022-03-28T12:42:43.000Z
src/atlas/grid/detail/spacing/gaussian/N80.cc
pmarguinaud/atlas
7e0a1251685e07a5dcccc84f4d9251d5a066e2ee
[ "Apache-2.0" ]
1
2021-03-10T19:19:08.000Z
2021-03-10T19:19:08.000Z
/* * (C) Copyright 2013 ECMWF. * * This software is licensed under the terms of the Apache Licence Version 2.0 * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. * In applying this licence, ECMWF does not waive the privileges and immunities * granted to it by virtue of its status as an intergovernmental organisation * nor does it submit to any jurisdiction. */ // TL159 #include "atlas/grid/detail/spacing/gaussian/N.h" namespace atlas { namespace grid { namespace spacing { namespace gaussian { DEFINE_GAUSSIAN_LATITUDES( 80, LIST( 89.141519426461, 88.029428867952, 86.910770814124, 85.790628883637, 84.669924084447, 83.548946912542, 82.427817524008, 81.306594522669, 80.185309872477, 79.063982481409, 77.942624246673, 76.821243027100, 75.699844222011, 74.578431663296, 73.457008145583, 72.335575754909, 71.214136079887, 70.092690351624, 68.971239538936, 67.849784414670, 66.728325602882, 65.606863613010, 64.485398865043, 63.363931708341, 62.242462435891, 61.120991295252, 59.999518497040, 58.878044221583, 57.756568624184, 56.635091839330, 55.513613984077, 54.392135160792, 53.270655459398, 52.149174959220, 51.027693730509, 49.906211835711, 48.784729330535, 47.663246264843, 46.541762683406, 45.420278626548, 44.298794130694, 43.177309228835, 42.055823950935, 40.934338324279, 39.812852373771, 38.691366122202, 37.569879590471, 36.448392797794, 35.326905761872, 34.205418499049, 33.083931024447, 31.962443352088, 30.840955495002, 29.719467465319, 28.597979274357, 27.476490932696, 26.355002450251, 25.233513836324, 24.112025099671, 22.990536248541, 21.869047290730, 20.747558233616, 19.626069084199, 18.504579849136, 17.383090534771, 16.261601147162, 15.140111692111, 14.018622175186, 12.897132601745, 11.775642976956, 10.654153305818, 9.532663593176, 8.411173843743, 7.289684062115, 6.168194252784, 5.046704420157, 3.925214568566, 2.803724702287, 1.682234825547, 0.560744942544 ) ) } // namespace gaussian } // namespace spacing } // namespace grid } // namespace atlas
55
115
0.726818
wdeconinck
e184190113e5855db318513c6add2d7386339f9d
34,893
cpp
C++
Source/Macad.Occt/Generated/Adaptor2d.cpp
zhyifei/Macad3D
55d92a7de53a1fc8f4453c09b162c261a40586f0
[ "MIT" ]
107
2020-11-29T18:01:50.000Z
2022-03-31T13:54:40.000Z
Source/Macad.Occt/Generated/Adaptor2d.cpp
zhyifei/Macad3D
55d92a7de53a1fc8f4453c09b162c261a40586f0
[ "MIT" ]
10
2021-03-12T18:34:24.000Z
2022-01-08T21:03:58.000Z
Source/Macad.Occt/Generated/Adaptor2d.cpp
zhyifei/Macad3D
55d92a7de53a1fc8f4453c09b162c261a40586f0
[ "MIT" ]
42
2021-01-07T06:23:24.000Z
2022-03-29T10:03:51.000Z
// Generated wrapper code for package Adaptor2d #include "OcctPCH.h" #include "Adaptor2d.h" using namespace System::Runtime::InteropServices; // for class Marshal #include "Adaptor2d.h" #include "Geom2dAdaptor.h" #include "ProjLib.h" #include "BRepAdaptor.h" #include "Standard.h" #include "GeomAbs.h" #include "TColStd.h" #include "gp.h" #include "Geom2d.h" //--------------------------------------------------------------------- // Class Adaptor2d_HCurve2d //--------------------------------------------------------------------- Macad::Occt::Adaptor2d_HCurve2d::Adaptor2d_HCurve2d(Macad::Occt::Adaptor2d_HCurve2d^ parameter1) : Macad::Occt::Standard_Transient(BaseClass::InitMode::Uninitialized) { throw gcnew System::NotImplementedException("Native class is abstract"); } Macad::Occt::Adaptor2d_HCurve2d::Adaptor2d_HCurve2d() : Macad::Occt::Standard_Transient(BaseClass::InitMode::Uninitialized) { throw gcnew System::NotImplementedException("Native class is abstract"); } Macad::Occt::Adaptor2d_Curve2d^ Macad::Occt::Adaptor2d_HCurve2d::Curve2d() { ::Adaptor2d_Curve2d* _result = new ::Adaptor2d_Curve2d(); *_result = (::Adaptor2d_Curve2d)((::Adaptor2d_HCurve2d*)_NativeInstance)->Curve2d(); return _result==nullptr ? nullptr : gcnew Macad::Occt::Adaptor2d_Curve2d(_result); } double Macad::Occt::Adaptor2d_HCurve2d::FirstParameter() { return ((::Adaptor2d_HCurve2d*)_NativeInstance)->FirstParameter(); } double Macad::Occt::Adaptor2d_HCurve2d::LastParameter() { return ((::Adaptor2d_HCurve2d*)_NativeInstance)->LastParameter(); } Macad::Occt::GeomAbs_Shape Macad::Occt::Adaptor2d_HCurve2d::Continuity() { return (Macad::Occt::GeomAbs_Shape)((::Adaptor2d_HCurve2d*)_NativeInstance)->Continuity(); } int Macad::Occt::Adaptor2d_HCurve2d::NbIntervals(Macad::Occt::GeomAbs_Shape S) { return ((::Adaptor2d_HCurve2d*)_NativeInstance)->NbIntervals((::GeomAbs_Shape)S); } void Macad::Occt::Adaptor2d_HCurve2d::Intervals(Macad::Occt::TColStd_Array1OfReal^ T, Macad::Occt::GeomAbs_Shape S) { ((::Adaptor2d_HCurve2d*)_NativeInstance)->Intervals(*(::TColStd_Array1OfReal*)T->NativeInstance, (::GeomAbs_Shape)S); } Macad::Occt::Adaptor2d_HCurve2d^ Macad::Occt::Adaptor2d_HCurve2d::Trim(double First, double Last, double Tol) { Handle(::Adaptor2d_HCurve2d) _result; _result = ((::Adaptor2d_HCurve2d*)_NativeInstance)->Trim(First, Last, Tol); return _result.IsNull() ? nullptr : Macad::Occt::Adaptor2d_HCurve2d::CreateDowncasted( _result.get()); } bool Macad::Occt::Adaptor2d_HCurve2d::IsClosed() { return ((::Adaptor2d_HCurve2d*)_NativeInstance)->IsClosed(); } bool Macad::Occt::Adaptor2d_HCurve2d::IsPeriodic() { return ((::Adaptor2d_HCurve2d*)_NativeInstance)->IsPeriodic(); } double Macad::Occt::Adaptor2d_HCurve2d::Period() { return ((::Adaptor2d_HCurve2d*)_NativeInstance)->Period(); } Macad::Occt::Pnt2d Macad::Occt::Adaptor2d_HCurve2d::Value(double U) { return Macad::Occt::Pnt2d(((::Adaptor2d_HCurve2d*)_NativeInstance)->Value(U)); } void Macad::Occt::Adaptor2d_HCurve2d::D0(double U, Macad::Occt::Pnt2d% P) { pin_ptr<Macad::Occt::Pnt2d> pp_P = &P; ((::Adaptor2d_HCurve2d*)_NativeInstance)->D0(U, *(gp_Pnt2d*)pp_P); } void Macad::Occt::Adaptor2d_HCurve2d::D1(double U, Macad::Occt::Pnt2d% P, Macad::Occt::Vec2d% V) { pin_ptr<Macad::Occt::Pnt2d> pp_P = &P; pin_ptr<Macad::Occt::Vec2d> pp_V = &V; ((::Adaptor2d_HCurve2d*)_NativeInstance)->D1(U, *(gp_Pnt2d*)pp_P, *(gp_Vec2d*)pp_V); } void Macad::Occt::Adaptor2d_HCurve2d::D2(double U, Macad::Occt::Pnt2d% P, Macad::Occt::Vec2d% V1, Macad::Occt::Vec2d% V2) { pin_ptr<Macad::Occt::Pnt2d> pp_P = &P; pin_ptr<Macad::Occt::Vec2d> pp_V1 = &V1; pin_ptr<Macad::Occt::Vec2d> pp_V2 = &V2; ((::Adaptor2d_HCurve2d*)_NativeInstance)->D2(U, *(gp_Pnt2d*)pp_P, *(gp_Vec2d*)pp_V1, *(gp_Vec2d*)pp_V2); } void Macad::Occt::Adaptor2d_HCurve2d::D3(double U, Macad::Occt::Pnt2d% P, Macad::Occt::Vec2d% V1, Macad::Occt::Vec2d% V2, Macad::Occt::Vec2d% V3) { pin_ptr<Macad::Occt::Pnt2d> pp_P = &P; pin_ptr<Macad::Occt::Vec2d> pp_V1 = &V1; pin_ptr<Macad::Occt::Vec2d> pp_V2 = &V2; pin_ptr<Macad::Occt::Vec2d> pp_V3 = &V3; ((::Adaptor2d_HCurve2d*)_NativeInstance)->D3(U, *(gp_Pnt2d*)pp_P, *(gp_Vec2d*)pp_V1, *(gp_Vec2d*)pp_V2, *(gp_Vec2d*)pp_V3); } Macad::Occt::Vec2d Macad::Occt::Adaptor2d_HCurve2d::DN(double U, int N) { return Macad::Occt::Vec2d(((::Adaptor2d_HCurve2d*)_NativeInstance)->DN(U, N)); } double Macad::Occt::Adaptor2d_HCurve2d::Resolution(double R3d) { return ((::Adaptor2d_HCurve2d*)_NativeInstance)->Resolution(R3d); } Macad::Occt::GeomAbs_CurveType Macad::Occt::Adaptor2d_HCurve2d::GetGeomType() { return (Macad::Occt::GeomAbs_CurveType)((::Adaptor2d_HCurve2d*)_NativeInstance)->GetType(); } Macad::Occt::gp_Lin2d^ Macad::Occt::Adaptor2d_HCurve2d::Line() { ::gp_Lin2d* _result = new ::gp_Lin2d(); *_result = ((::Adaptor2d_HCurve2d*)_NativeInstance)->Line(); return _result==nullptr ? nullptr : gcnew Macad::Occt::gp_Lin2d(_result); } Macad::Occt::gp_Circ2d^ Macad::Occt::Adaptor2d_HCurve2d::Circle() { ::gp_Circ2d* _result = new ::gp_Circ2d(); *_result = ((::Adaptor2d_HCurve2d*)_NativeInstance)->Circle(); return _result==nullptr ? nullptr : gcnew Macad::Occt::gp_Circ2d(_result); } Macad::Occt::gp_Elips2d^ Macad::Occt::Adaptor2d_HCurve2d::Ellipse() { ::gp_Elips2d* _result = new ::gp_Elips2d(); *_result = ((::Adaptor2d_HCurve2d*)_NativeInstance)->Ellipse(); return _result==nullptr ? nullptr : gcnew Macad::Occt::gp_Elips2d(_result); } Macad::Occt::gp_Hypr2d^ Macad::Occt::Adaptor2d_HCurve2d::Hyperbola() { ::gp_Hypr2d* _result = new ::gp_Hypr2d(); *_result = ((::Adaptor2d_HCurve2d*)_NativeInstance)->Hyperbola(); return _result==nullptr ? nullptr : gcnew Macad::Occt::gp_Hypr2d(_result); } Macad::Occt::gp_Parab2d^ Macad::Occt::Adaptor2d_HCurve2d::Parabola() { ::gp_Parab2d* _result = new ::gp_Parab2d(); *_result = ((::Adaptor2d_HCurve2d*)_NativeInstance)->Parabola(); return _result==nullptr ? nullptr : gcnew Macad::Occt::gp_Parab2d(_result); } int Macad::Occt::Adaptor2d_HCurve2d::Degree() { return ((::Adaptor2d_HCurve2d*)_NativeInstance)->Degree(); } bool Macad::Occt::Adaptor2d_HCurve2d::IsRational() { return ((::Adaptor2d_HCurve2d*)_NativeInstance)->IsRational(); } int Macad::Occt::Adaptor2d_HCurve2d::NbPoles() { return ((::Adaptor2d_HCurve2d*)_NativeInstance)->NbPoles(); } int Macad::Occt::Adaptor2d_HCurve2d::NbKnots() { return ((::Adaptor2d_HCurve2d*)_NativeInstance)->NbKnots(); } Macad::Occt::Geom2d_BezierCurve^ Macad::Occt::Adaptor2d_HCurve2d::Bezier() { Handle(::Geom2d_BezierCurve) _result; _result = ((::Adaptor2d_HCurve2d*)_NativeInstance)->Bezier(); return _result.IsNull() ? nullptr : Macad::Occt::Geom2d_BezierCurve::CreateDowncasted( _result.get()); } Macad::Occt::Geom2d_BSplineCurve^ Macad::Occt::Adaptor2d_HCurve2d::BSpline() { Handle(::Geom2d_BSplineCurve) _result; _result = ((::Adaptor2d_HCurve2d*)_NativeInstance)->BSpline(); return _result.IsNull() ? nullptr : Macad::Occt::Geom2d_BSplineCurve::CreateDowncasted( _result.get()); } Macad::Occt::Adaptor2d_HCurve2d^ Macad::Occt::Adaptor2d_HCurve2d::CreateDowncasted(::Adaptor2d_HCurve2d* instance) { if( instance == nullptr ) return nullptr; if (instance->IsKind(STANDARD_TYPE(::Adaptor2d_HLine2d))) return Macad::Occt::Adaptor2d_HLine2d::CreateDowncasted((::Adaptor2d_HLine2d*)instance); if (instance->IsKind(STANDARD_TYPE(::Adaptor2d_HOffsetCurve))) return Macad::Occt::Adaptor2d_HOffsetCurve::CreateDowncasted((::Adaptor2d_HOffsetCurve*)instance); if (instance->IsKind(STANDARD_TYPE(::Geom2dAdaptor_GHCurve))) return Macad::Occt::Geom2dAdaptor_GHCurve::CreateDowncasted((::Geom2dAdaptor_GHCurve*)instance); if (instance->IsKind(STANDARD_TYPE(::ProjLib_HProjectedCurve))) return Macad::Occt::ProjLib_HProjectedCurve::CreateDowncasted((::ProjLib_HProjectedCurve*)instance); if (instance->IsKind(STANDARD_TYPE(::ProjLib_HCompProjectedCurve))) return Macad::Occt::ProjLib_HCompProjectedCurve::CreateDowncasted((::ProjLib_HCompProjectedCurve*)instance); if (instance->IsKind(STANDARD_TYPE(::BRepAdaptor_HCurve2d))) return Macad::Occt::BRepAdaptor_HCurve2d::CreateDowncasted((::BRepAdaptor_HCurve2d*)instance); return gcnew Macad::Occt::Adaptor2d_HCurve2d( instance ); } //--------------------------------------------------------------------- // Class Adaptor2d_Curve2d //--------------------------------------------------------------------- Macad::Occt::Adaptor2d_Curve2d::Adaptor2d_Curve2d(Macad::Occt::Adaptor2d_Curve2d^ parameter1) : BaseClass<::Adaptor2d_Curve2d>(BaseClass::InitMode::Uninitialized) { _NativeInstance = new ::Adaptor2d_Curve2d(*(::Adaptor2d_Curve2d*)parameter1->NativeInstance); } Macad::Occt::Adaptor2d_Curve2d::Adaptor2d_Curve2d() : BaseClass<::Adaptor2d_Curve2d>(BaseClass::InitMode::Uninitialized) { _NativeInstance = new ::Adaptor2d_Curve2d(); } double Macad::Occt::Adaptor2d_Curve2d::FirstParameter() { return ((::Adaptor2d_Curve2d*)_NativeInstance)->FirstParameter(); } double Macad::Occt::Adaptor2d_Curve2d::LastParameter() { return ((::Adaptor2d_Curve2d*)_NativeInstance)->LastParameter(); } Macad::Occt::GeomAbs_Shape Macad::Occt::Adaptor2d_Curve2d::Continuity() { return (Macad::Occt::GeomAbs_Shape)((::Adaptor2d_Curve2d*)_NativeInstance)->Continuity(); } int Macad::Occt::Adaptor2d_Curve2d::NbIntervals(Macad::Occt::GeomAbs_Shape S) { return ((::Adaptor2d_Curve2d*)_NativeInstance)->NbIntervals((::GeomAbs_Shape)S); } void Macad::Occt::Adaptor2d_Curve2d::Intervals(Macad::Occt::TColStd_Array1OfReal^ T, Macad::Occt::GeomAbs_Shape S) { ((::Adaptor2d_Curve2d*)_NativeInstance)->Intervals(*(::TColStd_Array1OfReal*)T->NativeInstance, (::GeomAbs_Shape)S); } Macad::Occt::Adaptor2d_HCurve2d^ Macad::Occt::Adaptor2d_Curve2d::Trim(double First, double Last, double Tol) { Handle(::Adaptor2d_HCurve2d) _result; _result = ((::Adaptor2d_Curve2d*)_NativeInstance)->Trim(First, Last, Tol); return _result.IsNull() ? nullptr : Macad::Occt::Adaptor2d_HCurve2d::CreateDowncasted( _result.get()); } bool Macad::Occt::Adaptor2d_Curve2d::IsClosed() { return ((::Adaptor2d_Curve2d*)_NativeInstance)->IsClosed(); } bool Macad::Occt::Adaptor2d_Curve2d::IsPeriodic() { return ((::Adaptor2d_Curve2d*)_NativeInstance)->IsPeriodic(); } double Macad::Occt::Adaptor2d_Curve2d::Period() { return ((::Adaptor2d_Curve2d*)_NativeInstance)->Period(); } Macad::Occt::Pnt2d Macad::Occt::Adaptor2d_Curve2d::Value(double U) { return Macad::Occt::Pnt2d(((::Adaptor2d_Curve2d*)_NativeInstance)->Value(U)); } void Macad::Occt::Adaptor2d_Curve2d::D0(double U, Macad::Occt::Pnt2d% P) { pin_ptr<Macad::Occt::Pnt2d> pp_P = &P; ((::Adaptor2d_Curve2d*)_NativeInstance)->D0(U, *(gp_Pnt2d*)pp_P); } void Macad::Occt::Adaptor2d_Curve2d::D1(double U, Macad::Occt::Pnt2d% P, Macad::Occt::Vec2d% V) { pin_ptr<Macad::Occt::Pnt2d> pp_P = &P; pin_ptr<Macad::Occt::Vec2d> pp_V = &V; ((::Adaptor2d_Curve2d*)_NativeInstance)->D1(U, *(gp_Pnt2d*)pp_P, *(gp_Vec2d*)pp_V); } void Macad::Occt::Adaptor2d_Curve2d::D2(double U, Macad::Occt::Pnt2d% P, Macad::Occt::Vec2d% V1, Macad::Occt::Vec2d% V2) { pin_ptr<Macad::Occt::Pnt2d> pp_P = &P; pin_ptr<Macad::Occt::Vec2d> pp_V1 = &V1; pin_ptr<Macad::Occt::Vec2d> pp_V2 = &V2; ((::Adaptor2d_Curve2d*)_NativeInstance)->D2(U, *(gp_Pnt2d*)pp_P, *(gp_Vec2d*)pp_V1, *(gp_Vec2d*)pp_V2); } void Macad::Occt::Adaptor2d_Curve2d::D3(double U, Macad::Occt::Pnt2d% P, Macad::Occt::Vec2d% V1, Macad::Occt::Vec2d% V2, Macad::Occt::Vec2d% V3) { pin_ptr<Macad::Occt::Pnt2d> pp_P = &P; pin_ptr<Macad::Occt::Vec2d> pp_V1 = &V1; pin_ptr<Macad::Occt::Vec2d> pp_V2 = &V2; pin_ptr<Macad::Occt::Vec2d> pp_V3 = &V3; ((::Adaptor2d_Curve2d*)_NativeInstance)->D3(U, *(gp_Pnt2d*)pp_P, *(gp_Vec2d*)pp_V1, *(gp_Vec2d*)pp_V2, *(gp_Vec2d*)pp_V3); } Macad::Occt::Vec2d Macad::Occt::Adaptor2d_Curve2d::DN(double U, int N) { return Macad::Occt::Vec2d(((::Adaptor2d_Curve2d*)_NativeInstance)->DN(U, N)); } double Macad::Occt::Adaptor2d_Curve2d::Resolution(double R3d) { return ((::Adaptor2d_Curve2d*)_NativeInstance)->Resolution(R3d); } Macad::Occt::GeomAbs_CurveType Macad::Occt::Adaptor2d_Curve2d::GetGeomType() { return (Macad::Occt::GeomAbs_CurveType)((::Adaptor2d_Curve2d*)_NativeInstance)->GetType(); } Macad::Occt::gp_Lin2d^ Macad::Occt::Adaptor2d_Curve2d::Line() { ::gp_Lin2d* _result = new ::gp_Lin2d(); *_result = ((::Adaptor2d_Curve2d*)_NativeInstance)->Line(); return _result==nullptr ? nullptr : gcnew Macad::Occt::gp_Lin2d(_result); } Macad::Occt::gp_Circ2d^ Macad::Occt::Adaptor2d_Curve2d::Circle() { ::gp_Circ2d* _result = new ::gp_Circ2d(); *_result = ((::Adaptor2d_Curve2d*)_NativeInstance)->Circle(); return _result==nullptr ? nullptr : gcnew Macad::Occt::gp_Circ2d(_result); } Macad::Occt::gp_Elips2d^ Macad::Occt::Adaptor2d_Curve2d::Ellipse() { ::gp_Elips2d* _result = new ::gp_Elips2d(); *_result = ((::Adaptor2d_Curve2d*)_NativeInstance)->Ellipse(); return _result==nullptr ? nullptr : gcnew Macad::Occt::gp_Elips2d(_result); } Macad::Occt::gp_Hypr2d^ Macad::Occt::Adaptor2d_Curve2d::Hyperbola() { ::gp_Hypr2d* _result = new ::gp_Hypr2d(); *_result = ((::Adaptor2d_Curve2d*)_NativeInstance)->Hyperbola(); return _result==nullptr ? nullptr : gcnew Macad::Occt::gp_Hypr2d(_result); } Macad::Occt::gp_Parab2d^ Macad::Occt::Adaptor2d_Curve2d::Parabola() { ::gp_Parab2d* _result = new ::gp_Parab2d(); *_result = ((::Adaptor2d_Curve2d*)_NativeInstance)->Parabola(); return _result==nullptr ? nullptr : gcnew Macad::Occt::gp_Parab2d(_result); } int Macad::Occt::Adaptor2d_Curve2d::Degree() { return ((::Adaptor2d_Curve2d*)_NativeInstance)->Degree(); } bool Macad::Occt::Adaptor2d_Curve2d::IsRational() { return ((::Adaptor2d_Curve2d*)_NativeInstance)->IsRational(); } int Macad::Occt::Adaptor2d_Curve2d::NbPoles() { return ((::Adaptor2d_Curve2d*)_NativeInstance)->NbPoles(); } int Macad::Occt::Adaptor2d_Curve2d::NbKnots() { return ((::Adaptor2d_Curve2d*)_NativeInstance)->NbKnots(); } int Macad::Occt::Adaptor2d_Curve2d::NbSamples() { return ((::Adaptor2d_Curve2d*)_NativeInstance)->NbSamples(); } Macad::Occt::Geom2d_BezierCurve^ Macad::Occt::Adaptor2d_Curve2d::Bezier() { Handle(::Geom2d_BezierCurve) _result; _result = ((::Adaptor2d_Curve2d*)_NativeInstance)->Bezier(); return _result.IsNull() ? nullptr : Macad::Occt::Geom2d_BezierCurve::CreateDowncasted( _result.get()); } Macad::Occt::Geom2d_BSplineCurve^ Macad::Occt::Adaptor2d_Curve2d::BSpline() { Handle(::Geom2d_BSplineCurve) _result; _result = ((::Adaptor2d_Curve2d*)_NativeInstance)->BSpline(); return _result.IsNull() ? nullptr : Macad::Occt::Geom2d_BSplineCurve::CreateDowncasted( _result.get()); } //--------------------------------------------------------------------- // Class Adaptor2d_Line2d //--------------------------------------------------------------------- Macad::Occt::Adaptor2d_Line2d::Adaptor2d_Line2d() : Macad::Occt::Adaptor2d_Curve2d(BaseClass::InitMode::Uninitialized) { _NativeInstance = new ::Adaptor2d_Line2d(); } Macad::Occt::Adaptor2d_Line2d::Adaptor2d_Line2d(Macad::Occt::Pnt2d P, Macad::Occt::Dir2d D, double UFirst, double ULast) : Macad::Occt::Adaptor2d_Curve2d(BaseClass::InitMode::Uninitialized) { pin_ptr<Macad::Occt::Pnt2d> pp_P = &P; pin_ptr<Macad::Occt::Dir2d> pp_D = &D; _NativeInstance = new ::Adaptor2d_Line2d(*(gp_Pnt2d*)pp_P, *(gp_Dir2d*)pp_D, UFirst, ULast); } Macad::Occt::Adaptor2d_Line2d::Adaptor2d_Line2d(Macad::Occt::Adaptor2d_Line2d^ parameter1) : Macad::Occt::Adaptor2d_Curve2d(BaseClass::InitMode::Uninitialized) { _NativeInstance = new ::Adaptor2d_Line2d(*(::Adaptor2d_Line2d*)parameter1->NativeInstance); } void Macad::Occt::Adaptor2d_Line2d::Load(Macad::Occt::gp_Lin2d^ L) { ((::Adaptor2d_Line2d*)_NativeInstance)->Load(*(::gp_Lin2d*)L->NativeInstance); } void Macad::Occt::Adaptor2d_Line2d::Load(Macad::Occt::gp_Lin2d^ L, double UFirst, double ULast) { ((::Adaptor2d_Line2d*)_NativeInstance)->Load(*(::gp_Lin2d*)L->NativeInstance, UFirst, ULast); } double Macad::Occt::Adaptor2d_Line2d::FirstParameter() { return ((::Adaptor2d_Line2d*)_NativeInstance)->FirstParameter(); } double Macad::Occt::Adaptor2d_Line2d::LastParameter() { return ((::Adaptor2d_Line2d*)_NativeInstance)->LastParameter(); } Macad::Occt::GeomAbs_Shape Macad::Occt::Adaptor2d_Line2d::Continuity() { return (Macad::Occt::GeomAbs_Shape)((::Adaptor2d_Line2d*)_NativeInstance)->Continuity(); } int Macad::Occt::Adaptor2d_Line2d::NbIntervals(Macad::Occt::GeomAbs_Shape S) { return ((::Adaptor2d_Line2d*)_NativeInstance)->NbIntervals((::GeomAbs_Shape)S); } void Macad::Occt::Adaptor2d_Line2d::Intervals(Macad::Occt::TColStd_Array1OfReal^ T, Macad::Occt::GeomAbs_Shape S) { ((::Adaptor2d_Line2d*)_NativeInstance)->Intervals(*(::TColStd_Array1OfReal*)T->NativeInstance, (::GeomAbs_Shape)S); } Macad::Occt::Adaptor2d_HCurve2d^ Macad::Occt::Adaptor2d_Line2d::Trim(double First, double Last, double Tol) { Handle(::Adaptor2d_HCurve2d) _result; _result = ((::Adaptor2d_Line2d*)_NativeInstance)->Trim(First, Last, Tol); return _result.IsNull() ? nullptr : Macad::Occt::Adaptor2d_HCurve2d::CreateDowncasted( _result.get()); } bool Macad::Occt::Adaptor2d_Line2d::IsClosed() { return ((::Adaptor2d_Line2d*)_NativeInstance)->IsClosed(); } bool Macad::Occt::Adaptor2d_Line2d::IsPeriodic() { return ((::Adaptor2d_Line2d*)_NativeInstance)->IsPeriodic(); } double Macad::Occt::Adaptor2d_Line2d::Period() { return ((::Adaptor2d_Line2d*)_NativeInstance)->Period(); } Macad::Occt::Pnt2d Macad::Occt::Adaptor2d_Line2d::Value(double X) { return Macad::Occt::Pnt2d(((::Adaptor2d_Line2d*)_NativeInstance)->Value(X)); } void Macad::Occt::Adaptor2d_Line2d::D0(double X, Macad::Occt::Pnt2d% P) { pin_ptr<Macad::Occt::Pnt2d> pp_P = &P; ((::Adaptor2d_Line2d*)_NativeInstance)->D0(X, *(gp_Pnt2d*)pp_P); } void Macad::Occt::Adaptor2d_Line2d::D1(double X, Macad::Occt::Pnt2d% P, Macad::Occt::Vec2d% V) { pin_ptr<Macad::Occt::Pnt2d> pp_P = &P; pin_ptr<Macad::Occt::Vec2d> pp_V = &V; ((::Adaptor2d_Line2d*)_NativeInstance)->D1(X, *(gp_Pnt2d*)pp_P, *(gp_Vec2d*)pp_V); } void Macad::Occt::Adaptor2d_Line2d::D2(double X, Macad::Occt::Pnt2d% P, Macad::Occt::Vec2d% V1, Macad::Occt::Vec2d% V2) { pin_ptr<Macad::Occt::Pnt2d> pp_P = &P; pin_ptr<Macad::Occt::Vec2d> pp_V1 = &V1; pin_ptr<Macad::Occt::Vec2d> pp_V2 = &V2; ((::Adaptor2d_Line2d*)_NativeInstance)->D2(X, *(gp_Pnt2d*)pp_P, *(gp_Vec2d*)pp_V1, *(gp_Vec2d*)pp_V2); } void Macad::Occt::Adaptor2d_Line2d::D3(double X, Macad::Occt::Pnt2d% P, Macad::Occt::Vec2d% V1, Macad::Occt::Vec2d% V2, Macad::Occt::Vec2d% V3) { pin_ptr<Macad::Occt::Pnt2d> pp_P = &P; pin_ptr<Macad::Occt::Vec2d> pp_V1 = &V1; pin_ptr<Macad::Occt::Vec2d> pp_V2 = &V2; pin_ptr<Macad::Occt::Vec2d> pp_V3 = &V3; ((::Adaptor2d_Line2d*)_NativeInstance)->D3(X, *(gp_Pnt2d*)pp_P, *(gp_Vec2d*)pp_V1, *(gp_Vec2d*)pp_V2, *(gp_Vec2d*)pp_V3); } Macad::Occt::Vec2d Macad::Occt::Adaptor2d_Line2d::DN(double U, int N) { return Macad::Occt::Vec2d(((::Adaptor2d_Line2d*)_NativeInstance)->DN(U, N)); } double Macad::Occt::Adaptor2d_Line2d::Resolution(double R3d) { return ((::Adaptor2d_Line2d*)_NativeInstance)->Resolution(R3d); } Macad::Occt::GeomAbs_CurveType Macad::Occt::Adaptor2d_Line2d::GetGeomType() { return (Macad::Occt::GeomAbs_CurveType)((::Adaptor2d_Line2d*)_NativeInstance)->GetType(); } Macad::Occt::gp_Lin2d^ Macad::Occt::Adaptor2d_Line2d::Line() { ::gp_Lin2d* _result = new ::gp_Lin2d(); *_result = ((::Adaptor2d_Line2d*)_NativeInstance)->Line(); return _result==nullptr ? nullptr : gcnew Macad::Occt::gp_Lin2d(_result); } Macad::Occt::gp_Circ2d^ Macad::Occt::Adaptor2d_Line2d::Circle() { ::gp_Circ2d* _result = new ::gp_Circ2d(); *_result = ((::Adaptor2d_Line2d*)_NativeInstance)->Circle(); return _result==nullptr ? nullptr : gcnew Macad::Occt::gp_Circ2d(_result); } Macad::Occt::gp_Elips2d^ Macad::Occt::Adaptor2d_Line2d::Ellipse() { ::gp_Elips2d* _result = new ::gp_Elips2d(); *_result = ((::Adaptor2d_Line2d*)_NativeInstance)->Ellipse(); return _result==nullptr ? nullptr : gcnew Macad::Occt::gp_Elips2d(_result); } Macad::Occt::gp_Hypr2d^ Macad::Occt::Adaptor2d_Line2d::Hyperbola() { ::gp_Hypr2d* _result = new ::gp_Hypr2d(); *_result = ((::Adaptor2d_Line2d*)_NativeInstance)->Hyperbola(); return _result==nullptr ? nullptr : gcnew Macad::Occt::gp_Hypr2d(_result); } Macad::Occt::gp_Parab2d^ Macad::Occt::Adaptor2d_Line2d::Parabola() { ::gp_Parab2d* _result = new ::gp_Parab2d(); *_result = ((::Adaptor2d_Line2d*)_NativeInstance)->Parabola(); return _result==nullptr ? nullptr : gcnew Macad::Occt::gp_Parab2d(_result); } int Macad::Occt::Adaptor2d_Line2d::Degree() { return ((::Adaptor2d_Line2d*)_NativeInstance)->Degree(); } bool Macad::Occt::Adaptor2d_Line2d::IsRational() { return ((::Adaptor2d_Line2d*)_NativeInstance)->IsRational(); } int Macad::Occt::Adaptor2d_Line2d::NbPoles() { return ((::Adaptor2d_Line2d*)_NativeInstance)->NbPoles(); } int Macad::Occt::Adaptor2d_Line2d::NbKnots() { return ((::Adaptor2d_Line2d*)_NativeInstance)->NbKnots(); } Macad::Occt::Geom2d_BezierCurve^ Macad::Occt::Adaptor2d_Line2d::Bezier() { Handle(::Geom2d_BezierCurve) _result; _result = ((::Adaptor2d_Line2d*)_NativeInstance)->Bezier(); return _result.IsNull() ? nullptr : Macad::Occt::Geom2d_BezierCurve::CreateDowncasted( _result.get()); } Macad::Occt::Geom2d_BSplineCurve^ Macad::Occt::Adaptor2d_Line2d::BSpline() { Handle(::Geom2d_BSplineCurve) _result; _result = ((::Adaptor2d_Line2d*)_NativeInstance)->BSpline(); return _result.IsNull() ? nullptr : Macad::Occt::Geom2d_BSplineCurve::CreateDowncasted( _result.get()); } //--------------------------------------------------------------------- // Class Adaptor2d_HLine2d //--------------------------------------------------------------------- Macad::Occt::Adaptor2d_HLine2d::Adaptor2d_HLine2d() : Macad::Occt::Adaptor2d_HCurve2d(BaseClass::InitMode::Uninitialized) { NativeInstance = new ::Adaptor2d_HLine2d(); } Macad::Occt::Adaptor2d_HLine2d::Adaptor2d_HLine2d(Macad::Occt::Adaptor2d_Line2d^ C) : Macad::Occt::Adaptor2d_HCurve2d(BaseClass::InitMode::Uninitialized) { NativeInstance = new ::Adaptor2d_HLine2d(*(::Adaptor2d_Line2d*)C->NativeInstance); } Macad::Occt::Adaptor2d_HLine2d::Adaptor2d_HLine2d(Macad::Occt::Adaptor2d_HLine2d^ parameter1) : Macad::Occt::Adaptor2d_HCurve2d(BaseClass::InitMode::Uninitialized) { NativeInstance = new ::Adaptor2d_HLine2d(*(::Adaptor2d_HLine2d*)parameter1->NativeInstance); } void Macad::Occt::Adaptor2d_HLine2d::Set(Macad::Occt::Adaptor2d_Line2d^ C) { ((::Adaptor2d_HLine2d*)_NativeInstance)->Set(*(::Adaptor2d_Line2d*)C->NativeInstance); } Macad::Occt::Adaptor2d_Curve2d^ Macad::Occt::Adaptor2d_HLine2d::Curve2d() { ::Adaptor2d_Curve2d* _result = new ::Adaptor2d_Curve2d(); *_result = (::Adaptor2d_Curve2d)((::Adaptor2d_HLine2d*)_NativeInstance)->Curve2d(); return _result==nullptr ? nullptr : gcnew Macad::Occt::Adaptor2d_Curve2d(_result); } Macad::Occt::Adaptor2d_Line2d^ Macad::Occt::Adaptor2d_HLine2d::ChangeCurve2d() { ::Adaptor2d_Line2d* _result = new ::Adaptor2d_Line2d(); *_result = ((::Adaptor2d_HLine2d*)_NativeInstance)->ChangeCurve2d(); return _result==nullptr ? nullptr : gcnew Macad::Occt::Adaptor2d_Line2d(_result); } Macad::Occt::Adaptor2d_HLine2d^ Macad::Occt::Adaptor2d_HLine2d::CreateDowncasted(::Adaptor2d_HLine2d* instance) { return gcnew Macad::Occt::Adaptor2d_HLine2d( instance ); } //--------------------------------------------------------------------- // Class Adaptor2d_OffsetCurve //--------------------------------------------------------------------- Macad::Occt::Adaptor2d_OffsetCurve::Adaptor2d_OffsetCurve() : Macad::Occt::Adaptor2d_Curve2d(BaseClass::InitMode::Uninitialized) { _NativeInstance = new ::Adaptor2d_OffsetCurve(); } Macad::Occt::Adaptor2d_OffsetCurve::Adaptor2d_OffsetCurve(Macad::Occt::Adaptor2d_HCurve2d^ C) : Macad::Occt::Adaptor2d_Curve2d(BaseClass::InitMode::Uninitialized) { Handle(::Adaptor2d_HCurve2d) h_C = C->NativeInstance; _NativeInstance = new ::Adaptor2d_OffsetCurve(h_C); C->NativeInstance = h_C.get(); } Macad::Occt::Adaptor2d_OffsetCurve::Adaptor2d_OffsetCurve(Macad::Occt::Adaptor2d_HCurve2d^ C, double Offset) : Macad::Occt::Adaptor2d_Curve2d(BaseClass::InitMode::Uninitialized) { Handle(::Adaptor2d_HCurve2d) h_C = C->NativeInstance; _NativeInstance = new ::Adaptor2d_OffsetCurve(h_C, Offset); C->NativeInstance = h_C.get(); } Macad::Occt::Adaptor2d_OffsetCurve::Adaptor2d_OffsetCurve(Macad::Occt::Adaptor2d_HCurve2d^ C, double Offset, double WFirst, double WLast) : Macad::Occt::Adaptor2d_Curve2d(BaseClass::InitMode::Uninitialized) { Handle(::Adaptor2d_HCurve2d) h_C = C->NativeInstance; _NativeInstance = new ::Adaptor2d_OffsetCurve(h_C, Offset, WFirst, WLast); C->NativeInstance = h_C.get(); } Macad::Occt::Adaptor2d_OffsetCurve::Adaptor2d_OffsetCurve(Macad::Occt::Adaptor2d_OffsetCurve^ parameter1) : Macad::Occt::Adaptor2d_Curve2d(BaseClass::InitMode::Uninitialized) { _NativeInstance = new ::Adaptor2d_OffsetCurve(*(::Adaptor2d_OffsetCurve*)parameter1->NativeInstance); } void Macad::Occt::Adaptor2d_OffsetCurve::Load(Macad::Occt::Adaptor2d_HCurve2d^ S) { Handle(::Adaptor2d_HCurve2d) h_S = S->NativeInstance; ((::Adaptor2d_OffsetCurve*)_NativeInstance)->Load(h_S); S->NativeInstance = h_S.get(); } void Macad::Occt::Adaptor2d_OffsetCurve::Load(double Offset) { ((::Adaptor2d_OffsetCurve*)_NativeInstance)->Load(Offset); } void Macad::Occt::Adaptor2d_OffsetCurve::Load(double Offset, double WFirst, double WLast) { ((::Adaptor2d_OffsetCurve*)_NativeInstance)->Load(Offset, WFirst, WLast); } Macad::Occt::Adaptor2d_HCurve2d^ Macad::Occt::Adaptor2d_OffsetCurve::Curve() { Handle(::Adaptor2d_HCurve2d) _result; _result = ((::Adaptor2d_OffsetCurve*)_NativeInstance)->Curve(); return _result.IsNull() ? nullptr : Macad::Occt::Adaptor2d_HCurve2d::CreateDowncasted( _result.get()); } double Macad::Occt::Adaptor2d_OffsetCurve::Offset() { return ((::Adaptor2d_OffsetCurve*)_NativeInstance)->Offset(); } double Macad::Occt::Adaptor2d_OffsetCurve::FirstParameter() { return ((::Adaptor2d_OffsetCurve*)_NativeInstance)->FirstParameter(); } double Macad::Occt::Adaptor2d_OffsetCurve::LastParameter() { return ((::Adaptor2d_OffsetCurve*)_NativeInstance)->LastParameter(); } Macad::Occt::GeomAbs_Shape Macad::Occt::Adaptor2d_OffsetCurve::Continuity() { return (Macad::Occt::GeomAbs_Shape)((::Adaptor2d_OffsetCurve*)_NativeInstance)->Continuity(); } int Macad::Occt::Adaptor2d_OffsetCurve::NbIntervals(Macad::Occt::GeomAbs_Shape S) { return ((::Adaptor2d_OffsetCurve*)_NativeInstance)->NbIntervals((::GeomAbs_Shape)S); } void Macad::Occt::Adaptor2d_OffsetCurve::Intervals(Macad::Occt::TColStd_Array1OfReal^ T, Macad::Occt::GeomAbs_Shape S) { ((::Adaptor2d_OffsetCurve*)_NativeInstance)->Intervals(*(::TColStd_Array1OfReal*)T->NativeInstance, (::GeomAbs_Shape)S); } Macad::Occt::Adaptor2d_HCurve2d^ Macad::Occt::Adaptor2d_OffsetCurve::Trim(double First, double Last, double Tol) { Handle(::Adaptor2d_HCurve2d) _result; _result = ((::Adaptor2d_OffsetCurve*)_NativeInstance)->Trim(First, Last, Tol); return _result.IsNull() ? nullptr : Macad::Occt::Adaptor2d_HCurve2d::CreateDowncasted( _result.get()); } bool Macad::Occt::Adaptor2d_OffsetCurve::IsClosed() { return ((::Adaptor2d_OffsetCurve*)_NativeInstance)->IsClosed(); } bool Macad::Occt::Adaptor2d_OffsetCurve::IsPeriodic() { return ((::Adaptor2d_OffsetCurve*)_NativeInstance)->IsPeriodic(); } double Macad::Occt::Adaptor2d_OffsetCurve::Period() { return ((::Adaptor2d_OffsetCurve*)_NativeInstance)->Period(); } Macad::Occt::Pnt2d Macad::Occt::Adaptor2d_OffsetCurve::Value(double U) { return Macad::Occt::Pnt2d(((::Adaptor2d_OffsetCurve*)_NativeInstance)->Value(U)); } void Macad::Occt::Adaptor2d_OffsetCurve::D0(double U, Macad::Occt::Pnt2d% P) { pin_ptr<Macad::Occt::Pnt2d> pp_P = &P; ((::Adaptor2d_OffsetCurve*)_NativeInstance)->D0(U, *(gp_Pnt2d*)pp_P); } void Macad::Occt::Adaptor2d_OffsetCurve::D1(double U, Macad::Occt::Pnt2d% P, Macad::Occt::Vec2d% V) { pin_ptr<Macad::Occt::Pnt2d> pp_P = &P; pin_ptr<Macad::Occt::Vec2d> pp_V = &V; ((::Adaptor2d_OffsetCurve*)_NativeInstance)->D1(U, *(gp_Pnt2d*)pp_P, *(gp_Vec2d*)pp_V); } void Macad::Occt::Adaptor2d_OffsetCurve::D2(double U, Macad::Occt::Pnt2d% P, Macad::Occt::Vec2d% V1, Macad::Occt::Vec2d% V2) { pin_ptr<Macad::Occt::Pnt2d> pp_P = &P; pin_ptr<Macad::Occt::Vec2d> pp_V1 = &V1; pin_ptr<Macad::Occt::Vec2d> pp_V2 = &V2; ((::Adaptor2d_OffsetCurve*)_NativeInstance)->D2(U, *(gp_Pnt2d*)pp_P, *(gp_Vec2d*)pp_V1, *(gp_Vec2d*)pp_V2); } void Macad::Occt::Adaptor2d_OffsetCurve::D3(double U, Macad::Occt::Pnt2d% P, Macad::Occt::Vec2d% V1, Macad::Occt::Vec2d% V2, Macad::Occt::Vec2d% V3) { pin_ptr<Macad::Occt::Pnt2d> pp_P = &P; pin_ptr<Macad::Occt::Vec2d> pp_V1 = &V1; pin_ptr<Macad::Occt::Vec2d> pp_V2 = &V2; pin_ptr<Macad::Occt::Vec2d> pp_V3 = &V3; ((::Adaptor2d_OffsetCurve*)_NativeInstance)->D3(U, *(gp_Pnt2d*)pp_P, *(gp_Vec2d*)pp_V1, *(gp_Vec2d*)pp_V2, *(gp_Vec2d*)pp_V3); } Macad::Occt::Vec2d Macad::Occt::Adaptor2d_OffsetCurve::DN(double U, int N) { return Macad::Occt::Vec2d(((::Adaptor2d_OffsetCurve*)_NativeInstance)->DN(U, N)); } double Macad::Occt::Adaptor2d_OffsetCurve::Resolution(double R3d) { return ((::Adaptor2d_OffsetCurve*)_NativeInstance)->Resolution(R3d); } Macad::Occt::GeomAbs_CurveType Macad::Occt::Adaptor2d_OffsetCurve::GetGeomType() { return (Macad::Occt::GeomAbs_CurveType)((::Adaptor2d_OffsetCurve*)_NativeInstance)->GetType(); } Macad::Occt::gp_Lin2d^ Macad::Occt::Adaptor2d_OffsetCurve::Line() { ::gp_Lin2d* _result = new ::gp_Lin2d(); *_result = ((::Adaptor2d_OffsetCurve*)_NativeInstance)->Line(); return _result==nullptr ? nullptr : gcnew Macad::Occt::gp_Lin2d(_result); } Macad::Occt::gp_Circ2d^ Macad::Occt::Adaptor2d_OffsetCurve::Circle() { ::gp_Circ2d* _result = new ::gp_Circ2d(); *_result = ((::Adaptor2d_OffsetCurve*)_NativeInstance)->Circle(); return _result==nullptr ? nullptr : gcnew Macad::Occt::gp_Circ2d(_result); } Macad::Occt::gp_Elips2d^ Macad::Occt::Adaptor2d_OffsetCurve::Ellipse() { ::gp_Elips2d* _result = new ::gp_Elips2d(); *_result = ((::Adaptor2d_OffsetCurve*)_NativeInstance)->Ellipse(); return _result==nullptr ? nullptr : gcnew Macad::Occt::gp_Elips2d(_result); } Macad::Occt::gp_Hypr2d^ Macad::Occt::Adaptor2d_OffsetCurve::Hyperbola() { ::gp_Hypr2d* _result = new ::gp_Hypr2d(); *_result = ((::Adaptor2d_OffsetCurve*)_NativeInstance)->Hyperbola(); return _result==nullptr ? nullptr : gcnew Macad::Occt::gp_Hypr2d(_result); } Macad::Occt::gp_Parab2d^ Macad::Occt::Adaptor2d_OffsetCurve::Parabola() { ::gp_Parab2d* _result = new ::gp_Parab2d(); *_result = ((::Adaptor2d_OffsetCurve*)_NativeInstance)->Parabola(); return _result==nullptr ? nullptr : gcnew Macad::Occt::gp_Parab2d(_result); } int Macad::Occt::Adaptor2d_OffsetCurve::Degree() { return ((::Adaptor2d_OffsetCurve*)_NativeInstance)->Degree(); } bool Macad::Occt::Adaptor2d_OffsetCurve::IsRational() { return ((::Adaptor2d_OffsetCurve*)_NativeInstance)->IsRational(); } int Macad::Occt::Adaptor2d_OffsetCurve::NbPoles() { return ((::Adaptor2d_OffsetCurve*)_NativeInstance)->NbPoles(); } int Macad::Occt::Adaptor2d_OffsetCurve::NbKnots() { return ((::Adaptor2d_OffsetCurve*)_NativeInstance)->NbKnots(); } Macad::Occt::Geom2d_BezierCurve^ Macad::Occt::Adaptor2d_OffsetCurve::Bezier() { Handle(::Geom2d_BezierCurve) _result; _result = ((::Adaptor2d_OffsetCurve*)_NativeInstance)->Bezier(); return _result.IsNull() ? nullptr : Macad::Occt::Geom2d_BezierCurve::CreateDowncasted( _result.get()); } Macad::Occt::Geom2d_BSplineCurve^ Macad::Occt::Adaptor2d_OffsetCurve::BSpline() { Handle(::Geom2d_BSplineCurve) _result; _result = ((::Adaptor2d_OffsetCurve*)_NativeInstance)->BSpline(); return _result.IsNull() ? nullptr : Macad::Occt::Geom2d_BSplineCurve::CreateDowncasted( _result.get()); } int Macad::Occt::Adaptor2d_OffsetCurve::NbSamples() { return ((::Adaptor2d_OffsetCurve*)_NativeInstance)->NbSamples(); } //--------------------------------------------------------------------- // Class Adaptor2d_HOffsetCurve //--------------------------------------------------------------------- Macad::Occt::Adaptor2d_HOffsetCurve::Adaptor2d_HOffsetCurve() : Macad::Occt::Adaptor2d_HCurve2d(BaseClass::InitMode::Uninitialized) { NativeInstance = new ::Adaptor2d_HOffsetCurve(); } Macad::Occt::Adaptor2d_HOffsetCurve::Adaptor2d_HOffsetCurve(Macad::Occt::Adaptor2d_OffsetCurve^ C) : Macad::Occt::Adaptor2d_HCurve2d(BaseClass::InitMode::Uninitialized) { NativeInstance = new ::Adaptor2d_HOffsetCurve(*(::Adaptor2d_OffsetCurve*)C->NativeInstance); } Macad::Occt::Adaptor2d_HOffsetCurve::Adaptor2d_HOffsetCurve(Macad::Occt::Adaptor2d_HOffsetCurve^ parameter1) : Macad::Occt::Adaptor2d_HCurve2d(BaseClass::InitMode::Uninitialized) { NativeInstance = new ::Adaptor2d_HOffsetCurve(*(::Adaptor2d_HOffsetCurve*)parameter1->NativeInstance); } void Macad::Occt::Adaptor2d_HOffsetCurve::Set(Macad::Occt::Adaptor2d_OffsetCurve^ C) { ((::Adaptor2d_HOffsetCurve*)_NativeInstance)->Set(*(::Adaptor2d_OffsetCurve*)C->NativeInstance); } Macad::Occt::Adaptor2d_Curve2d^ Macad::Occt::Adaptor2d_HOffsetCurve::Curve2d() { ::Adaptor2d_Curve2d* _result = new ::Adaptor2d_Curve2d(); *_result = (::Adaptor2d_Curve2d)((::Adaptor2d_HOffsetCurve*)_NativeInstance)->Curve2d(); return _result==nullptr ? nullptr : gcnew Macad::Occt::Adaptor2d_Curve2d(_result); } Macad::Occt::Adaptor2d_OffsetCurve^ Macad::Occt::Adaptor2d_HOffsetCurve::ChangeCurve2d() { ::Adaptor2d_OffsetCurve* _result = new ::Adaptor2d_OffsetCurve(); *_result = ((::Adaptor2d_HOffsetCurve*)_NativeInstance)->ChangeCurve2d(); return _result==nullptr ? nullptr : gcnew Macad::Occt::Adaptor2d_OffsetCurve(_result); } Macad::Occt::Adaptor2d_HOffsetCurve^ Macad::Occt::Adaptor2d_HOffsetCurve::CreateDowncasted(::Adaptor2d_HOffsetCurve* instance) { return gcnew Macad::Occt::Adaptor2d_HOffsetCurve( instance ); }
36.158549
149
0.70358
zhyifei
e1847fd3c0b4dbbdeaef8b0f2c16acb4801ba59f
5,782
cpp
C++
cegui/src/Clipboard.cpp
OpenTechEngine-Libraries/CEGUI
6f00952d31f318f9482766d1ad2206cb540a78b9
[ "MIT" ]
57
2015-05-15T11:42:42.000Z
2022-03-24T06:13:17.000Z
cegui/src/Clipboard.cpp
OpenTechEngine-Libraries/CEGUI
6f00952d31f318f9482766d1ad2206cb540a78b9
[ "MIT" ]
null
null
null
cegui/src/Clipboard.cpp
OpenTechEngine-Libraries/CEGUI
6f00952d31f318f9482766d1ad2206cb540a78b9
[ "MIT" ]
22
2015-05-07T16:17:22.000Z
2019-12-18T05:58:41.000Z
/*********************************************************************** created: 28/5/2011 author: Martin Preisler purpose: Implements platform independent clipboard handling *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team * * 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 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 "CEGUI/Clipboard.h" // Start of CEGUI namespace section namespace CEGUI { NativeClipboardProvider::~NativeClipboardProvider() {} //----------------------------------------------------------------------------// Clipboard::Clipboard(): d_mimeType("text/plain"), // reasonable default I think d_buffer(0), d_bufferSize(0), d_nativeProvider(0) {} //----------------------------------------------------------------------------// Clipboard::~Clipboard() { if (d_buffer != 0) { delete[] d_buffer; } } //----------------------------------------------------------------------------// void Clipboard::setNativeProvider(NativeClipboardProvider* provider) { d_nativeProvider = provider; } //----------------------------------------------------------------------------// NativeClipboardProvider* Clipboard::getNativeProvider() const { return d_nativeProvider; } //----------------------------------------------------------------------------// void Clipboard::setData(const String& mimeType, const void* buffer, size_t size) { d_mimeType = mimeType; if (size != d_bufferSize) { if (d_buffer != 0) { delete[] d_buffer; d_buffer = 0; } d_bufferSize = size; d_buffer = new BufferElement[d_bufferSize]; } memcpy(d_buffer, buffer, d_bufferSize); // we have set the data to the internal clipboard, now sync it with the // system-wide native clipboard if possible if (d_nativeProvider) { d_nativeProvider->sendToClipboard(d_mimeType, d_buffer, d_bufferSize); } } //----------------------------------------------------------------------------// void Clipboard::getData(String& mimeType, const void*& buffer, size_t& size) { // first make sure we are in sync with system-wide native clipboard // (if possible) if (d_nativeProvider) { size_t retrievedSize; void* retrievedBuffer; d_nativeProvider->retrieveFromClipboard(d_mimeType, retrievedBuffer, retrievedSize); if (retrievedSize != d_bufferSize) { if (d_buffer != 0) { delete[] d_buffer; d_buffer = 0; } d_bufferSize = retrievedSize; d_buffer = new BufferElement[d_bufferSize]; } memcpy(d_buffer, retrievedBuffer, retrievedSize); } mimeType = d_mimeType; buffer = d_buffer; size = d_bufferSize; } //----------------------------------------------------------------------------// void Clipboard::setText(const String& text) { // could be just ASCII if std::string is used as CEGUI::String const char* utf8_bytes = text.c_str(); // we don't want the actual string length, that might not be the buffer size // in case of utf8! // this gets us the number of bytes until \0 is encountered const size_t size = strlen(utf8_bytes); setData("text/plain", static_cast<const void*>(utf8_bytes), size); } //----------------------------------------------------------------------------// String Clipboard::getText() { String mimeType; const void* buffer; size_t size; // we have to use this, can't use the member variables directly because of // the native clipboard provider! getData(mimeType, buffer, size); if (mimeType == "text/plain" && size != 0) { // d_buffer an utf8 or ASCII C string (ASCII if std::string is used) // !!! However it is not null terminated !!! So we have to tell String // how many code units (not code points!) there are. #if CEGUI_STRING_CLASS == CEGUI_STRING_CLASS_UNICODE return String(reinterpret_cast<const utf8*>(d_buffer), d_bufferSize); #else return String(static_cast<const char*>(d_buffer), d_bufferSize); #endif } else { // the held mime type differs, it's not plain text so we can't // return it as just string return String(); } } //----------------------------------------------------------------------------// } // End of CEGUI namespace section
33.229885
92
0.538741
OpenTechEngine-Libraries
e187145fafc793349bf9fdf956120825e3cae7ea
3,536
cc
C++
diagnostics/dpsl/internal/dpsl_thread_context_impl.cc
strassek/chromiumos-platform2
12c953f41f48b8a6b0bd1c181d09bdb1de38325c
[ "BSD-3-Clause" ]
4
2020-07-24T06:54:16.000Z
2021-06-16T17:13:53.000Z
diagnostics/dpsl/internal/dpsl_thread_context_impl.cc
strassek/chromiumos-platform2
12c953f41f48b8a6b0bd1c181d09bdb1de38325c
[ "BSD-3-Clause" ]
1
2021-04-02T17:35:07.000Z
2021-04-02T17:35:07.000Z
diagnostics/dpsl/internal/dpsl_thread_context_impl.cc
strassek/chromiumos-platform2
12c953f41f48b8a6b0bd1c181d09bdb1de38325c
[ "BSD-3-Clause" ]
1
2020-11-04T22:31:45.000Z
2020-11-04T22:31:45.000Z
// Copyright 2018 The Chromium OS 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 "diagnostics/dpsl/internal/dpsl_thread_context_impl.h" #include <utility> #include <base/lazy_instance.h> #include <base/location.h> #include <base/logging.h> #include <base/threading/thread_local.h> #include <base/threading/thread_task_runner_handle.h> #include <base/time/time.h> #include "diagnostics/dpsl/internal/callback_utils.h" namespace diagnostics { namespace { // Whether an instance of DpslThreadContextImpl was created on the current // thread. base::LazyInstance<base::ThreadLocalBoolean>::Leaky g_thread_context_impl_created = LAZY_INSTANCE_INITIALIZER; } // namespace // static void DpslThreadContextImpl::CleanThreadCounterForTesting() { g_thread_context_impl_created.Pointer()->Set(false); } DpslThreadContextImpl::DpslThreadContextImpl() : thread_id_(base::PlatformThread::CurrentId()), // Initialize the SingleThreadTaskExecutor only if there's no TaskRunner // yet (it could be already set up by the calling code via other means, // e.g., brillo::Daemon). owned_task_executor_( base::ThreadTaskRunnerHandle::IsSet() ? nullptr : std::make_unique<base::SingleThreadTaskExecutor>( base::MessagePumpType::IO)), task_runner_(base::ThreadTaskRunnerHandle::Get()) {} DpslThreadContextImpl::~DpslThreadContextImpl() { CHECK(sequence_checker_.CalledOnValidSequence()) << "Called from wrong thread"; } bool DpslThreadContextImpl::BelongsToCurrentThread() { return base::PlatformThread::CurrentId() == thread_id_; } void DpslThreadContextImpl::RunEventLoop() { CHECK(sequence_checker_.CalledOnValidSequence()) << "Called from wrong thread"; CHECK(!base::RunLoop::IsRunningOnCurrentThread()) << "Called from already running message loop"; CHECK(!current_run_loop_); base::RunLoop run_loop; current_run_loop_ = &run_loop; run_loop.Run(); current_run_loop_ = nullptr; } bool DpslThreadContextImpl::IsEventLoopRunning() { CHECK(sequence_checker_.CalledOnValidSequence()) << "Called from wrong thread"; return current_run_loop_ != nullptr; } void DpslThreadContextImpl::PostTask(std::function<void()> task) { task_runner_->PostTask(FROM_HERE, MakeCallbackFromStdFunction(std::move(task))); } void DpslThreadContextImpl::PostDelayedTask(std::function<void()> task, int64_t delay_milliseconds) { CHECK_GE(delay_milliseconds, 0) << "Delay must be non-negative"; task_runner_->PostDelayedTask( FROM_HERE, MakeCallbackFromStdFunction(std::move(task)), base::TimeDelta::FromMilliseconds(delay_milliseconds)); } void DpslThreadContextImpl::QuitEventLoop() { CHECK(sequence_checker_.CalledOnValidSequence()) << "Called from wrong thread"; if (current_run_loop_) current_run_loop_->Quit(); } // static std::unique_ptr<DpslThreadContext> DpslThreadContext::Create( DpslGlobalContext* global_context) { CHECK(global_context) << "GlobalContext is nullptr"; // Verify we're not called twice on the current thread. CHECK(!g_thread_context_impl_created.Pointer()->Get()) << "Duplicate DpslThreadContext instances constructed on the same thread"; g_thread_context_impl_created.Pointer()->Set(true); return std::make_unique<DpslThreadContextImpl>(); } } // namespace diagnostics
31.855856
80
0.731335
strassek
e1872723f039006da4b07196cad3e3e9f20bab9e
761
hpp
C++
include/dish2/peripheral/readable_state/introspective_state/ResourceStockpile.hpp
schregardusc/dishtiny
b0b1841a457a955fa4c22f36a050d91f12484f9e
[ "MIT" ]
1
2021-02-12T23:53:55.000Z
2021-02-12T23:53:55.000Z
include/dish2/peripheral/readable_state/introspective_state/ResourceStockpile.hpp
schregardusc/dishtiny
b0b1841a457a955fa4c22f36a050d91f12484f9e
[ "MIT" ]
null
null
null
include/dish2/peripheral/readable_state/introspective_state/ResourceStockpile.hpp
schregardusc/dishtiny
b0b1841a457a955fa4c22f36a050d91f12484f9e
[ "MIT" ]
null
null
null
#pragma once #ifndef DISH2_PERIPHERAL_READABLE_STATE_INTROSPECTIVE_STATE_RESOURCESTOCKPILE_HPP_INCLUDE #define DISH2_PERIPHERAL_READABLE_STATE_INTROSPECTIVE_STATE_RESOURCESTOCKPILE_HPP_INCLUDE #include "../../../../../third-party/conduit/include/uitsl/datastructs/PodLeafNode.hpp" #include "../../../../../third-party/conduit/include/uitsl/meta/TypeName.hpp" namespace dish2 { struct ResourceStockpile : public uitsl::PodLeafNode<float> { // inherit constructors using parent_t = uitsl::PodLeafNode<float>; using parent_t::parent_t; }; } // namespace dish2 namespace uitsl { UITSL_ENABLE_TYPENAME( dish2::ResourceStockpile ); } // namespace uitsl #endif // #ifndef DISH2_PERIPHERAL_READABLE_STATE_INTROSPECTIVE_STATE_RESOURCESTOCKPILE_HPP_INCLUDE
30.44
99
0.802891
schregardusc
e18818fff813361483e7842f2c94687a3b6647ae
704
cpp
C++
windows/src/test/manual-tests/test_i2908/i2908/stdafx.cpp
srl295/keyman
4dfd0f71f3f4ccf81d1badbd824900deee1bb6d1
[ "MIT" ]
219
2017-06-21T03:37:03.000Z
2022-03-27T12:09:28.000Z
windows/src/test/manual-tests/test_i2908/i2908/stdafx.cpp
srl295/keyman
4dfd0f71f3f4ccf81d1badbd824900deee1bb6d1
[ "MIT" ]
4,451
2017-05-29T02:52:06.000Z
2022-03-31T23:53:23.000Z
windows/src/test/manual-tests/test_i2908/i2908/stdafx.cpp
srl295/keyman
4dfd0f71f3f4ccf81d1badbd824900deee1bb6d1
[ "MIT" ]
72
2017-05-26T04:08:37.000Z
2022-03-03T10:26:20.000Z
/* Name: stdafx Copyright: Copyright (C) 2003-2017 SIL International. Documentation: Description: Create Date: 28 Jun 2011 Modified Date: 28 Jun 2011 Authors: mcdurdin Related Files: Dependencies: Bugs: Todo: Notes: History: 28 Jun 2011 - mcdurdin - I2908 - Fix double-strike characters */ // stdafx.cpp : source file that includes just the standard includes // i2908.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h" // TODO: reference any additional headers you need in STDAFX.H // and not in this file
27.076923
81
0.62358
srl295
e189593b28f70587cb413a088631a6bce990f455
833
cpp
C++
UAlbertaBot/Source/strategies/protoss/DarkTemplarRush.cpp
kant2002/ualbertabot
b4c75be8bf023f289f2e58e49ad600a9bda38fcd
[ "MIT" ]
2
2017-07-06T18:27:41.000Z
2018-03-14T06:19:43.000Z
UAlbertaBot/Source/strategies/protoss/DarkTemplarRush.cpp
kant2002/ualbertabot
b4c75be8bf023f289f2e58e49ad600a9bda38fcd
[ "MIT" ]
18
2017-10-29T20:37:47.000Z
2019-08-25T16:01:28.000Z
UAlbertaBot/Source/strategies/protoss/DarkTemplarRush.cpp
kant2002/ualbertabot
b4c75be8bf023f289f2e58e49ad600a9bda38fcd
[ "MIT" ]
1
2017-09-13T07:02:23.000Z
2017-09-13T07:02:23.000Z
#include "DarkTemplarRush.h" #include "..\..\UnitUtil.h" using UAlbertaBot::MetaPairVector; using UAlbertaBot::MetaPair; using UAlbertaBot::UnitUtil::GetAllUnitCount; AKBot::DarkTemplarRush::DarkTemplarRush(BWAPI::Player self) : _self(self) { } void AKBot::DarkTemplarRush::getBuildOrderGoal(MetaPairVector& goal, int currentFrame) const { int numDragoons = GetAllUnitCount(_self, BWAPI::UnitTypes::Protoss_Dragoon); int numNexusAll = GetAllUnitCount(_self, BWAPI::UnitTypes::Protoss_Nexus); int numDarkTeplar = GetAllUnitCount(_self, BWAPI::UnitTypes::Protoss_Dark_Templar); goal.push_back(MetaPair(BWAPI::UnitTypes::Protoss_Dark_Templar, numDarkTeplar + 2)); // if we have a 2nd nexus then get some goons out if (numNexusAll >= 2) { goal.push_back(MetaPair(BWAPI::UnitTypes::Protoss_Dragoon, numDragoons + 4)); } }
30.851852
92
0.77431
kant2002
e18a7f00e225b168bb40fc8abd06d9cca70c28c8
422
hpp
C++
toy_compiler/munster/ast/op/assign_op.hpp
Wmbat/toy_compiler
370a2e76aaaa874de5fb6c25e0755638dd84b8b4
[ "MIT" ]
null
null
null
toy_compiler/munster/ast/op/assign_op.hpp
Wmbat/toy_compiler
370a2e76aaaa874de5fb6c25e0755638dd84b8b4
[ "MIT" ]
null
null
null
toy_compiler/munster/ast/op/assign_op.hpp
Wmbat/toy_compiler
370a2e76aaaa874de5fb6c25e0755638dd84b8b4
[ "MIT" ]
null
null
null
#pragma once #include <toy_compiler/munster/ast/op/op.hpp> namespace munster::ast { class assign_op : public op { public: using ptr = std::unique_ptr<assign_op>; public: assign_op(node_ptr val_0, node_ptr id_decl, node_ptr val_1); void accept(visitor_variant &visitor) const override; [[nodiscard]] auto to_string() const -> std::string override; }; } // namespace munster::ast
21.1
67
0.680095
Wmbat
e18bc9c979aba4446d9350ecabb781c2d4c78e3f
3,886
cpp
C++
src/sim/Cache/ZCacheV2.cpp
heyyod/AttilaSimulator
cf9bcaa8c86dee378abbfb5967896dd9a1ab5ce1
[ "BSD-3-Clause" ]
null
null
null
src/sim/Cache/ZCacheV2.cpp
heyyod/AttilaSimulator
cf9bcaa8c86dee378abbfb5967896dd9a1ab5ce1
[ "BSD-3-Clause" ]
null
null
null
src/sim/Cache/ZCacheV2.cpp
heyyod/AttilaSimulator
cf9bcaa8c86dee378abbfb5967896dd9a1ab5ce1
[ "BSD-3-Clause" ]
null
null
null
/************************************************************************** * * Copyright (c) 2002 - 2011 by Computer Architecture Department, * Universitat Politecnica de Catalunya. * All rights reserved. * * The contents of this file may not b;e disclosed to third parties, * copied or duplicated in any form, in whole or in part, without the * prior permission of the authors, Computer Architecture Department * and Universitat Politecnica de Catalunya. * * $RCSfile: ZCacheV2.cpp,v $ * $Revision: 1.5 $ * $Author: vmoya $ * $Date: 2008-03-02 19:09:17 $ * * Z Cache class implementation file. * */ /** * * @file ZCacheV2.cpp * * Implements the Z Cache class. This class the cache used for access to the Z buffer in a GPU. * */ #include "ZCacheV2.h" #include "GPUMath.h" #include "FragmentOpEmulator.h" using namespace gpu3d; // Z Cache class counter. Used to create identifiers for the created Z Caches // that are then used to access the Memory Controller. u32bit ZCacheV2::cacheCounter = 0; // Z cache constructor. ZCacheV2::ZCacheV2(u32bit ways, u32bit lines, u32bit lineSz, u32bit readP, u32bit writeP, u32bit pWidth, u32bit reqQSize, u32bit inReqs, u32bit outReqs, bool zComprDisabled, u32bit numStampUnits, u32bit stampUnitStride, u32bit maxZBlocks, u32bit blocksPerCycle, u32bit compCycles, u32bit decompCycles, char *postfix #if KONDAMASK_CACHE_DECAY , u32bit decayInterval #endif ) : ROPCache(ways, lines, lineSz, readP, writeP, pWidth, reqQSize, inReqs, outReqs, zComprDisabled, numStampUnits, stampUnitStride, maxZBlocks, blocksPerCycle, compCycles, decompCycles, ZSTENCILTEST, "ZCache", postfix #if KONDAMASK_CACHE_DECAY , decayInterval #endif ) { // Get the Z Cache identifier. cacheID = cacheCounter; // Update the number of created Z Caches. cacheCounter++; // Set reset value for clear. for (u32bit i = 0; i < (MAX_BYTES_PER_PIXEL >> 2); i++) ((u32bit *) clearResetValue)[i] = 0x00ffffff; } // Clears the Z cache. bool ZCacheV2::clear(u32bit depth, u8bit stencil) { // Reset the cache. if (clearMode) { // Check clear cycles remaining. if (clearCycles > 0) { // Update clear cycles. clearCycles--; // Check if end of clear. if (clearCycles == 0) { // Set the clear value registers. clearDepth = depth; clearStencil = stencil; // Set the ROP data clear value ((u32bit *) clearROPValue)[0] = (clearStencil << 24) | (clearDepth & 0x00ffffff); /* Unset reset mode. */ clearMode = FALSE; } } } else { // NOTE: SHOULD TAKE INTO ACCOUNT THE RESOLUTION SO NOT ALL // BLOCKS HAD TO BE CLEARED EVEN IF UNUSED AT CURRENT RESOLUTION. // Set clear cycles. clearCycles = (u32bit) ceil((f32bit) maxBlocks / (f32bit) blocksCycle); // Set clear mode. clearMode = TRUE; // Reset the cache. resetMode = TRUE; } return clearMode; } // Check HZ updates. bool ZCacheV2::updateHZ(u32bit &block, u32bit &z) { // Check if there is an updated block. if (blockWasWritten) { // Return block identifier and block Z. block = writtenBlock; z = wrBlockMaxVal; // Reset updated HZ block flag. blockWasWritten = false; return true; } else return false; } void ZCacheV2::processNextWrittenBlock(u8bit* outputBuffer, u32bit size) { u32bit* data = (u32bit*) outputBuffer; u32bit dataSize = size / sizeof(u32bit); u32bit maxZ; // Calculate the maximum depth/Z. FragmentOpEmulator::blockMaxZ(data, dataSize, maxZ); // Store for later use wrBlockMaxVal = maxZ; } // Copies the block state memory. void ZCacheV2::copyBlockStateMemory(ROPBlockState *buffer, u32bit blocks) { GPU_ASSERT( if (blocks > maxBlocks) panic("ZCache", "copyBlockSateMemory", "More blocks to copy than blocks in the state memory."); ) // Copy the block states. memcpy(buffer, blockState, sizeof(ROPBlockState) * blocks); }
24.136646
125
0.687597
heyyod
e18be70802221c41be6b90dbf9aa54796449175d
1,504
hpp
C++
library/range.hpp
shibasis0801/showcase
265e94130e567efd3625650bfd9592eb465ffd5e
[ "MIT" ]
null
null
null
library/range.hpp
shibasis0801/showcase
265e94130e567efd3625650bfd9592eb465ffd5e
[ "MIT" ]
null
null
null
library/range.hpp
shibasis0801/showcase
265e94130e567efd3625650bfd9592eb465ffd5e
[ "MIT" ]
null
null
null
#include "printer.hpp" #ifndef RANGE_HPP #define RANGE_HPP struct range { int start; int stop; int stride; range(int start, int stop) : start(start), stop(stop), stride(1) {} range(int start, int stop, int stride) : start(start), stop(stop), stride(stride) {} struct iterator; iterator begin() { return iterator(start, stride, stride > 0); } iterator end() { return iterator(stop, stride, stride > 0); } range step(int stride) { if (stride < 0) return range(stop, start, stride * this->stride); else return range(start, stop, stride * this->stride); } struct iterator { int value; bool increasing = true; int step = 1; iterator(int value, int step, bool increasing) : value(value), step(step), increasing(increasing) {} iterator &operator=(int element) { value = element; return *this; } // Prefix iterator &operator++() { value += step; return *this; } // Postfix iterator operator++(int) { auto temp = iterator(value, this->step, increasing); value += step; return temp; } bool operator!=(const iterator &iter) { return increasing ? value < iter.value : value > iter.value; } int operator*() { return value; } }; }; #endif
22.447761
108
0.522606
shibasis0801
e18c0b85c91b24131d254205f3ca587b8c9ba794
3,214
hpp
C++
Include/Injector/Engine.hpp
InjectorGames/Inject
09e74a83c287b81fd8272c10d6bae2b1aa785c0e
[ "BSD-3-Clause" ]
2
2019-12-10T16:26:58.000Z
2020-04-17T11:47:42.000Z
Include/Injector/Engine.hpp
InjectorGames/Inject
09e74a83c287b81fd8272c10d6bae2b1aa785c0e
[ "BSD-3-Clause" ]
28
2020-08-17T12:39:50.000Z
2020-11-16T20:42:50.000Z
Include/Injector/Engine.hpp
InjectorGames/InjectorEngine
09e74a83c287b81fd8272c10d6bae2b1aa785c0e
[ "BSD-3-Clause" ]
null
null
null
#pragma once #include "Injector/Defines.hpp" #include "Injector/ECS/EcsManager.hpp" #include "Injector/Mathematics/Matrix4.hpp" #include "Injector/Graphics/GraphicsAPI.hpp" #include <chrono> namespace Injector { class Engine final { private: static bool engineInitialized; static bool networkInitialized; static bool graphicsInitialized; static bool virtualRealityInitialized; static bool updateRunning; static bool capUpdateRate; static int targetUpdateRate; static std::chrono::steady_clock:: time_point updateStartTick; static double updateStartTime; static double updateDeltaTime; static GraphicsAPI graphicsAPI; static FloatMatrix4 hmdModelMatrix; static FloatMatrix4 leftEyeModelMatrix; static FloatMatrix4 rightEyeModelMatrix; static FloatMatrix4 leftEyeProjMatrix; static FloatMatrix4 rightEyeProjMatrix; static std::vector<std::shared_ptr<EcsManager>> managers; public: static bool getCapUpdateRate() noexcept; static void setCapUpdateRate(bool cap = true) noexcept; static int getTargetUpdateRate() noexcept; static void setTargetUpdateRate(int ups = 60) noexcept; static std::chrono::steady_clock:: time_point getUpdateStartTick() noexcept; static double getUpdateStartTime() noexcept; static double getUpdateDeltaTime() noexcept; static void initializeEngine( int majorVersion = INJECTOR_VERSION_MAJOR, int minorVersion = INJECTOR_VERSION_MINOR, int patchVersion = INJECTOR_VERSION_PATCH); static void terminateEngine(); static bool isEngineInitialized() noexcept; static void initializeNetwork(); static void terminateNetwork(); static bool isNetworkInitialized(); static void glfwErrorCallback( int error, const char* description); static void initializeGraphics( GraphicsAPI graphicsAPI = GraphicsAPI::OpenGL); static void terminateGraphics(); static bool isGraphicsInitialized() noexcept; static void initializeVirtualReality(); static void terminateVirtualReality(); static bool isVirtualRealityInitialized() noexcept; static void startUpdateLoop(); static void stopUpdateLoop() noexcept; static bool getUpdateRunning() noexcept; static std::chrono::steady_clock:: time_point getTickNow() noexcept; static double getTimeNow() noexcept; static GraphicsAPI getGraphicsAPI() noexcept; static const FloatMatrix4& getHmdModelMatrix() noexcept; static const FloatMatrix4& getLeftEyeModelMatrix() noexcept; static const FloatMatrix4& getRightEyeModelMatrix() noexcept; static const FloatMatrix4& getLeftEyeProjMatrix() noexcept; static const FloatMatrix4& getRightEyeProjMatrix() noexcept; static bool addManager( const std::shared_ptr<EcsManager>& manager) noexcept; static bool removeManager( const std::shared_ptr<EcsManager>& manager) noexcept; static bool containsManager( const std::shared_ptr<EcsManager>& manager) noexcept; static void removeManagers() noexcept; static size_t getManagerCount() noexcept; template<class T = EcsManager, class ...Args> static std::shared_ptr<T> createManager(Args... args) noexcept { auto manager = std::make_shared<T>(args...); managers.push_back(manager); return manager; } }; }
30.903846
64
0.780647
InjectorGames
e18e7a47b50ebb9e3ebd0b6d16fea63bd85063e2
17,049
cpp
C++
src/materialsystem/stdshaders_old/spritecard.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
6
2022-01-23T09:40:33.000Z
2022-03-20T20:53:25.000Z
src/materialsystem/stdshaders_old/spritecard.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
null
null
null
src/materialsystem/stdshaders_old/spritecard.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
1
2022-02-06T21:05:23.000Z
2022-02-06T21:05:23.000Z
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: shader for drawing sprites as cards, with animation frame lerping // // $Header: $ // $NoKeywords: $ //===========================================================================// #include "BaseVSShader.h" #include "convar.h" // STDSHADER_DX9_DLL_EXPORT #include "spritecard_ps20.inc" #include "spritecard_ps20b.inc" #include "spritecard_vs20.inc" #include "splinecard_vs20.inc" #if SUPPORT_DX8 // STDSHADER_DX8_DLL_EXPORT #include "spritecard_vs11.inc" #include "spritecard_ps11.inc" #include "splinecard_vs11.inc" #endif #include "tier0/icommandline.h" //command line // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" #define DEFAULT_PARTICLE_FEATHERING_ENABLED 1 #ifdef STDSHADER_DX8_DLL_EXPORT DEFINE_FALLBACK_SHADER( Spritecard, Spritecard_DX8 ) #endif int GetDefaultDepthFeatheringValue( void ) //Allow the command-line to go against the default soft-particle value { static int iRetVal = -1; if( iRetVal == -1 ) { # if( DEFAULT_PARTICLE_FEATHERING_ENABLED == 1 ) { if( CommandLine()->CheckParm( "-softparticlesdefaultoff" ) ) iRetVal = 0; else iRetVal = 1; } # else { if( CommandLine()->CheckParm( "-softparticlesdefaulton" ) ) iRetVal = 1; else iRetVal = 0; } # endif } // On low end parts on the Mac, we reduce particles and shut off depth blending here static ConVarRef mat_reduceparticles( "mat_reduceparticles" ); if ( mat_reduceparticles.GetBool() ) { iRetVal = 0; } return iRetVal; } #ifdef STDSHADER_DX9_DLL_EXPORT BEGIN_VS_SHADER_FLAGS( Spritecard, "Help for Spritecard", SHADER_NOT_EDITABLE ) #else BEGIN_VS_SHADER_FLAGS( Spritecard_DX8, "Help for Spritecard_DX8", SHADER_NOT_EDITABLE ) #endif BEGIN_SHADER_PARAMS SHADER_PARAM( DEPTHBLEND, SHADER_PARAM_TYPE_INTEGER, "0", "fade at intersection boundaries" ) SHADER_PARAM( DEPTHBLENDSCALE, SHADER_PARAM_TYPE_FLOAT, "50.0", "Amplify or reduce DEPTHBLEND fading. Lower values make harder edges." ) SHADER_PARAM( ORIENTATION, SHADER_PARAM_TYPE_INTEGER, "0", "0 = always face camera, 1 = rotate around z, 2= parallel to ground" ) SHADER_PARAM( ADDBASETEXTURE2, SHADER_PARAM_TYPE_FLOAT, "0.0", "amount to blend second texture into frame by" ) SHADER_PARAM( OVERBRIGHTFACTOR, SHADER_PARAM_TYPE_FLOAT, "1.0", "overbright factor for texture. For HDR effects.") SHADER_PARAM( DUALSEQUENCE, SHADER_PARAM_TYPE_INTEGER, "0", "blend two separate animated sequences.") SHADER_PARAM( SEQUENCE_BLEND_MODE, SHADER_PARAM_TYPE_INTEGER, "0", "defines the blend mode between the images un dual sequence particles. 0 = avg, 1=alpha from first, rgb from 2nd, 2= first over second" ) SHADER_PARAM( MAXLUMFRAMEBLEND1, SHADER_PARAM_TYPE_INTEGER, "0", "instead of blending between animation frames for the first sequence, select pixels based upon max luminance" ) SHADER_PARAM( MAXLUMFRAMEBLEND2, SHADER_PARAM_TYPE_INTEGER, "0", "instead of blending between animation frames for the 2nd sequence, select pixels based upon max luminance" ) SHADER_PARAM( RAMPTEXTURE, SHADER_PARAM_TYPE_TEXTURE, "", "if specified, then the red value of the image is used to index this ramp to produce the output color" ) SHADER_PARAM( ZOOMANIMATESEQ2, SHADER_PARAM_TYPE_FLOAT, "1.0", "amount to gradually zoom between frames on the second sequence. 2.0 will double the size of a frame over its lifetime.") SHADER_PARAM( EXTRACTGREENALPHA, SHADER_PARAM_TYPE_INTEGER, "0", "grayscale data sitting in green/alpha channels") SHADER_PARAM( ADDOVERBLEND, SHADER_PARAM_TYPE_INTEGER, "0", "use ONE:INVSRCALPHA blending") SHADER_PARAM( ADDSELF, SHADER_PARAM_TYPE_FLOAT, "0.0", "amount of base texture to additively blend in" ) SHADER_PARAM( BLENDFRAMES, SHADER_PARAM_TYPE_BOOL, "1", "whether or not to smoothly blend between animated frames" ) SHADER_PARAM( MINSIZE, SHADER_PARAM_TYPE_FLOAT, "0.0", "minimum screen fractional size of particle") SHADER_PARAM( STARTFADESIZE, SHADER_PARAM_TYPE_FLOAT, "10.0", "screen fractional size to start fading particle out") SHADER_PARAM( ENDFADESIZE, SHADER_PARAM_TYPE_FLOAT, "20.0", "screen fractional size to finish fading particle out") SHADER_PARAM( MAXSIZE, SHADER_PARAM_TYPE_FLOAT, "20.0", "maximum screen fractional size of particle") SHADER_PARAM( USEINSTANCING, SHADER_PARAM_TYPE_BOOL, "1", "whether to use GPU vertex instancing (submit 1 vert per particle quad)") SHADER_PARAM( SPLINETYPE, SHADER_PARAM_TYPE_INTEGER, "0", "spline type 0 = none, 1=ctamull rom") SHADER_PARAM( MAXDISTANCE, SHADER_PARAM_TYPE_FLOAT, "100000.0", "maximum distance to draw particles at") SHADER_PARAM( FARFADEINTERVAL, SHADER_PARAM_TYPE_FLOAT, "400.0", "interval over which to fade out far away particles") END_SHADER_PARAMS SHADER_INIT_PARAMS() { INIT_FLOAT_PARM( MAXDISTANCE, 100000.0); INIT_FLOAT_PARM( FARFADEINTERVAL, 400.0); INIT_FLOAT_PARM( MAXSIZE, 20.0 ); INIT_FLOAT_PARM( ENDFADESIZE, 20.0 ); INIT_FLOAT_PARM( STARTFADESIZE, 10.0 ); INIT_FLOAT_PARM( DEPTHBLENDSCALE, 50.0 ); INIT_FLOAT_PARM( OVERBRIGHTFACTOR, 1.0 ); INIT_FLOAT_PARM( ADDBASETEXTURE2, 0.0 ); INIT_FLOAT_PARM( ADDSELF, 0.0 ); INIT_FLOAT_PARM( ZOOMANIMATESEQ2, 0.0 ); if ( !params[DEPTHBLEND]->IsDefined() ) { params[ DEPTHBLEND ]->SetIntValue( GetDefaultDepthFeatheringValue() ); } if ( !g_pHardwareConfig->SupportsPixelShaders_2_b() ) { params[ DEPTHBLEND ]->SetIntValue( 0 ); } if ( !params[DUALSEQUENCE]->IsDefined() ) { params[DUALSEQUENCE]->SetIntValue( 0 ); } if ( !params[MAXLUMFRAMEBLEND1]->IsDefined() ) { params[MAXLUMFRAMEBLEND1]->SetIntValue( 0 ); } if ( !params[MAXLUMFRAMEBLEND2]->IsDefined() ) { params[MAXLUMFRAMEBLEND2]->SetIntValue( 0 ); } if ( !params[EXTRACTGREENALPHA]->IsDefined() ) { params[EXTRACTGREENALPHA]->SetIntValue( 0 ); } if ( !params[ADDOVERBLEND]->IsDefined() ) { params[ADDOVERBLEND]->SetIntValue( 0 ); } if ( !params[BLENDFRAMES]->IsDefined() ) { params[ BLENDFRAMES ]->SetIntValue( 1 ); } if ( !params[USEINSTANCING]->IsDefined() ) { params[ USEINSTANCING ]->SetIntValue( IsX360() ? 1 : 0 ); } SET_FLAGS2( MATERIAL_VAR2_IS_SPRITECARD ); } SHADER_FALLBACK { #ifdef STDSHADER_DX9_DLL_EXPORT if ( g_pHardwareConfig->GetDXSupportLevel() < 90 ) return "SpriteCard_DX8"; #endif #ifdef STDSHADER_DX8_DLL_EXPORT // STDSHADER_DX8_DLL_EXPORT if ( g_pHardwareConfig->GetDXSupportLevel() < 80 ) return "Wireframe"; #endif return 0; } SHADER_INIT { #ifdef STDSHADER_DX9_DLL_EXPORT const bool bDX8 = false; #endif #ifdef STDSHADER_DX8_DLL_EXPORT const bool bDX8 = true; #endif SET_FLAGS2( MATERIAL_VAR2_LIGHTING_VERTEX_LIT ); if ( params[BASETEXTURE]->IsDefined() ) { bool bExtractGreenAlpha = false; if ( params[EXTRACTGREENALPHA]->IsDefined() ) { bExtractGreenAlpha = params[EXTRACTGREENALPHA]->GetIntValue() != 0; } LoadTexture( BASETEXTURE, !bExtractGreenAlpha && !bDX8 ? TEXTUREFLAGS_SRGB : 0 ); } if ( params[RAMPTEXTURE]->IsDefined() ) { LoadTexture( RAMPTEXTURE, TEXTUREFLAGS_SRGB ); } } SHADER_DRAW { #ifdef STDSHADER_DX9_DLL_EXPORT const bool bDX8 = false; #endif #ifdef STDSHADER_DX8_DLL_EXPORT const bool bDX8 = true; #endif bool bUseRampTexture = (! bDX8 ) && ( params[RAMPTEXTURE]->IsDefined() ); bool bZoomSeq2 = (! bDX8 ) && ( ( params[ZOOMANIMATESEQ2]->GetFloatValue()) > 1.0 ); bool bDepthBlend = (! bDX8 ) && ( params[DEPTHBLEND]->GetIntValue() != 0 ); bool bAdditive2ndTexture = params[ADDBASETEXTURE2]->GetFloatValue() != 0.0; int nSplineType = params[SPLINETYPE]->GetIntValue(); SHADOW_STATE { bool bSecondSequence = params[DUALSEQUENCE]->GetIntValue() != 0; bool bAddOverBlend = params[ADDOVERBLEND]->GetIntValue() != 0; bool bExtractGreenAlpha = (! bDX8 ) && ( params[EXTRACTGREENALPHA]->GetIntValue() != 0 ); bool bBlendFrames = (! bDX8 ) && ( params[BLENDFRAMES]->GetIntValue() != 0 ); if ( nSplineType ) { bBlendFrames = false; } bool bAddSelf = params[ADDSELF]->GetFloatValue() != 0.0; bool bUseInstancing = IsX360() ? ( params[ USEINSTANCING ]->GetIntValue() != 0 ) : false; if ( nSplineType ) bUseInstancing = false; // draw back-facing because of yaw spin pShaderShadow->EnableCulling( false ); // Be sure not to write to dest alpha pShaderShadow->EnableAlphaWrites( false ); pShaderShadow->EnableTexture( SHADER_SAMPLER0, true ); if ( bDX8 ) pShaderShadow->EnableTexture( SHADER_SAMPLER1, true ); if ( bAdditive2ndTexture && bDX8 ) pShaderShadow->EnableTexture( SHADER_SAMPLER3, true ); if ( bUseRampTexture ) { pShaderShadow->EnableTexture( SHADER_SAMPLER1, true ); pShaderShadow->EnableSRGBRead( SHADER_SAMPLER1, true ); } if ( bDepthBlend ) { pShaderShadow->EnableTexture( SHADER_SAMPLER2, true ); } if ( bAdditive2ndTexture || bAddSelf ) pShaderShadow->EnableAlphaTest( false ); else pShaderShadow->EnableAlphaTest( true ); pShaderShadow->AlphaFunc( SHADER_ALPHAFUNC_GREATER, 0.01f ); if ( bAdditive2ndTexture || bAddOverBlend || bAddSelf ) { EnableAlphaBlending( SHADER_BLEND_ONE, SHADER_BLEND_ONE_MINUS_SRC_ALPHA ); } else { if ( IS_FLAG_SET(MATERIAL_VAR_ADDITIVE) ) { EnableAlphaBlending( SHADER_BLEND_SRC_ALPHA, SHADER_BLEND_ONE ); } else { EnableAlphaBlending( SHADER_BLEND_SRC_ALPHA, SHADER_BLEND_ONE_MINUS_SRC_ALPHA ); } } unsigned int flags = VERTEX_POSITION | VERTEX_COLOR; static int s_TexCoordSize[8]={4, // 0 = sheet bounding uvs, frame0 4, // 1 = sheet bounding uvs, frame 1 4, // 2 = frame blend, rot, radius, ??? 2, // 3 = corner identifier ( 0/0,1/0,1/1, 1/0 ) 4, // 4 = texture 2 bounding uvs 4, // 5 = second sequence bounding uvs, frame0 4, // 6 = second sequence bounding uvs, frame1 4, // 7 = second sequence frame blend, ?,?,? }; static int s_TexCoordSizeSpline[]={4, // 0 = sheet bounding uvs, frame0 4, // 1 = sheet bounding uvs, frame 1 4, // 2 = frame blend, rot, radius, ??? 4, // 3 = corner identifier ( 0/0,1/0,1/1, 1/0 ) 4, // 4 = texture 2 bounding uvs 4, // 5 = second sequence bounding uvs, frame0 4, // 6 = second sequence bounding uvs, frame1 4, // 7 = second sequence frame blend, ?,?,? }; int numTexCoords = 4; if ( true /* bAdditive2ndTexture */ ) // there is no branch for 2nd texture in the VS! -henryg { numTexCoords = 5; } if ( bSecondSequence ) { // the whole shebang - 2 sequences, with a possible multi-image sequence first numTexCoords = 8; } pShaderShadow->VertexShaderVertexFormat( flags, numTexCoords, nSplineType? s_TexCoordSizeSpline : s_TexCoordSize, 0 ); if ( bDX8 ) { #if SUPPORT_DX8 if ( nSplineType ) { DECLARE_STATIC_VERTEX_SHADER( splinecard_vs11 ); SET_STATIC_VERTEX_SHADER( splinecard_vs11 ); } else { DECLARE_STATIC_VERTEX_SHADER( spritecard_vs11 ); if ( bSecondSequence ) bAdditive2ndTexture = false; SET_STATIC_VERTEX_SHADER_COMBO( DUALSEQUENCE, false ); SET_STATIC_VERTEX_SHADER_COMBO( ZOOM_ANIMATE_SEQ2, false ); SET_STATIC_VERTEX_SHADER_COMBO( EXTRACTGREENALPHA, bExtractGreenAlpha ); SET_STATIC_VERTEX_SHADER( spritecard_vs11 ); } DECLARE_STATIC_PIXEL_SHADER( spritecard_ps11 ); SET_STATIC_PIXEL_SHADER_COMBO( ADDBASETEXTURE2, bAdditive2ndTexture ); SET_STATIC_PIXEL_SHADER_COMBO( ADDSELF, bAddSelf ); SET_STATIC_PIXEL_SHADER_COMBO( USEALPHAASRGB, bSecondSequence ); SET_STATIC_PIXEL_SHADER( spritecard_ps11 ); #endif } else { if ( nSplineType ) { DECLARE_STATIC_VERTEX_SHADER( splinecard_vs20 ); SET_STATIC_VERTEX_SHADER( splinecard_vs20 ); } else { DECLARE_STATIC_VERTEX_SHADER( spritecard_vs20 ); SET_STATIC_VERTEX_SHADER_COMBO( DUALSEQUENCE, bSecondSequence ); SET_STATIC_VERTEX_SHADER_COMBO( ZOOM_ANIMATE_SEQ2, bZoomSeq2 ); SET_STATIC_VERTEX_SHADER_COMBO( EXTRACTGREENALPHA, bExtractGreenAlpha ); SET_STATIC_VERTEX_SHADER_COMBO( USE_INSTANCING, bUseInstancing ); SET_STATIC_VERTEX_SHADER( spritecard_vs20 ); } if( g_pHardwareConfig->SupportsPixelShaders_2_b() ) { DECLARE_STATIC_PIXEL_SHADER( spritecard_ps20b ); SET_STATIC_PIXEL_SHADER_COMBO( ADDBASETEXTURE2, bAdditive2ndTexture ); SET_STATIC_PIXEL_SHADER_COMBO( ADDSELF, bAddSelf ); SET_STATIC_PIXEL_SHADER_COMBO( ANIMBLEND, bBlendFrames ); SET_STATIC_PIXEL_SHADER_COMBO( DUALSEQUENCE, bSecondSequence ); SET_STATIC_PIXEL_SHADER_COMBO( SEQUENCE_BLEND_MODE, bSecondSequence ? params[SEQUENCE_BLEND_MODE]->GetIntValue() : 0 ); SET_STATIC_PIXEL_SHADER_COMBO( MAXLUMFRAMEBLEND1, params[MAXLUMFRAMEBLEND1]->GetIntValue() ); SET_STATIC_PIXEL_SHADER_COMBO( MAXLUMFRAMEBLEND2, bSecondSequence? params[MAXLUMFRAMEBLEND1]->GetIntValue() : 0 ); SET_STATIC_PIXEL_SHADER_COMBO( COLORRAMP, bUseRampTexture ); SET_STATIC_PIXEL_SHADER_COMBO( EXTRACTGREENALPHA, bExtractGreenAlpha ); SET_STATIC_PIXEL_SHADER_COMBO( DEPTHBLEND, bDepthBlend ); SET_STATIC_PIXEL_SHADER( spritecard_ps20b ); } else { DECLARE_STATIC_PIXEL_SHADER( spritecard_ps20 ); SET_STATIC_PIXEL_SHADER_COMBO( ADDBASETEXTURE2, bAdditive2ndTexture ); SET_STATIC_PIXEL_SHADER_COMBO( DUALSEQUENCE, bSecondSequence ); SET_STATIC_PIXEL_SHADER_COMBO( ADDSELF, bAddSelf ); SET_STATIC_PIXEL_SHADER_COMBO( ANIMBLEND, bBlendFrames ); SET_STATIC_PIXEL_SHADER_COMBO( SEQUENCE_BLEND_MODE, bSecondSequence ? params[SEQUENCE_BLEND_MODE]->GetIntValue() : 0 ); SET_STATIC_PIXEL_SHADER_COMBO( MAXLUMFRAMEBLEND1, params[MAXLUMFRAMEBLEND1]->GetIntValue() ); SET_STATIC_PIXEL_SHADER_COMBO( MAXLUMFRAMEBLEND2, bSecondSequence? params[MAXLUMFRAMEBLEND1]->GetIntValue() : 0 ); SET_STATIC_PIXEL_SHADER_COMBO( COLORRAMP, bUseRampTexture ); SET_STATIC_PIXEL_SHADER_COMBO( EXTRACTGREENALPHA, bExtractGreenAlpha ); SET_STATIC_PIXEL_SHADER( spritecard_ps20 ); } if ( !bDX8 ) pShaderShadow->EnableSRGBWrite( true ); if( !bExtractGreenAlpha && !bDX8 ) pShaderShadow->EnableSRGBRead( SHADER_SAMPLER0, true ); } } DYNAMIC_STATE { BindTexture( SHADER_SAMPLER0, BASETEXTURE, FRAME ); if ( bDX8 ) // bind on 2nd sampelr so we can lerp BindTexture( SHADER_SAMPLER1, BASETEXTURE, FRAME ); if ( bDX8 && bAdditive2ndTexture ) BindTexture( SHADER_SAMPLER3, BASETEXTURE, FRAME ); if ( bUseRampTexture && ( !bDX8 ) ) { BindTexture( SHADER_SAMPLER1, RAMPTEXTURE, FRAME ); } if ( bDepthBlend ) { pShaderAPI->BindStandardTexture( SHADER_SAMPLER2, TEXTURE_FRAME_BUFFER_FULL_DEPTH ); } LoadViewportTransformScaledIntoVertexShaderConstant( VERTEX_SHADER_SHADER_SPECIFIC_CONST_10 ); int nOrientation = params[ORIENTATION]->GetIntValue(); nOrientation = clamp( nOrientation, 0, 2 ); // We need these only when screen-orienting if ( nOrientation == 0 ) { LoadModelViewMatrixIntoVertexShaderConstant( VERTEX_SHADER_SHADER_SPECIFIC_CONST_0 ); LoadProjectionMatrixIntoVertexShaderConstant( VERTEX_SHADER_SHADER_SPECIFIC_CONST_3 ); } if ( bZoomSeq2 ) { float flZScale=1.0/(params[ZOOMANIMATESEQ2]->GetFloatValue()); float C0[4]={ (float)(0.5*(1.0+flZScale)), flZScale, 0, 0 }; pShaderAPI->SetVertexShaderConstant( VERTEX_SHADER_SHADER_SPECIFIC_CONST_7, C0, ARRAYSIZE(C0)/4 ); } // set fade constants in vsconsts 8 and 9 float flMaxDistance = params[MAXDISTANCE]->GetFloatValue(); float flStartFade = max( 1.f, flMaxDistance - params[FARFADEINTERVAL]->GetFloatValue() ); float VC0[8]={ params[MINSIZE]->GetFloatValue(), params[MAXSIZE]->GetFloatValue(), params[STARTFADESIZE]->GetFloatValue(), params[ENDFADESIZE]->GetFloatValue(), flStartFade, (float)(1.0/(flMaxDistance-flStartFade)), 0,0 }; pShaderAPI->SetVertexShaderConstant( VERTEX_SHADER_SHADER_SPECIFIC_CONST_8, VC0, ARRAYSIZE(VC0)/4 ); pShaderAPI->SetDepthFeatheringPixelShaderConstant( 2, params[DEPTHBLENDSCALE]->GetFloatValue() ); float C0[4]={ params[ADDBASETEXTURE2]->GetFloatValue(), params[OVERBRIGHTFACTOR]->GetFloatValue(), params[ADDSELF]->GetFloatValue(), 0.0f }; if ( bDX8 && ( !bAdditive2ndTexture ) ) // deal with 0..1 limit for pix shader constants { C0[2] *= 0.25; C0[1] *= 0.25; } pShaderAPI->SetPixelShaderConstant( 0, C0, ARRAYSIZE(C0)/4 ); if ( g_pHardwareConfig->GetDXSupportLevel() < 90 ) { #if SUPPORT_DX8 if ( nSplineType ) { DECLARE_DYNAMIC_VERTEX_SHADER( splinecard_vs11 ); SET_DYNAMIC_VERTEX_SHADER( splinecard_vs11 ); } else { DECLARE_DYNAMIC_VERTEX_SHADER( spritecard_vs11 ); SET_DYNAMIC_VERTEX_SHADER_COMBO( ORIENTATION, nOrientation ); SET_DYNAMIC_VERTEX_SHADER( spritecard_vs11 ); } #endif } else { if ( nSplineType ) { DECLARE_DYNAMIC_VERTEX_SHADER( splinecard_vs20 ); SET_DYNAMIC_VERTEX_SHADER( splinecard_vs20 ); } else { DECLARE_DYNAMIC_VERTEX_SHADER( spritecard_vs20 ); SET_DYNAMIC_VERTEX_SHADER_COMBO( ORIENTATION, nOrientation ); SET_DYNAMIC_VERTEX_SHADER( spritecard_vs20 ); } } } Draw( ); } END_SHADER
35.152577
204
0.732301
cstom4994
e18ec119b1fb0ececf03a6f69e01433c8ca7ce5e
156
cpp
C++
src/xtd.forms.native.fltk/src/xtd/forms/native/fltk/tab_page.cpp
ExternalRepositories/xtd
5889d69900ad22a00fcb640d7850a1d599cf593a
[ "MIT" ]
251
2019-04-20T02:02:24.000Z
2022-03-31T09:52:08.000Z
src/xtd.forms.native.fltk/src/xtd/forms/native/fltk/tab_page.cpp
leanid/xtd
2e1ea6537218788ca08901faf8915d4100990b53
[ "MIT" ]
29
2021-01-07T12:52:12.000Z
2022-03-29T08:42:14.000Z
src/xtd.forms.native.fltk/src/xtd/forms/native/fltk/tab_page.cpp
leanid/xtd
2e1ea6537218788ca08901faf8915d4100990b53
[ "MIT" ]
27
2019-11-21T02:37:44.000Z
2022-03-30T22:59:14.000Z
#include <xtd/forms/native/tab_page.hpp> #include "fl_tab_page.hpp" using namespace xtd; using namespace xtd::drawing; using namespace xtd::forms::native;
22.285714
40
0.782051
ExternalRepositories
e18ee0fdc9dbb4bc476f0c69cd051f01fa24f5aa
1,039
cpp
C++
tmp/main.cpp
adrs0049/AdhesionRandomWalk
25d9d805261be504a61a1d9ae329559f346fe95a
[ "MIT" ]
null
null
null
tmp/main.cpp
adrs0049/AdhesionRandomWalk
25d9d805261be504a61a1d9ae329559f346fe95a
[ "MIT" ]
null
null
null
tmp/main.cpp
adrs0049/AdhesionRandomWalk
25d9d805261be504a61a1d9ae329559f346fe95a
[ "MIT" ]
null
null
null
#include <iostream> #include <functional> #include <vector> #include <map> #include <string> #include <utility> #include "Event.h" #include "EventListener.h" using namespace std; class Foo { public: Foo() {} Event<int> event; void setValue(int i) { value = i; event.notifyListeners(i); } private: int value; }; class Moo { public: Moo(Foo *f) { f->event.registerSyncValue(syncVal); eventListener = f->event.createListener([](int v) { cout << "Value is "<<v+1<<endl; }); } SyncValue<int> syncVal; private: EventListener<int> eventListener; }; int main(int argc, const char * argv[]) { Foo f; { Moo m(&f); f.setValue(123); cout << "synched value " << m.syncVal.getValue() << endl; f.setValue(12); cout << "synched value " << m.syncVal.getValue() << endl; } f.setValue(1234); return 0; }
18.553571
65
0.512031
adrs0049
e190c80de46583cab915b6dd4796b5b97d980c09
21,189
cpp
C++
DetectorDescription/Parser/test/testDoc.cpp
pasmuss/cmssw
566f40c323beef46134485a45ea53349f59ae534
[ "Apache-2.0" ]
null
null
null
DetectorDescription/Parser/test/testDoc.cpp
pasmuss/cmssw
566f40c323beef46134485a45ea53349f59ae534
[ "Apache-2.0" ]
null
null
null
DetectorDescription/Parser/test/testDoc.cpp
pasmuss/cmssw
566f40c323beef46134485a45ea53349f59ae534
[ "Apache-2.0" ]
null
null
null
#include <stdlib.h> #include <exception> #include <iostream> #include <string> #include <utility> #include <vector> #include "DetectorDescription/Core/interface/DDCompactView.h" #include "DetectorDescription/Core/interface/DDExpandedNode.h" #include "DetectorDescription/Core/interface/DDExpandedView.h" #include "DetectorDescription/Core/interface/DDLogicalPart.h" #include "DetectorDescription/Core/interface/DDMaterial.h" #include "DetectorDescription/Core/interface/DDName.h" #include "DetectorDescription/Core/interface/DDRoot.h" #include "DetectorDescription/Core/interface/DDSolid.h" #include "DetectorDescription/Core/interface/DDTransform.h" #include "DetectorDescription/Core/src/DDCheck.h" #include "DetectorDescription/Parser/interface/DDLDocumentProvider.h" #include "DetectorDescription/Parser/interface/DDLParser.h" #include "DetectorDescription/Parser/interface/DDLSAX2ConfigHandler.h" #include "DetectorDescription/Parser/interface/DDLSAX2Handler.h" #include "FWCore/PluginManager/interface/PluginManager.h" #include "FWCore/PluginManager/interface/standard.h" #include "FWCore/Utilities/interface/Exception.h" #include "Utilities/Xerces/interface/XercesStrUtils.h" #include "xercesc/util/XMLException.hpp" #include "xercesc/util/XercesVersion.hpp" using namespace cms::xerces; class DDLTestDoc : public DDLDocumentProvider { public: DDLTestDoc( void ); ~DDLTestDoc() override; /// Return a list of files as a vector of strings. const std::vector < std::string >& getFileList( void ) const override; /// Return a list of urls as a vector of strings. const std::vector < std::string >& getURLList( void ) const override; /// Print out the list of files. void dumpFileList( void ) const override; /// Return whether Validation should be on or off and where the DDL SchemaLocation is. bool doValidation( void ) const override; /// Return the designation for where to look for the schema. std::string getSchemaLocation( void ) const override; /// ReadConfig int readConfig( const std::string& filename ) override; void emplace_back( const std::string& fileName, const std::string& url = std::string( "./" )); void setSchemaLocation( std::string path = std::string( "../../DDSchema" )); void setValidation( bool val ); void clear( void ); private: std::vector < std::string > fnames_; std::vector < std::string > urls_; std::string schemaLoc_; bool validate_; }; //-------------------------------------------------------------------------- // DDLTestDoc: Default constructor and destructor. //-------------------------------------------------------------------------- DDLTestDoc::~DDLTestDoc( void ) { } DDLTestDoc::DDLTestDoc( void ) : validate_(true) { schemaLoc_ = "http://www.cern.ch/cms/DDL ../../Schema/DDLSchema.xsd"; } const std::vector<std::string>& DDLTestDoc::getFileList( void ) const { return fnames_; } const std::vector<std::string>& DDLTestDoc::getURLList( void ) const { return urls_; } void DDLTestDoc::emplace_back( const std::string& fileName, const std::string& url ) { fnames_.emplace_back(fileName); urls_.emplace_back(url); } void DDLTestDoc::setValidation( bool val ) { validate_= val; } bool DDLTestDoc::doValidation( void ) const { return validate_; } void DDLTestDoc::setSchemaLocation( std::string path ) { schemaLoc_ = std::move(path); } std::string DDLTestDoc::getSchemaLocation( void ) const { std::cout << schemaLoc_ << std::endl; return schemaLoc_; } void DDLTestDoc::dumpFileList( void ) const { std::cout << "File List:" << std::endl; std::vector<std::string> vst = getFileList(); std::cout << " number of files=" << vst.size() << std::endl; for (std::vector<std::string>::const_iterator it = vst.begin(); it != vst.end(); ++it) std::cout << *it << std::endl; } void DDLTestDoc::clear( void ) { fnames_.clear(); urls_.clear(); } //----------------------------------------------------------------------- // Here the Xerces parser is used to process the content of the // configuration file. // FIX: Right now, each config file passed to this will simply increase the // size of the list of files. So if this default DDLDocumentProvider is // called repeatedly (i.e. the same instance of it) then the file list MAY // repeat files. It is the Parser which checks for maintains a list of real // files. //----------------------------------------------------------------------- int DDLTestDoc::readConfig( const std::string& filename ) { std::cout << "readConfig" << std::endl; // Set the parser to use the handler for the configuration file. // This makes sure the Parser is initialized and gets a handle to it. DDCompactView cpv; DDLParser parser(cpv); DDLSAX2Handler* errHandler; DDLSAX2ConfigHandler * sch; sch = new DDLSAX2ConfigHandler(cpv); errHandler = new DDLSAX2Handler; parser.getXMLParser()->setContentHandler(sch); parser.getXMLParser()->setErrorHandler(errHandler); try { parser.getXMLParser()->parse(filename.c_str()); } catch (const XERCES_CPP_NAMESPACE::XMLException& toCatch) { std::cout << "\nXMLException: parsing '" << filename << "'\n" << "Exception message is: \n" << cStr(toCatch.getMessage()).ptr() << "\n" ; return 1; } catch (...) { std::cout << "\nUnexpected exception during parsing: '" << filename << "'\n"; return 3; } fnames_ = sch->getFileNames(); urls_ = sch->getURLs(); std::cout << "there are " << fnames_.size() << " files." << std::endl; for (size_t i = 0; i < fnames_.size(); ++i) std::cout << "url=" << urls_[i] << " file=" << fnames_[i] << std::endl; return 0; } void testRotations( void ) { std::cout << "--------------- Parser testing Rotations --------------" << std::endl; std::cout << "z30 should be a rotation of 30 degrees around the z axis:" << std::endl; std::cout << DDRotation(DDName( "z30", "testRotations")) << std::endl; std::cout << std::endl; std::cout << "z30x20 should be a rotation 30 degrees around z, then 20 degrees around x:" << std::endl; std::cout << DDRotation(DDName( "z30x20", "testRotations")) << std::endl; std::cout << std::endl; std::cout << "x90y45 should be a rotation 90 degrees around x, then 45 degrees around y:" << std::endl; std::cout << DDRotation(DDName( "x90y45", "testRotations")) << std::endl; std::cout << std::endl; std::cout << "x90y90 should be a rotation 90 degrees around x, then 90 degrees around y:" << std::endl; std::cout << DDRotation(DDName( "x90y90", "testRotations")) << std::endl; std::cout << std::endl; std::cout << "x90y135 should be a rotation 90 degrees around x, then 135 degrees around y:" << std::endl; std::cout << DDRotation(DDName( "x90y135", "testRotations")) << std::endl; std::cout << std::endl; std::cout << "x90y180 should be a rotation 90 degrees around x, then 180 degrees around y:" << std::endl; std::cout << DDRotation(DDName( "x90y180", "testRotations")) << std::endl; std::cout << std::endl; std::cout << "x90 should be a rotation of 90 degrees around the x axis:" << std::endl; std::cout << DDRotation(DDName( "x90", "testRotations")) << std::endl; std::cout << std::endl; std::cout << "cmsimIdentity makes the identity rotation matrix using the cmsim method (phi and theta of each axis):" << std::endl; std::cout << DDRotation(DDName("cmsimIdentity", "testRotations")) << std::endl; std::cout << std::endl; std::cout << "newrotIdentity makes the identity rotation matrix by rotating 0 degrees around the z axis:" << std::endl; std::cout << DDRotation(DDName("newrotIdentity", "testRotations")) << std::endl; std::cout << std::endl; std::cout << "180R should be a REFLECTION rotation. It is defined using the cmsim way:" << std::endl; std::cout << DDRotation(DDName("180R", "testRotations")) << std::endl; std::cout << std::endl; } void testMaterials() { std::cout << "--------------- Parser testing Materials --------------" << std::endl; std::cout << "There should be 4 Elementary Materials: Nitrogen," << std::endl; std::cout << "Oxygen,Argon and Hydrogen. There should be one composite" << std::endl; std::cout << " material:Air, made up of those 4 components." << std::endl; std::cout << DDMaterial(DDName("Nitrogen", "testMaterials")) << std::endl; std::cout << std::endl; std::cout << DDMaterial(DDName("Oxygen", "testMaterials")) << std::endl; std::cout << std::endl; std::cout << DDMaterial(DDName("Argon", "testMaterials")) << std::endl; std::cout << std::endl; std::cout << DDMaterial(DDName("Hydrogen", "testMaterials")) << std::endl; std::cout << std::endl; std::cout << DDMaterial(DDName("Air", "testMaterials")) << std::endl; std::cout << std::endl; } void testSolids( void ) { std::cout << "--------------- Parser testing Solids --------------" << std::endl; std::cout << "trap1 is a trapezoid:" << std::endl; std::cout << DDSolid(DDName("trap1", "testSolids")) << std::endl; std::cout << std::endl; std::cout << "trap2 is a trapezoid with more symmetry:" << std::endl; std::cout << DDSolid(DDName("trap2", "testSolids")) << std::endl; std::cout << std::endl; std::cout << "ptrap1 is a pseudo Trapezoid with atMinusZ=false:" << std::endl; std::cout << DDSolid(DDName("ptrap1", "testSolids")) << std::endl; std::cout << std::endl; std::cout << "ptrap2 is a psuedo Trapezoid with atMinusZ=true:" << std::endl; std::cout << DDSolid(DDName("ptrap2", "testSolids")) << std::endl; std::cout << std::endl; std::cout << "box1 is a Box:" << std::endl; std::cout << DDSolid(DDName("box1", "testSolids")) << std::endl; std::cout << std::endl; std::cout << "cone1 is a conical section (full 360 degree):" << std::endl; std::cout << DDSolid(DDName("cone1", "testSolids")) << std::endl; std::cout << std::endl; std::cout << "cone2 is a conical section (full 360 degree) which is actually a tube:" << std::endl; std::cout << DDSolid(DDName("cone2", "testSolids")) << std::endl; std::cout << std::endl; std::cout << "cone2hole is a conical section (20 degree):" << std::endl; std::cout << DDSolid(DDName("cone2hole", "testSolids")) << std::endl; std::cout << std::endl; std::cout << "pczsect is a polycone defined using z-sections:" << std::endl; std::cout << DDSolid(DDName("pczsect", "testSolids")) << std::endl; std::cout << std::endl; std::cout << "pcrz is a polycone defined using r & z points:" << std::endl; std::cout << DDSolid(DDName("pcrz", "testSolids")) << std::endl; std::cout << std::endl; std::cout << "phzsect is a polyhedra defined using z-sections:" << std::endl; std::cout << DDSolid(DDName("phzsect", "testSolids")) << std::endl; std::cout << std::endl; std::cout << "phrz is a polyhedra defined using r & z points:" << std::endl; std::cout << DDSolid(DDName("phrz", "testSolids")) << std::endl; std::cout << std::endl; std::cout << "trd1 is a \"special\" trapezoid declaration with fewer" ; std::cout << " parameters (Trd1):" << std::endl; std::cout << DDSolid(DDName("trd1", "testSolids")) << std::endl; std::cout << std::endl; std::cout << "trd2 is a \"special\" trapezoid declaration with fewer" ; std::cout << " parameters (Trd1):" << std::endl; std::cout << DDSolid(DDName("trd2", "testSolids")) << std::endl; std::cout << std::endl; std::cout << "tube1 is a tube:" << std::endl; std::cout << DDSolid(DDName("tube1", "testSolids")) << std::endl; std::cout << std::endl; std::cout << "tube2 is a tubs(Tube Section):" << std::endl; std::cout << DDSolid(DDName("tube2", "testSolids")) << std::endl; std::cout << std::endl; std::cout << "trunctubs1 is a trunctubs(Cut or truncated Tube Section):" << std::endl; std::cout << DDSolid(DDName("trunctubs1", "testSolids")) << std::endl; std::cout << std::endl; std::cout << "momma is a shapeless solid, a way of \"grouping\" things:" << std::endl; std::cout << DDSolid(DDName("momma", "testSolids")) << std::endl; std::cout << std::endl; std::cout << "MotherOfAllBoxes is a box and is the root's solid:" << std::endl; std::cout << DDSolid(DDName("MotherOfAllBoxes", "testSolids")) << std::endl; std::cout << std::endl; std::cout << "trd2mirror is a ReflectionSolid of trd2:" << std::endl; std::cout << DDSolid(DDName("trd2mirror", "testSolids")) << std::endl; std::cout << std::endl; std::cout << "subsolid is a subtraction solid, cone2-cone2hole:" << std::endl; std::cout << DDSolid(DDName("subsolid", "testSolids")) << std::endl; std::cout << std::endl; std::cout << "unionsolid is a union of pcrz and cone1:" << std::endl; std::cout << DDSolid(DDName("unionsolid", "testSolids")) << std::endl; std::cout << std::endl; std::cout << "intsolid is an Intersection(Solid) of cone1 and cone2:" << std::endl; std::cout << DDSolid(DDName("intsolid", "testSolids")) << std::endl; std::cout << std::endl; std::cout << "cuttubs is a Cut tubs solid:" << std::endl; std::cout << DDSolid(DDName("cuttubs", "testSolids")) << std::endl; std::cout << std::endl; std::cout << "extrudedpgon is an Extruded Polygone solid:" << std::endl; std::cout << DDSolid(DDName("extrudedpgon", "testSolids")) << std::endl; std::cout << std::endl; std::cout << "verify parameters interface\nx: "; DDExtrudedPolygon extrPgon(DDSolid(DDName("extrudedpgon", "testSolids"))); std::vector<double> x = extrPgon.xVec(); std::vector<double> y = extrPgon.yVec(); std::vector<double> z = extrPgon.zVec(); std::vector<double> zx = extrPgon.zxVec(); std::vector<double> zy = extrPgon.zyVec(); std::vector<double> zs = extrPgon.zscaleVec(); for( auto i : x ) std::cout << i << ", "; std::cout << "\ny: "; for( auto i : y ) std::cout << i << ", "; std::cout << "\nz: "; for( auto i : z ) std::cout << i << ", "; std::cout << "\nzx: "; for( auto i : zx ) std::cout << i << ", "; std::cout << "\nzy: "; for( auto i : zy ) std::cout << i << ", "; std::cout << "\nz scale: "; for( auto i : zs ) std::cout << i << ", "; std::cout << std::endl; std::cout << "multiunionsolid is a Multi Union solid:" << std::endl; std::cout << DDSolid(DDName("multiunionsolid", "testSolids")) << std::endl; std::cout << std::endl; std::cout << "verify parameters interface\n"; DDMultiUnion multiUnion(DDSolid(DDName("multiunionsolid", "testSolids"))); std::cout << " Solids:\n"; for( auto s : multiUnion.solids()) std::cout << s << "\n"; for( auto t : multiUnion.translations()) std::cout << t << "\n"; for( auto r : multiUnion.rotations()) std::cout << r << "\n"; } void testLogicalParts( void ) { std::cout << "--------------- Parser testing LogicalParts --------------" << std::endl; std::cout << "LogicalPart trap1:" << std::endl; std::cout << DDLogicalPart(DDName("trap1", "testLogicalParts")) << std::endl; std::cout << std::endl; std::cout << "LogicalPart trap2:" << std::endl; std::cout << DDLogicalPart(DDName("trap2", "testLogicalParts")) << std::endl; std::cout << std::endl; std::cout << "LogicalPart ptrap1:" << std::endl; std::cout << DDLogicalPart(DDName("ptrap1", "testLogicalParts")) << std::endl; std::cout << std::endl; std::cout << "LogicalPart ptrap2:" << std::endl; std::cout << DDLogicalPart(DDName("ptrap2", "testLogicalParts")) << std::endl; std::cout << std::endl; std::cout << "LogicalPart box1:" << std::endl; std::cout << DDLogicalPart(DDName("box1", "testLogicalParts")) << std::endl; std::cout << std::endl; std::cout << "LogicalPart cone1:" << std::endl; std::cout << DDLogicalPart(DDName("cone1", "testLogicalParts")) << std::endl; std::cout << std::endl; std::cout << "LogicalPart cone2:" << std::endl; std::cout << DDLogicalPart(DDName("cone2", "testLogicalParts")) << std::endl; std::cout << std::endl; std::cout << "LogicalPart cone2hole:" << std::endl; std::cout << DDLogicalPart(DDName("cone2hole", "testLogicalParts")) << std::endl; std::cout << std::endl; std::cout << "LogicalPart pczsect:" << std::endl; std::cout << DDLogicalPart(DDName("pczsect", "testLogicalParts")) << std::endl; std::cout << std::endl; std::cout << "LogicalPart pcrz:" << std::endl; std::cout << DDLogicalPart(DDName("pcrz", "testLogicalParts")) << std::endl; std::cout << std::endl; std::cout << "LogicalPart phzsect:" << std::endl; std::cout << DDLogicalPart(DDName("phzsect", "testLogicalParts")) << std::endl; std::cout << std::endl; std::cout << "LogicalPart phrz:" << std::endl; std::cout << DDLogicalPart(DDName("phrz", "testLogicalParts")) << std::endl; std::cout << std::endl; std::cout << "LogicalPart trd1:" ; std::cout << DDLogicalPart(DDName("trd1", "testLogicalParts")) << std::endl; std::cout << std::endl; std::cout << "LogicalPart trd2:" << std::endl; std::cout << DDLogicalPart(DDName("trd2", "testLogicalParts")) << std::endl; std::cout << std::endl; std::cout << "LogicalPart tube1:" << std::endl; std::cout << DDLogicalPart(DDName("tube1", "testLogicalParts")) << std::endl; std::cout << std::endl; std::cout << "LogicalPart tube2:" << std::endl; std::cout << DDLogicalPart(DDName("tube2", "testLogicalParts")) << std::endl; std::cout << std::endl; std::cout << "LogicalPart trunctubs1:" << std::endl; std::cout << DDLogicalPart(DDName("trunctubs1", "testLogicalParts")) << std::endl; std::cout << std::endl; std::cout << "LogicalPart momma:" << std::endl; std::cout << DDLogicalPart(DDName("momma", "testLogicalParts")) << std::endl; std::cout << std::endl; std::cout << "LogicalPart MotherOfAllBoxes:" << std::endl; std::cout << DDLogicalPart(DDName("MotherOfAllBoxes", "testLogicalParts")) << std::endl; std::cout << std::endl; std::cout << "LogicalPart torus:" << std::endl; std::cout << DDLogicalPart(DDName("torus", "testLogicalParts")) << std::endl; std::cout << std::endl; std::cout << "LogicalPart trd2mirror:" << std::endl; std::cout << DDLogicalPart(DDName("trd2mirror", "testLogicalParts")) << std::endl; std::cout << std::endl; std::cout << "LogicalPart subsolid:" << std::endl; std::cout << DDLogicalPart(DDName("subsolid", "testLogicalParts")) << std::endl; std::cout << std::endl; std::cout << "LogicalPart unionsolid:" << std::endl; std::cout << DDLogicalPart(DDName("unionsolid", "testLogicalParts")) << std::endl; std::cout << std::endl; std::cout << "LogicalPart intsolid:" << std::endl; std::cout << DDLogicalPart(DDName("intsolid", "testLogicalParts")) << std::endl; std::cout << std::endl; } int main(int argc, char *argv[]) { std::string const kProgramName = argv[0]; int rc = 0; if (argc < 2 || argc > 2 ) { std::cout << "This is a polite exit so that scram b runtests' first run of this program does not give an error" << std::endl; exit(0); // SUCCESS; } try { edmplugin::PluginManager::configure(edmplugin::standard::config()); std::cout << "Initialize a DDL parser " << std::endl; DDCompactView cpv; DDLParser myP(cpv); if ( argc == 2 ) { DDLTestDoc dp; dp.readConfig(argv[1]); dp.dumpFileList(); std::cout << "About to start parsing..." << std::endl; myP.parse(dp); std::cout << "Completed Parser" << std::endl; std::cout << std::endl << std::endl << "Start checking!" << std::endl << std::endl; std::cout << "Call DDCheckMaterials and other DDChecks." << std::endl; DDCheckMaterials(std::cout); std::cout << "======== Navigate a little bit ======" << std::endl; try { if (!cpv.root().isDefined().second) { cpv.setRoot(DDRootDef::instance().root()); } DDExpandedView ev(cpv); while (ev.next()) { std::cout << ev.geoHistory() << std::endl; } } catch (cms::Exception& e) { std::cout << e.what() << std::endl; } std::cout << "--------------- Parser testing started --------------" << std::endl; std::cout << std::endl << "Run the XML tests." << std::endl; testMaterials(); testRotations(); testSolids(); testLogicalParts(); } else if (argc < 3) { // scram b runtests for now this should not work. // just to have something! DDRootDef::instance().set(DDName("LP1", "testNoSections")); std::string fname = std::string(argv[1]); DDLTestDoc dp; while (fname != "q") { std::cout << "about to try to process the file " << fname << std::endl; dp.emplace_back(fname); myP.parse(dp); std::cout << "next file name:" ; std::cin >> fname; dp.clear(); } } } catch (cms::Exception& e) { std::cout << "cms::Exception caught in " << kProgramName << "\n" << e.explainSelf(); rc = 1; } catch (std::exception& e) { std::cout << "Standard library exception caught in " << kProgramName << "\n" << e.what(); rc = 1; } return rc; }
40.51434
132
0.616924
pasmuss
e1951ff900b94c2a88f1985b1d765e3dbfba4cda
15,051
cpp
C++
third_party/mlir/lib/Dialect/FxpMathOps/Transforms/LowerUniformRealMath.cpp
5GApp/tensorflow
ca87089f9e0073bad9fc999ce9c318f661d2e425
[ "Apache-2.0" ]
1
2019-12-23T20:23:43.000Z
2019-12-23T20:23:43.000Z
third_party/mlir/lib/Dialect/FxpMathOps/Transforms/LowerUniformRealMath.cpp
5GApp/tensorflow
ca87089f9e0073bad9fc999ce9c318f661d2e425
[ "Apache-2.0" ]
null
null
null
third_party/mlir/lib/Dialect/FxpMathOps/Transforms/LowerUniformRealMath.cpp
5GApp/tensorflow
ca87089f9e0073bad9fc999ce9c318f661d2e425
[ "Apache-2.0" ]
1
2020-04-22T01:47:46.000Z
2020-04-22T01:47:46.000Z
//===- LowerUniformRealMath.cpp ------------------------------------------===// // // Copyright 2019 The MLIR Authors. // // 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 "UniformKernelUtils.h" #include "mlir/Dialect/FxpMathOps/FxpMathOps.h" #include "mlir/Dialect/FxpMathOps/Passes.h" #include "mlir/Dialect/StandardOps/Ops.h" #include "mlir/IR/Diagnostics.h" #include "mlir/IR/PatternMatch.h" #include "mlir/Pass/Pass.h" using namespace mlir; using namespace mlir::fxpmath; using namespace mlir::fxpmath::detail; using namespace mlir::quant; namespace { struct LowerUniformRealMathPass : public FunctionPass<LowerUniformRealMathPass> { void runOnFunction() override; }; struct LowerUniformCastsPass : public FunctionPass<LowerUniformCastsPass> { void runOnFunction() override; }; } // end anonymous namespace //===----------------------------------------------------------------------===// // Dequantize //===----------------------------------------------------------------------===// static ValuePtr emitUniformPerLayerDequantize(Location loc, ValuePtr input, UniformQuantizedType elementType, PatternRewriter &rewriter) { // Pre-conditions. if (!elementType.isSigned()) { // TODO: Support unsigned storage type. emitWarning(loc, "unimplemented: dequantize signed uniform"); return nullptr; } Type storageType = elementType.castToStorageType(input->getType()); Type realType = elementType.castToExpressedType(input->getType()); Type intermediateType = castElementType(storageType, IntegerType::get(32, rewriter.getContext())); assert(storageType && "cannot cast to storage type"); assert(realType && "cannot cast to expressed type"); // Cast to storage type. input = rewriter.create<StorageCastOp>(loc, storageType, input); // Promote to intermediate type. input = rewriter.create<ConvertISOp>(loc, intermediateType, input); // Apply zero-point offset. if (elementType.getZeroPoint() != 0) { ValuePtr negZeroPointConst = rewriter.create<ConstantOp>( loc, broadcastScalarConstIntValue(intermediateType, -elementType.getZeroPoint())); input = rewriter.create<AddIOp>(loc, input, negZeroPointConst); } // Convert to float. input = rewriter.create<ConvertISToFOp>(loc, realType, input); // Mul by scale. ValuePtr scaleConst = rewriter.create<ConstantOp>( loc, broadcastScalarConstFloatValue(realType, APFloat(elementType.getScale()))); return rewriter.create<MulFOp>(loc, input, scaleConst); } static ValuePtr emitUniformPerAxisDequantize(Location loc, ValuePtr input, UniformQuantizedPerAxisType elementType, PatternRewriter &rewriter) { // TODO: Support per-axis dequantize. rewriter.getContext()->getDiagEngine().emit(loc, DiagnosticSeverity::Warning) << "unimplemented: per-axis uniform dequantization"; return nullptr; } static ValuePtr emitDequantize(Location loc, ValuePtr input, PatternRewriter &rewriter) { Type inputType = input->getType(); QuantizedType qElementType = QuantizedType::getQuantizedElementType(inputType); if (auto uperLayerElementType = qElementType.dyn_cast_or_null<UniformQuantizedType>()) { return emitUniformPerLayerDequantize(loc, input, uperLayerElementType, rewriter); } else if (auto uperAxisElementType = qElementType.dyn_cast_or_null<UniformQuantizedPerAxisType>()) { return emitUniformPerAxisDequantize(loc, input, uperAxisElementType, rewriter); } else { return nullptr; } } namespace { struct UniformDequantizePattern : public OpRewritePattern<DequantizeCastOp> { using OpRewritePattern<DequantizeCastOp>::OpRewritePattern; PatternMatchResult matchAndRewrite(DequantizeCastOp op, PatternRewriter &rewriter) const override { Type inputType = op.arg()->getType(); Type outputType = op.getResult()->getType(); QuantizedType inputElementType = QuantizedType::getQuantizedElementType(inputType); Type expressedOutputType = inputElementType.castToExpressedType(inputType); if (expressedOutputType != outputType) { // Not a valid uniform cast. return matchFailure(); } ValuePtr dequantizedValue = emitDequantize(op.getLoc(), op.arg(), rewriter); if (!dequantizedValue) { return matchFailure(); } rewriter.replaceOp(op, dequantizedValue); return matchSuccess(); } }; } // end anonymous namespace //===----------------------------------------------------------------------===// // Elementwise add //===----------------------------------------------------------------------===// static LogicalResult tryRewriteAffineAddEwIsomorphicSigned(const UniformBinaryOpInfo &info, PatternRewriter &rewriter) { if (!info.resultType.isSigned() || info.lhsType != info.resultType || info.rhsType != info.resultType) { return failure(); } // Choose a byte aligned intermediate width big enough to perform the // calculation without overflow. // TODO: This should probably be made just big enough to avoid overflow and // leave the downstream tooling to decide how to align that to machine // word sizes. unsigned intermediateWidth = info.resultType.getStorageTypeIntegralWidth() <= 8 ? 16 : 32; IntegerType intermediateElementType = IntegerType::get(intermediateWidth, rewriter.getContext()); Type intermediateType = castElementType(info.resultStorageType, intermediateElementType); // Cast operands to storage type. ValuePtr lhsValue = rewriter .create<StorageCastOp>(info.op->getLoc(), info.lhsStorageType, info.lhs) .getResult(); ValuePtr rhsValue = rewriter .create<StorageCastOp>(info.op->getLoc(), info.rhsStorageType, info.rhs) .getResult(); // Cast to the intermediate sized type. lhsValue = rewriter.create<ConvertISOp>(info.op->getLoc(), intermediateType, lhsValue); rhsValue = rewriter.create<ConvertISOp>(info.op->getLoc(), intermediateType, rhsValue); // Add. ValuePtr resultValue = rewriter.create<AddIOp>(info.op->getLoc(), lhsValue, rhsValue); // Zero point offset adjustment. // result = (lhs - zp) + (rhs - zp) + zp // zpOffset = -zp int zpOffset = -1 * info.resultType.getZeroPoint(); if (zpOffset != 0) { ValuePtr zpOffsetConst = rewriter.create<ConstantOp>( info.op->getLoc(), broadcastScalarConstIntValue(intermediateType, zpOffset)); resultValue = rewriter.create<AddIOp>(info.op->getLoc(), resultValue, zpOffsetConst); } // Clamp. auto clampMinMax = info.getClampMinMax(intermediateElementType); resultValue = rewriter.create<ClampISOp>( info.op->getLoc(), resultValue, clampMinMax.first, clampMinMax.second); // Convert back to original type. resultValue = rewriter.create<ConvertISOp>( info.op->getLoc(), info.resultStorageType, resultValue); // Cast back for new result. rewriter.replaceOpWithNewOp<StorageCastOp>( info.op, info.getQuantizedResultType(), resultValue); return success(); } //===----------------------------------------------------------------------===// // Elementwise mul //===----------------------------------------------------------------------===// static LogicalResult tryRewriteAffineMulEwSigned(const UniformBinaryOpInfo &info, PatternRewriter &rewriter) { if (!info.resultType.isSigned()) { return failure(); } double outputMultiplierReal = info.lhsType.getScale() * info.rhsType.getScale() / info.resultType.getScale(); if (outputMultiplierReal > 1.0) { info.op->emitWarning( "unimplemented: cannot multiply with multiplier > 1.0"); return failure(); } // TODO: Choose an appropriate intermediate width for muls > 8 bits to // avoid overflow. unsigned intermediateWidth = 32; IntegerType intermediateElementType = IntegerType::get(intermediateWidth, rewriter.getContext()); Type intermediateType = castElementType(info.resultStorageType, intermediateElementType); // Cast operands to storage type. ValuePtr lhsValue = rewriter .create<StorageCastOp>(info.op->getLoc(), info.lhsStorageType, info.lhs) .getResult(); ValuePtr rhsValue = rewriter .create<StorageCastOp>(info.op->getLoc(), info.rhsStorageType, info.rhs) .getResult(); // Cast to the intermediate sized type. lhsValue = rewriter.create<ConvertISOp>(info.op->getLoc(), intermediateType, lhsValue); rhsValue = rewriter.create<ConvertISOp>(info.op->getLoc(), intermediateType, rhsValue); // Apply argument zeroPoints. if (info.lhsType.getZeroPoint() != 0) { ValuePtr zpOffsetConst = rewriter.create<ConstantOp>( info.op->getLoc(), broadcastScalarConstIntValue( intermediateType, -info.lhsType.getZeroPoint())); lhsValue = rewriter.create<AddIOp>(info.op->getLoc(), lhsValue, zpOffsetConst); } if (info.rhsType.getZeroPoint() != 0) { ValuePtr zpOffsetConst = rewriter.create<ConstantOp>( info.op->getLoc(), broadcastScalarConstIntValue( intermediateType, -info.rhsType.getZeroPoint())); rhsValue = rewriter.create<AddIOp>(info.op->getLoc(), rhsValue, zpOffsetConst); } // Mul. ValuePtr resultValue = rewriter.create<MulIOp>(info.op->getLoc(), lhsValue, rhsValue); // Scale output. QuantizedMultiplierSmallerThanOneExp outputMultiplier(outputMultiplierReal); resultValue = rewriter.create<VecScalarSaturatingRoundingDoublingHighMulISOp>( info.op->getLoc(), resultValue, IntegerAttr::get(intermediateElementType, outputMultiplier.multiplier)); resultValue = rewriter.create<RoundingDivideByPotISOp>( info.op->getLoc(), resultValue, IntegerAttr::get(intermediateElementType, -outputMultiplier.exponent)); // Zero point offset adjustment. if (info.resultType.getZeroPoint() != 0) { ValuePtr zpOffsetConst = rewriter.create<ConstantOp>( info.op->getLoc(), broadcastScalarConstIntValue(intermediateType, info.resultType.getZeroPoint())); resultValue = rewriter.create<AddIOp>(info.op->getLoc(), resultValue, zpOffsetConst); } // Clamp. auto clampMinMax = info.getClampMinMax(intermediateElementType); resultValue = rewriter.create<ClampISOp>( info.op->getLoc(), resultValue, clampMinMax.first, clampMinMax.second); // Convert back to original type. resultValue = rewriter.create<ConvertISOp>( info.op->getLoc(), info.resultStorageType, resultValue); // Cast back for new result. rewriter.replaceOpWithNewOp<StorageCastOp>( info.op, info.getQuantizedResultType(), resultValue); return success(); } namespace { struct UniformRealAddEwPattern : public OpRewritePattern<RealAddEwOp> { using OpRewritePattern<RealAddEwOp>::OpRewritePattern; PatternMatchResult matchAndRewrite(RealAddEwOp op, PatternRewriter &rewriter) const override { const UniformBinaryOpInfo info(op, op.lhs(), op.rhs(), op.clamp_min(), op.clamp_max()); if (!info.isValid()) { return matchFailure(); } // Try all of the permutations we support. if (succeeded(tryRewriteAffineAddEwIsomorphicSigned(info, rewriter))) { return matchSuccess(); } return matchFailure(); } }; struct UniformRealMulEwPattern : public OpRewritePattern<RealMulEwOp> { using OpRewritePattern<RealMulEwOp>::OpRewritePattern; PatternMatchResult matchAndRewrite(RealMulEwOp op, PatternRewriter &rewriter) const override { const UniformBinaryOpInfo info(op, op.lhs(), op.rhs(), op.clamp_min(), op.clamp_max()); if (!info.isValid()) { return matchFailure(); } // Try all of the permutations we support. if (succeeded(tryRewriteAffineMulEwSigned(info, rewriter))) { return matchSuccess(); } return matchFailure(); } }; } // end anonymous namespace //===----------------------------------------------------------------------===// // LowerUniformRealMath pass //===----------------------------------------------------------------------===// void LowerUniformRealMathPass::runOnFunction() { auto fn = getFunction(); OwningRewritePatternList patterns; auto *context = &getContext(); patterns.insert<UniformRealAddEwPattern, UniformRealMulEwPattern>(context); applyPatternsGreedily(fn, patterns); } OpPassBase<FuncOp> *mlir::fxpmath::createLowerUniformRealMathPass() { return new LowerUniformRealMathPass(); } static PassRegistration<LowerUniformRealMathPass> lowerUniformRealMathPass( "fxpmath-lower-uniform-real-math", "Lowers uniform-quantized real math ops to integer arithmetic."); //===----------------------------------------------------------------------===// // LowerUniformCasts pass //===----------------------------------------------------------------------===// void LowerUniformCastsPass::runOnFunction() { auto fn = getFunction(); OwningRewritePatternList patterns; auto *context = &getContext(); patterns.insert<UniformDequantizePattern>(context); applyPatternsGreedily(fn, patterns); } OpPassBase<FuncOp> *mlir::fxpmath::createLowerUniformCastsPass() { return new LowerUniformCastsPass(); } static PassRegistration<LowerUniformCastsPass> lowerUniformCastsPass("fxpmath-lower-uniform-casts", "Lowers uniform-quantized casts.");
37.347395
80
0.626669
5GApp
e1966c6c4425affb914d7da7a176e9cf8053850b
30,144
cpp
C++
src/frameworks/av/media/libstagefright/codecs/amrwb/src/mime_io.cpp
dAck2cC2/m3e
475b89b59d5022a94e00b636438b25e27e4eaab2
[ "Apache-2.0" ]
10
2020-04-17T04:02:36.000Z
2021-11-23T11:38:42.000Z
src/frameworks/av/media/libstagefright/codecs/amrwb/src/mime_io.cpp
dAck2cC2/m3e
475b89b59d5022a94e00b636438b25e27e4eaab2
[ "Apache-2.0" ]
3
2020-02-19T16:53:25.000Z
2021-04-29T07:28:40.000Z
src/frameworks/av/media/libstagefright/codecs/amrwb/src/mime_io.cpp
dAck2cC2/m3e
475b89b59d5022a94e00b636438b25e27e4eaab2
[ "Apache-2.0" ]
12
2020-04-15T11:37:33.000Z
2021-09-13T13:19:04.000Z
/* ------------------------------------------------------------------ * Copyright (C) 1998-2009 PacketVideo * * 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. * ------------------------------------------------------------------- */ /**************************************************************************************** Portions of this file are derived from the following 3GPP standard: 3GPP TS 26.173 ANSI-C code for the Adaptive Multi-Rate - Wideband (AMR-WB) speech codec Available from http://www.3gpp.org (C) 2007, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC) Permission to distribute, modify and use this file under the standard license terms listed above has been obtained from the copyright holder. ****************************************************************************************/ /* ------------------------------------------------------------------------------ Pathname: ./src/mime_io.cpp Date: 05/07/2007 ------------------------------------------------------------------------------ REVISION HISTORY Description: ------------------------------------------------------------------------------ INPUT AND OUTPUT DEFINITIONS Inputs: [input_variable_name] = [description of the input to module, its type definition, and length (when applicable)] Local Stores/Buffers/Pointers Needed: [local_store_name] = [description of the local store, its type definition, and length (when applicable)] [local_buffer_name] = [description of the local buffer, its type definition, and length (when applicable)] [local_ptr_name] = [description of the local pointer, its type definition, and length (when applicable)] Global Stores/Buffers/Pointers Needed: [global_store_name] = [description of the global store, its type definition, and length (when applicable)] [global_buffer_name] = [description of the global buffer, its type definition, and length (when applicable)] [global_ptr_name] = [description of the global pointer, its type definition, and length (when applicable)] Outputs: [return_variable_name] = [description of data/pointer returned by module, its type definition, and length (when applicable)] Pointers and Buffers Modified: [variable_bfr_ptr] points to the [describe where the variable_bfr_ptr points to, its type definition, and length (when applicable)] [variable_bfr] contents are [describe the new contents of variable_bfr] Local Stores Modified: [local_store_name] = [describe new contents, its type definition, and length (when applicable)] Global Stores Modified: [global_store_name] = [describe new contents, its type definition, and length (when applicable)] ------------------------------------------------------------------------------ FUNCTION DESCRIPTION [Describe what the module does by using the variable names listed in the Input and Output Definitions Section above.] ------------------------------------------------------------------------------ REQUIREMENTS [List requirements to be satisfied by this module.] ------------------------------------------------------------------------------ REFERENCES [List all references used in designing this module.] ------------------------------------------------------------------------------ PSEUDO-CODE ------------------------------------------------------------------------------ RESOURCES USED STACK USAGE: DATA MEMORY USED: x words PROGRAM MEMORY USED: x words CLOCK CYCLES: ------------------------------------------------------------------------------ */ /*---------------------------------------------------------------------------- ; INCLUDES ----------------------------------------------------------------------------*/ #include "pv_amr_wb_type_defs.h" #include "pvamrwbdecoder_api.h" #include "pvamrwbdecoder.h" #include "pvamrwbdecoder_mem_funcs.h" #include "pvamrwbdecoder_cnst.h" #include "dtx.h" #include "mime_io.h" /*---------------------------------------------------------------------------- ; MACROS ; Define module specific macros here ----------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------- ; DEFINES ; Include all pre-processor statements here. Include conditional ; compile variables also. ----------------------------------------------------------------------------*/ #define MRSID 9 /*---------------------------------------------------------------------------- ; LOCAL FUNCTION DEFINITIONS ; Function Prototype declaration ----------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------- ; LOCAL STORE/BUFFER/POINTER DEFINITIONS ; Variable declaration - defined here and used outside this module ----------------------------------------------------------------------------*/ const uint8 toc_byte[16] = {0x04, 0x0C, 0x14, 0x1C, 0x24, 0x2C, 0x34, 0x3C, 0x44, 0x4C, 0x54, 0x5C, 0x64, 0x6C, 0x74, 0x7C }; /* number of speech bits for all modes */ const int16 unpacked_size[16] = { 132, 177, 253, 285, 317, 365, 397, 461, 477, 35, 0, 0, 0, 0, 0, 0 }; /* size of packed frame for each mode, excluding TOC byte */ const int16 packed_size[16] = {17, 23, 32, 36, 40, 46, 50, 58, 60, 5, 0, 0, 0, 0, 0, 0 }; /* number of unused speech bits in packed format for each mode */ const int16 unused_size[16] = {4, 7, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0}; /* sorting tables for all modes */ const int16 sort_660[132] = { 0, 5, 6, 7, 61, 84, 107, 130, 62, 85, 8, 4, 37, 38, 39, 40, 58, 81, 104, 127, 60, 83, 106, 129, 108, 131, 128, 41, 42, 80, 126, 1, 3, 57, 103, 82, 105, 59, 2, 63, 109, 110, 86, 19, 22, 23, 64, 87, 18, 20, 21, 17, 13, 88, 43, 89, 65, 111, 14, 24, 25, 26, 27, 28, 15, 16, 44, 90, 66, 112, 9, 11, 10, 12, 67, 113, 29, 30, 31, 32, 34, 33, 35, 36, 45, 51, 68, 74, 91, 97, 114, 120, 46, 69, 92, 115, 52, 75, 98, 121, 47, 70, 93, 116, 53, 76, 99, 122, 48, 71, 94, 117, 54, 77, 100, 123, 49, 72, 95, 118, 55, 78, 101, 124, 50, 73, 96, 119, 56, 79, 102, 125 }; const int16 sort_885[177] = { 0, 4, 6, 7, 5, 3, 47, 48, 49, 112, 113, 114, 75, 106, 140, 171, 80, 111, 145, 176, 77, 108, 142, 173, 78, 109, 143, 174, 79, 110, 144, 175, 76, 107, 141, 172, 50, 115, 51, 2, 1, 81, 116, 146, 19, 21, 12, 17, 18, 20, 16, 25, 13, 10, 14, 24, 23, 22, 26, 8, 15, 52, 117, 31, 82, 147, 9, 33, 11, 83, 148, 53, 118, 28, 27, 84, 149, 34, 35, 29, 46, 32, 30, 54, 119, 37, 36, 39, 38, 40, 85, 150, 41, 42, 43, 44, 45, 55, 60, 65, 70, 86, 91, 96, 101, 120, 125, 130, 135, 151, 156, 161, 166, 56, 87, 121, 152, 61, 92, 126, 157, 66, 97, 131, 162, 71, 102, 136, 167, 57, 88, 122, 153, 62, 93, 127, 158, 67, 98, 132, 163, 72, 103, 137, 168, 58, 89, 123, 154, 63, 94, 128, 159, 68, 99, 133, 164, 73, 104, 138, 169, 59, 90, 124, 155, 64, 95, 129, 160, 69, 100, 134, 165, 74, 105, 139, 170 }; const int16 sort_1265[253] = { 0, 4, 6, 93, 143, 196, 246, 7, 5, 3, 47, 48, 49, 50, 51, 150, 151, 152, 153, 154, 94, 144, 197, 247, 99, 149, 202, 252, 96, 146, 199, 249, 97, 147, 200, 250, 100, 203, 98, 148, 201, 251, 95, 145, 198, 248, 52, 2, 1, 101, 204, 155, 19, 21, 12, 17, 18, 20, 16, 25, 13, 10, 14, 24, 23, 22, 26, 8, 15, 53, 156, 31, 102, 205, 9, 33, 11, 103, 206, 54, 157, 28, 27, 104, 207, 34, 35, 29, 46, 32, 30, 55, 158, 37, 36, 39, 38, 40, 105, 208, 41, 42, 43, 44, 45, 56, 106, 159, 209, 57, 66, 75, 84, 107, 116, 125, 134, 160, 169, 178, 187, 210, 219, 228, 237, 58, 108, 161, 211, 62, 112, 165, 215, 67, 117, 170, 220, 71, 121, 174, 224, 76, 126, 179, 229, 80, 130, 183, 233, 85, 135, 188, 238, 89, 139, 192, 242, 59, 109, 162, 212, 63, 113, 166, 216, 68, 118, 171, 221, 72, 122, 175, 225, 77, 127, 180, 230, 81, 131, 184, 234, 86, 136, 189, 239, 90, 140, 193, 243, 60, 110, 163, 213, 64, 114, 167, 217, 69, 119, 172, 222, 73, 123, 176, 226, 78, 128, 181, 231, 82, 132, 185, 235, 87, 137, 190, 240, 91, 141, 194, 244, 61, 111, 164, 214, 65, 115, 168, 218, 70, 120, 173, 223, 74, 124, 177, 227, 79, 129, 182, 232, 83, 133, 186, 236, 88, 138, 191, 241, 92, 142, 195, 245 }; const int16 sort_1425[285] = { 0, 4, 6, 101, 159, 220, 278, 7, 5, 3, 47, 48, 49, 50, 51, 166, 167, 168, 169, 170, 102, 160, 221, 279, 107, 165, 226, 284, 104, 162, 223, 281, 105, 163, 224, 282, 108, 227, 106, 164, 225, 283, 103, 161, 222, 280, 52, 2, 1, 109, 228, 171, 19, 21, 12, 17, 18, 20, 16, 25, 13, 10, 14, 24, 23, 22, 26, 8, 15, 53, 172, 31, 110, 229, 9, 33, 11, 111, 230, 54, 173, 28, 27, 112, 231, 34, 35, 29, 46, 32, 30, 55, 174, 37, 36, 39, 38, 40, 113, 232, 41, 42, 43, 44, 45, 56, 114, 175, 233, 62, 120, 181, 239, 75, 133, 194, 252, 57, 115, 176, 234, 63, 121, 182, 240, 70, 128, 189, 247, 76, 134, 195, 253, 83, 141, 202, 260, 92, 150, 211, 269, 84, 142, 203, 261, 93, 151, 212, 270, 85, 143, 204, 262, 94, 152, 213, 271, 86, 144, 205, 263, 95, 153, 214, 272, 64, 122, 183, 241, 77, 135, 196, 254, 65, 123, 184, 242, 78, 136, 197, 255, 87, 145, 206, 264, 96, 154, 215, 273, 58, 116, 177, 235, 66, 124, 185, 243, 71, 129, 190, 248, 79, 137, 198, 256, 88, 146, 207, 265, 97, 155, 216, 274, 59, 117, 178, 236, 67, 125, 186, 244, 72, 130, 191, 249, 80, 138, 199, 257, 89, 147, 208, 266, 98, 156, 217, 275, 60, 118, 179, 237, 68, 126, 187, 245, 73, 131, 192, 250, 81, 139, 200, 258, 90, 148, 209, 267, 99, 157, 218, 276, 61, 119, 180, 238, 69, 127, 188, 246, 74, 132, 193, 251, 82, 140, 201, 259, 91, 149, 210, 268, 100, 158, 219, 277 }; const int16 sort_1585[317] = { 0, 4, 6, 109, 175, 244, 310, 7, 5, 3, 47, 48, 49, 50, 51, 182, 183, 184, 185, 186, 110, 176, 245, 311, 115, 181, 250, 316, 112, 178, 247, 313, 113, 179, 248, 314, 116, 251, 114, 180, 249, 315, 111, 177, 246, 312, 52, 2, 1, 117, 252, 187, 19, 21, 12, 17, 18, 20, 16, 25, 13, 10, 14, 24, 23, 22, 26, 8, 15, 53, 188, 31, 118, 253, 9, 33, 11, 119, 254, 54, 189, 28, 27, 120, 255, 34, 35, 29, 46, 32, 30, 55, 190, 37, 36, 39, 38, 40, 121, 256, 41, 42, 43, 44, 45, 56, 122, 191, 257, 63, 129, 198, 264, 76, 142, 211, 277, 89, 155, 224, 290, 102, 168, 237, 303, 57, 123, 192, 258, 70, 136, 205, 271, 83, 149, 218, 284, 96, 162, 231, 297, 62, 128, 197, 263, 75, 141, 210, 276, 88, 154, 223, 289, 101, 167, 236, 302, 58, 124, 193, 259, 71, 137, 206, 272, 84, 150, 219, 285, 97, 163, 232, 298, 59, 125, 194, 260, 64, 130, 199, 265, 67, 133, 202, 268, 72, 138, 207, 273, 77, 143, 212, 278, 80, 146, 215, 281, 85, 151, 220, 286, 90, 156, 225, 291, 93, 159, 228, 294, 98, 164, 233, 299, 103, 169, 238, 304, 106, 172, 241, 307, 60, 126, 195, 261, 65, 131, 200, 266, 68, 134, 203, 269, 73, 139, 208, 274, 78, 144, 213, 279, 81, 147, 216, 282, 86, 152, 221, 287, 91, 157, 226, 292, 94, 160, 229, 295, 99, 165, 234, 300, 104, 170, 239, 305, 107, 173, 242, 308, 61, 127, 196, 262, 66, 132, 201, 267, 69, 135, 204, 270, 74, 140, 209, 275, 79, 145, 214, 280, 82, 148, 217, 283, 87, 153, 222, 288, 92, 158, 227, 293, 95, 161, 230, 296, 100, 166, 235, 301, 105, 171, 240, 306, 108, 174, 243, 309 }; const int16 sort_1825[365] = { 0, 4, 6, 121, 199, 280, 358, 7, 5, 3, 47, 48, 49, 50, 51, 206, 207, 208, 209, 210, 122, 200, 281, 359, 127, 205, 286, 364, 124, 202, 283, 361, 125, 203, 284, 362, 128, 287, 126, 204, 285, 363, 123, 201, 282, 360, 52, 2, 1, 129, 288, 211, 19, 21, 12, 17, 18, 20, 16, 25, 13, 10, 14, 24, 23, 22, 26, 8, 15, 53, 212, 31, 130, 289, 9, 33, 11, 131, 290, 54, 213, 28, 27, 132, 291, 34, 35, 29, 46, 32, 30, 55, 214, 37, 36, 39, 38, 40, 133, 292, 41, 42, 43, 44, 45, 56, 134, 215, 293, 198, 299, 136, 120, 138, 60, 279, 58, 62, 357, 139, 140, 295, 156, 57, 219, 297, 63, 217, 137, 170, 300, 222, 64, 106, 61, 78, 294, 92, 142, 141, 135, 221, 296, 301, 343, 59, 298, 184, 329, 315, 220, 216, 265, 251, 218, 237, 352, 223, 157, 86, 171, 87, 164, 351, 111, 302, 65, 178, 115, 323, 72, 192, 101, 179, 93, 73, 193, 151, 337, 309, 143, 274, 69, 324, 165, 150, 97, 338, 110, 310, 330, 273, 68, 107, 175, 245, 114, 79, 113, 189, 246, 259, 174, 71, 185, 96, 344, 100, 322, 83, 334, 316, 333, 252, 161, 348, 147, 82, 269, 232, 260, 308, 353, 347, 163, 231, 306, 320, 188, 270, 146, 177, 266, 350, 256, 85, 149, 116, 191, 160, 238, 258, 336, 305, 255, 88, 224, 99, 339, 230, 228, 227, 272, 242, 241, 319, 233, 311, 102, 74, 180, 275, 66, 194, 152, 325, 172, 247, 244, 261, 117, 158, 166, 354, 75, 144, 108, 312, 94, 186, 303, 80, 234, 89, 195, 112, 340, 181, 345, 317, 326, 276, 239, 167, 118, 313, 70, 355, 327, 253, 190, 176, 271, 104, 98, 153, 103, 90, 76, 267, 277, 248, 225, 262, 182, 84, 154, 235, 335, 168, 331, 196, 341, 249, 162, 307, 148, 349, 263, 321, 257, 243, 229, 356, 159, 119, 67, 187, 173, 145, 240, 77, 304, 332, 314, 342, 109, 254, 81, 278, 105, 91, 346, 318, 183, 250, 197, 328, 95, 155, 169, 268, 226, 236, 264 }; const int16 sort_1985[397] = { 0, 4, 6, 129, 215, 304, 390, 7, 5, 3, 47, 48, 49, 50, 51, 222, 223, 224, 225, 226, 130, 216, 305, 391, 135, 221, 310, 396, 132, 218, 307, 393, 133, 219, 308, 394, 136, 311, 134, 220, 309, 395, 131, 217, 306, 392, 52, 2, 1, 137, 312, 227, 19, 21, 12, 17, 18, 20, 16, 25, 13, 10, 14, 24, 23, 22, 26, 8, 15, 53, 228, 31, 138, 313, 9, 33, 11, 139, 314, 54, 229, 28, 27, 140, 315, 34, 35, 29, 46, 32, 30, 55, 230, 37, 36, 39, 38, 40, 141, 316, 41, 42, 43, 44, 45, 56, 142, 231, 317, 63, 73, 92, 340, 82, 324, 149, 353, 159, 334, 165, 338, 178, 163, 254, 77, 168, 257, 153, 343, 57, 248, 238, 79, 252, 166, 67, 80, 201, 101, 267, 143, 164, 341, 255, 339, 187, 376, 318, 78, 328, 362, 115, 232, 242, 253, 290, 276, 62, 58, 158, 68, 93, 179, 319, 148, 169, 154, 72, 385, 329, 333, 344, 102, 83, 144, 233, 323, 124, 243, 192, 354, 237, 64, 247, 202, 209, 150, 116, 335, 268, 239, 299, 188, 196, 298, 94, 195, 258, 123, 363, 384, 109, 325, 371, 170, 370, 84, 110, 295, 180, 74, 210, 191, 106, 291, 205, 367, 381, 377, 206, 355, 122, 119, 120, 383, 160, 105, 108, 277, 380, 294, 284, 285, 345, 208, 269, 249, 366, 386, 300, 297, 259, 125, 369, 197, 97, 194, 286, 211, 281, 280, 183, 372, 87, 155, 283, 59, 348, 327, 184, 76, 111, 330, 203, 349, 69, 98, 152, 145, 189, 66, 320, 337, 173, 358, 251, 198, 174, 263, 262, 126, 241, 193, 88, 388, 117, 95, 387, 112, 359, 287, 244, 103, 272, 301, 171, 162, 234, 273, 127, 373, 181, 292, 85, 378, 302, 121, 107, 364, 346, 356, 212, 278, 213, 65, 382, 288, 207, 113, 175, 99, 296, 374, 368, 199, 260, 185, 336, 331, 161, 270, 264, 250, 240, 75, 350, 151, 60, 89, 321, 156, 274, 360, 326, 70, 282, 167, 146, 352, 81, 91, 389, 266, 245, 177, 235, 190, 256, 204, 342, 128, 118, 303, 104, 379, 182, 114, 375, 200, 96, 293, 172, 214, 365, 279, 86, 289, 351, 347, 357, 261, 186, 176, 271, 90, 100, 147, 322, 275, 361, 71, 332, 61, 265, 157, 246, 236 }; const int16 sort_2305[461] = { 0, 4, 6, 145, 247, 352, 454, 7, 5, 3, 47, 48, 49, 50, 51, 254, 255, 256, 257, 258, 146, 248, 353, 455, 151, 253, 358, 460, 148, 250, 355, 457, 149, 251, 356, 458, 152, 359, 150, 252, 357, 459, 147, 249, 354, 456, 52, 2, 1, 153, 360, 259, 19, 21, 12, 17, 18, 20, 16, 25, 13, 10, 14, 24, 23, 22, 26, 8, 15, 53, 260, 31, 154, 361, 9, 33, 11, 155, 362, 54, 261, 28, 27, 156, 363, 34, 35, 29, 46, 32, 30, 55, 262, 37, 36, 39, 38, 40, 157, 364, 41, 42, 43, 44, 45, 56, 158, 263, 365, 181, 192, 170, 79, 57, 399, 90, 159, 297, 377, 366, 275, 68, 183, 388, 286, 194, 299, 92 , 70, 182, 401, 172, 59, 91, 58, 400, 368, 161, 81, 160, 264, 171, 80, 389, 390, 378, 379, 193, 298, 69, 266, 265, 367, 277, 288, 276, 287, 184, 60, 195, 82, 93, 71, 369, 402, 173, 162, 444, 300, 391, 98, 76, 278, 61, 267, 374, 135, 411, 167, 102, 380, 200, 87, 178, 65, 94, 204, 124, 72, 342, 189, 305, 381, 396, 433, 301, 226, 407, 289, 237, 113, 215, 185, 128, 309, 403, 116, 320, 196, 331, 370, 422, 174, 64, 392, 83, 425, 219, 134, 188, 432, 112, 427, 139, 279, 163, 436, 208, 447, 218, 236, 229, 97, 294, 385, 230, 166, 268, 177, 443, 225, 426, 101, 272, 138, 127, 290, 117, 347, 199, 414, 95, 140, 240, 410, 395, 209, 129, 283, 346, 105, 241, 437, 86, 308, 448, 203, 345, 186, 107, 220, 415, 334, 319, 106, 313, 118, 123, 73, 207, 421, 214, 384, 373, 438, 62, 371, 341, 75, 449, 168, 323, 164, 242, 416, 324, 304, 197, 335, 404, 271, 63, 191, 325, 96, 169, 231, 280, 312, 187, 406, 84, 201, 100, 67, 382, 175, 336, 202, 330, 269, 393, 376, 383, 293, 307, 409, 179, 285, 314, 302, 372, 398, 190, 180, 89, 99, 103, 232, 78, 88, 77, 136, 387, 165, 198, 394, 125, 176, 428, 74, 375, 238, 227, 66, 273, 282, 141, 306, 412, 114, 85, 130, 348, 119, 291, 296, 386, 233, 397, 303, 405, 284, 445, 423, 221, 210, 205, 450, 108, 274, 434, 216, 343, 337, 142, 243, 321, 408, 451, 310, 292, 120, 109, 281, 439, 270, 429, 332, 295, 418, 211, 315, 222, 326, 131, 430, 244, 327, 349, 417, 316, 143, 338, 440, 234, 110, 212, 452, 245, 121, 419, 350, 223, 132, 441, 328, 413, 317, 339, 126, 104, 137, 446, 344, 239, 435, 115, 333, 206, 322, 217, 228, 424, 453, 311, 351, 111, 442, 224, 213, 122, 431, 340, 235, 246, 133, 144, 420, 329, 318 }; const int16 sort_2385[477] = { 0, 4, 6, 145, 251, 360, 466, 7, 5, 3, 47, 48, 49, 50, 51, 262, 263, 264, 265, 266, 146, 252, 361, 467, 151, 257, 366, 472, 148, 254, 363, 469, 149, 255, 364, 470, 156, 371, 150, 256, 365, 471, 147, 253, 362, 468, 52, 2, 1, 157, 372, 267, 19, 21, 12, 17, 18, 20, 16, 25, 13, 10, 14, 24, 23, 22, 26, 8, 15, 53, 268, 31, 152, 153, 154, 155, 258, 259, 260, 261, 367, 368, 369, 370, 473, 474, 475, 476, 158, 373, 9, 33, 11, 159, 374, 54, 269, 28, 27, 160, 375, 34, 35, 29, 46, 32, 30, 55, 270, 37, 36, 39, 38, 40, 161, 376, 41, 42, 43, 44, 45, 56, 162, 271, 377, 185, 196, 174, 79, 57, 411, 90, 163, 305, 389, 378, 283, 68, 187, 400, 294, 198, 307, 92, 70, 186, 413, 176, 59, 91, 58, 412, 380, 165, 81, 164, 272, 175, 80, 401, 402, 390, 391, 197, 306, 69, 274, 273, 379, 285, 296, 284, 295, 188, 60, 199, 82, 93, 71, 381, 414, 177, 166, 456, 308, 403, 98, 76, 286, 61, 275, 386, 135, 423, 171, 102, 392, 204, 87, 182, 65, 94, 208, 124, 72, 350, 193, 313, 393, 408, 445, 309, 230, 419, 297, 241, 113, 219, 189, 128, 317, 415, 116, 328, 200, 339, 382, 434, 178, 64, 404, 83, 437, 223, 134, 192, 444, 112, 439, 139, 287, 167, 448, 212, 459, 222, 240, 233, 97, 302, 397, 234, 170, 276, 181, 455, 229, 438, 101, 280, 138, 127, 298, 117, 355, 203, 426, 95, 140, 244, 422, 407, 213, 129, 291, 354, 105, 245, 449, 86, 316, 460, 207, 353, 190, 107, 224, 427, 342, 327, 106, 321, 118, 123, 73, 211, 433, 218, 396, 385, 450, 62, 383, 349, 75, 461, 172, 331, 168, 246, 428, 332, 312, 201, 343, 416, 279, 63, 195, 333, 96, 173, 235, 288, 320, 191, 418, 84, 205, 100, 67, 394, 179, 344, 206, 338, 277, 405, 388, 395, 301, 315, 421, 183, 293, 322, 310, 384, 410, 194, 184, 89, 99, 103, 236, 78, 88, 77, 136, 399, 169, 202, 406, 125, 180, 440, 74, 387, 242, 231, 66, 281, 290, 141, 314, 424, 114, 85, 130, 356, 119, 299, 304, 398, 237, 409, 311, 417, 292, 457, 435, 225, 214, 209, 462, 108, 282, 446, 220, 351, 345, 142, 247, 329, 420, 463, 318, 300, 120, 109, 289, 451, 278, 441, 340, 303, 430, 215, 323, 226, 334, 131, 442, 248, 335, 357, 429, 324, 143, 346, 452, 238, 110, 216, 464, 249, 121, 431, 358, 227, 132, 453, 336, 425, 325, 347, 126, 104, 137, 458, 352, 243, 447, 115, 341, 210, 330, 221, 232, 436, 465, 319, 359, 111, 454, 228, 217, 122, 443, 348, 239, 250, 133, 144, 432, 337, 326 }; const int16 sort_SID[35] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34 }; /*---------------------------------------------------------------------------- ; EXTERNAL FUNCTION REFERENCES ; Declare functions defined elsewhere and referenced in this module ----------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------- ; EXTERNAL GLOBAL STORE/BUFFER/POINTER REFERENCES ; Declare variables used in this module but defined elsewhere ----------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------- ; FUNCTION CODE ----------------------------------------------------------------------------*/ void mime_unsorting(uint8 unsorted_bits[], int16 sorted_bits_into_int16[], int16 * frame_type, int16 * mode, uint8 quality, RX_State_wb *st) { int16 i; int16 j; uint8 temp = 0; uint8 *unsorted_bits_ptr = (uint8*)unsorted_bits; /* pointer table for bit sorting tables */ const int16 *AmrWbSortingTables[16] = { sort_660, sort_885, sort_1265, sort_1425, sort_1585, sort_1825, sort_1985, sort_2305, sort_2385, sort_SID, NULL, NULL, NULL, NULL, NULL, NULL }; const int16 * pt_AmrWbSortingTables = AmrWbSortingTables[*mode]; /* clear compressed speech bit buffer */ pv_memset(sorted_bits_into_int16, 0, unpacked_size[*mode]*sizeof(*sorted_bits_into_int16)); /* unpack and unsort speech or SID bits */ for (i = unpacked_size[*mode] >> 3; i != 0; i--) { temp = *(unsorted_bits_ptr++); for (j = 2; j != 0; j--) { switch (temp & 0xf0) { case 0xf0: sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1; sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1; sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1; sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1; break; case 0xe0: sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1; sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1; sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1; pt_AmrWbSortingTables++; break; case 0xd0: sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1; sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1; pt_AmrWbSortingTables++; sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1; break; case 0xc0: sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1; sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1; pt_AmrWbSortingTables += 2; break; case 0xb0: sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1; pt_AmrWbSortingTables++; sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1; sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1; break; case 0xa0: sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1; pt_AmrWbSortingTables++; sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1; pt_AmrWbSortingTables++; break; case 0x90: sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1; pt_AmrWbSortingTables += 2; sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1; break; case 0x80: sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1; pt_AmrWbSortingTables += 3; break; case 0x70: pt_AmrWbSortingTables++; sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1; sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1; sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1; break; case 0x60: pt_AmrWbSortingTables++; sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1; sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1; pt_AmrWbSortingTables++; break; case 0x50: pt_AmrWbSortingTables++; sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1; pt_AmrWbSortingTables++; sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1; break; case 0x40: pt_AmrWbSortingTables++; sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1; pt_AmrWbSortingTables += 2; break; case 0x30: pt_AmrWbSortingTables += 2; sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1; sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1; break; case 0x20: pt_AmrWbSortingTables += 2; sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1; pt_AmrWbSortingTables++; break; case 0x10: pt_AmrWbSortingTables += 3; sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1; break; default: pt_AmrWbSortingTables += 4; break; } temp <<= 4; } } if (unpacked_size[*mode] % 4) { temp <<= 1; if (temp & 0x80) { sorted_bits_into_int16[*(pt_AmrWbSortingTables++)] = BIT_1; } } /* set frame type */ switch (*mode) { case MODE_7k: case MODE_9k: case MODE_12k: case MODE_14k: case MODE_16k: case MODE_18k: case MODE_20k: case MODE_23k: case MODE_24k: if (quality) { *frame_type = RX_SPEECH_GOOD; } else { *frame_type = RX_SPEECH_BAD; } break; case MRSID: if (quality) { if (temp & 0x80) { *frame_type = RX_SID_UPDATE; } else { *frame_type = RX_SID_FIRST; } } else { *frame_type = RX_SID_BAD; } /* set mode index */ *mode = st->prev_mode; break; case 14: /* SPEECH_LOST */ *frame_type = RX_SPEECH_LOST; *mode = st->prev_mode; break; case 15: /* NO_DATA */ *frame_type = RX_NO_DATA; *mode = st->prev_mode; break; default: /* replace frame with unused mode index by NO_DATA frame */ *frame_type = RX_NO_DATA; *mode = st->prev_mode; break; } st->prev_mode = *mode; }
41.293151
89
0.484242
dAck2cC2
e1995200a41c73feb893397859bf6a95b2ea9864
2,821
cpp
C++
raycastergl/src/opengl/buffer.cpp
DanielAcedo/raycastergl
412bf8b6b2e8996bcdc9cb4112258cc24527b22a
[ "MIT" ]
4
2020-06-07T13:00:30.000Z
2021-10-18T20:50:21.000Z
raycastergl/src/opengl/buffer.cpp
DanielAcedo/raycastergl
412bf8b6b2e8996bcdc9cb4112258cc24527b22a
[ "MIT" ]
null
null
null
raycastergl/src/opengl/buffer.cpp
DanielAcedo/raycastergl
412bf8b6b2e8996bcdc9cb4112258cc24527b22a
[ "MIT" ]
2
2020-06-27T16:15:20.000Z
2020-09-01T06:48:14.000Z
#include <opengl/buffer.hpp> #include <fstream> #include <glad/glad.h> #include <opengl/check-error.hpp> constexpr int usageToGlUsage(Buffer::Usage usage) { switch(usage) { case Buffer::StreamDraw: return GL_STREAM_DRAW; case Buffer::StreamRead: return GL_STREAM_READ; case Buffer::StreamCopy: return GL_STREAM_COPY; case Buffer::StaticDraw: return GL_STATIC_DRAW; case Buffer::StaticRead: return GL_STATIC_READ; case Buffer::StaticCopy: return GL_STATIC_COPY; case Buffer::DynamicDraw: return GL_DYNAMIC_DRAW; case Buffer::DynamicRead: return GL_DYNAMIC_READ; case Buffer::DynamicCopy: return GL_DYNAMIC_COPY; default: return GL_STREAM_COPY; } } constexpr int typeToGlType(Buffer::Type type) { switch(type) { case Buffer::ArrayBuffer: return GL_ARRAY_BUFFER; case Buffer::ElementArrayBuffer: return GL_ELEMENT_ARRAY_BUFFER; case Buffer::ShaderStorageBuffer: return GL_SHADER_STORAGE_BUFFER; default: return GL_ARRAY_BUFFER; } } Buffer::~Buffer() { if(buffer) { glDeleteBuffers(1, &buffer); buffer = 0; } if(data) { free(data); data = nullptr; } } void Buffer::build() { auto type = typeToGlType(this->type); auto usage = usageToGlUsage(this->usage); checkGlError(glGenBuffers(1, &buffer)); checkGlError(glBindBuffer(type, buffer)); checkGlError(glBufferData(type, bufferSize, data, usage)); } void Buffer::bind() { if(!buffer) { build(); } checkGlError(glBindBuffer(typeToGlType(type), buffer)); } void Buffer::bindBase(uint32_t index) { if(!buffer) { build(); } checkGlError(glBindBufferBase(typeToGlType(type), index, buffer)); } void Buffer::setData(const void* data, size_t size) { if(bufferSize < size || !this->data) { this->data = realloc(this->data, size); } auto type = typeToGlType(this->type); auto usage = usageToGlUsage(this->usage); memcpy(this->data, data, size); bufferSize = size; checkGlError(glBufferData(type, bufferSize, data, usage)); } void Buffer::mapBuffer(const std::function<void(const void* const)>& func) { bind(); auto type = typeToGlType(this->type); GLvoid* p = glMapBuffer(type, GL_READ_ONLY); func(p); glUnmapBuffer(type); } void Buffer::mapWritableBuffer(const std::function<void(void*)>& func) { bind(); auto type = typeToGlType(this->type); GLvoid* p = glMapBuffer(type, GL_READ_WRITE); func(p); glUnmapBuffer(type); } void Buffer::_writeContentsToFile(const char* fileName) { mapBuffer([this, fileName] (const void* const ptr) { std::ofstream ff("yes.bin"); ff.write((const char*) ptr, this->bufferSize); ff.close(); }); }
27.656863
76
0.658632
DanielAcedo
e1a014d86af5c163b8c2c37e92e01d22b1f75dff
17,910
cpp
C++
dev/Gems/CryLegacy/Code/Source/CryAnimation/ModelMesh_DebugPC.cpp
brianherrera/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
[ "AML" ]
1,738
2017-09-21T10:59:12.000Z
2022-03-31T21:05:46.000Z
dev/Gems/CryLegacy/Code/Source/CryAnimation/ModelMesh_DebugPC.cpp
ArchitectureStudios/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
[ "AML" ]
427
2017-09-29T22:54:36.000Z
2022-02-15T19:26:50.000Z
dev/Gems/CryLegacy/Code/Source/CryAnimation/ModelMesh_DebugPC.cpp
ArchitectureStudios/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
[ "AML" ]
671
2017-09-21T08:04:01.000Z
2022-03-29T14:30:07.000Z
/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ // Original file Copyright Crytek GMBH or its affiliates, used under license. #include "CryLegacy_precompiled.h" #include <IRenderAuxGeom.h> #include "ModelMesh.h" #include "Model.h" #ifdef EDITOR_PCDEBUGCODE extern float g_YLine; //-------------------------------------------------------------------- //--- hex-dump of model --- //-------------------------------------------------------------------- void CModelMesh::ExportModel(IRenderMesh* pIRenderMesh) { #if 0 DynArray<Vec3> arrSrcPositions; DynArray<Quat> arrSrcQTangents; DynArray<Vec2> arrSrcUV; DynArray<BoneIndices8> arrSrcBoneIDs; DynArray<BoneWeights8> arrSrcVWeights; uint32 numExtIndices = pIRenderMesh->GetIndicesCount(); uint32 numExtVertices = pIRenderMesh->GetVerticesCount(); uint32 vsize = m_arrSrcPositions.size(); if (vsize < numExtVertices) { arrSrcPositions.resize(numExtVertices); arrSrcQTangents.resize(numExtVertices); arrSrcVWeights.resize(numExtVertices); arrSrcUV.resize(numExtVertices); } pIRenderMesh->LockForThreadAccess(); vtx_idx* pIndices = pIRenderMesh->GetIndexPtr(FSL_READ); int32 nPositionStride; uint8* pPositions = pIRenderMesh->GetPosPtr(nPositionStride, FSL_READ); if (pPositions == 0) { return; } int32 nQTangentStride; uint8* pQTangents = pIRenderMesh->GetQTangentPtr(nQTangentStride, FSL_READ); if (pQTangents == 0) { return; } int32 nUVStride; uint8* pUV = pIRenderMesh->GetUVPtr(nUVStride, FSL_READ); if (pUV == 0) { return; } int32 nSkinningStride; uint8* pSkinningInfo = pIRenderMesh->GetHWSkinPtr(nSkinningStride, FSL_READ); //pointer to weights and bone-id if (pSkinningInfo == 0) { return; } ++m_iThreadMeshAccessCounter; //convert hw-buffer into sw-buffer for (uint32 i = 0; i < numExtVertices; ++i) { Vec3 wpos = *((Vec3*) (pPositions + i * nPositionStride)); SPipQTangents QTangent = *(SPipQTangents*)(pQTangents + i * nQTangentStride); Vec2 uv = *((Vec2*) (pUV + i * nUVStride)); ColorB weights = *(ColorB*)&((SVF_W4B_I4B*)(pSkinningInfo + i * nSkinningStride))->weights; arrSrcPositions[i] = wpos; arrSrcQTangents[i] = QTangent.GetQ(); assert(m_arrSrcQTangents[i].IsUnit()); arrSrcVWeights[i].w0 = weights[0] / 255.0f; arrSrcVWeights[i].w1 = weights[1] / 255.0f; arrSrcVWeights[i].w2 = weights[2] / 255.0f; arrSrcVWeights[i].w3 = weights[3] / 255.0f; arrSrcUV[i].x = uv.x; arrSrcUV[i].y = uv.y; } //initialize bone indices if (m_arrSrcBoneIDs.size() != numExtVertices) { m_arrSrcBoneIDs.resize(numExtVertices); memset(&m_arrSrcBoneIDs[0], 0, numExtVertices * sizeof(BoneIndices8)); uint32 numSubsets = m_arrRenderChunks.size(); for (uint32 s = 0; s < numSubsets; s++) { uint32 startIndex = m_arrRenderChunks[s].m_nFirstIndexId; uint32 endIndex = m_arrRenderChunks[s].m_nFirstIndexId + m_arrRenderChunks[s].m_nNumIndices; for (uint32 idx = startIndex; idx < endIndex; ++idx) { uint32 e = pIndices[idx]; ColorB hwBoneIDs = *(ColorB*)&((SVF_W4B_I4B*)(pSkinningInfo + e * nSkinningStride))->indices; ColorB hwWeights = *(ColorB*)&((SVF_W4B_I4B*)(pSkinningInfo + e * nSkinningStride))->weights; uint32 _id0 = hwBoneIDs[0]; uint32 _id1 = hwBoneIDs[1]; uint32 _id2 = hwBoneIDs[2]; uint32 _id3 = hwBoneIDs[3]; if (hwWeights[0]) { arrSrcBoneIDs[e].idx0 = _id0; } if (hwWeights[1]) { arrSrcBoneIDs[e].idx1 = _id1; } if (hwWeights[2]) { arrSrcBoneIDs[e].idx2 = _id2; } if (hwWeights[3]) { arrSrcBoneIDs[e].idx3 = _id3; } } } } //-------------------------------------------------------------------------------- //-- dump all vertices //-------------------------------------------------------------------------------- FILE* vstream = nullptr; fopen_s(&vstream, "c:\\VBuffer.txt", "w+b"); for (uint32 v = 0; v < numExtVertices; v++) { fprintf(vstream, " {%15.10ff,%15.10ff,%15.10ff, %15.10ff,%15.10ff,%15.10ff,%15.10ff, %15.10ff,%15.10ff }, //%04x", arrSrcPositions[v].x, arrSrcPositions[v].y, arrSrcPositions[v].z, arrSrcQTangents[v].v.x, arrSrcQTangents[v].v.y, arrSrcQTangents[v].v.z, arrSrcQTangents[v].w, arrSrcUV[v].x, arrSrcUV[v].y, v); fprintf(vstream, "\r\n"); } fprintf(vstream, "\r\n\r\n"); fclose(vstream); //-------------------------------------------------------------------------------- //-- dump all indices //-------------------------------------------------------------------------------- FILE* istream = nullptr; fopen_s(&istream, "c:\\IBuffer.txt", "w+b"); for (uint32 f = 0; f < numExtIndices; f = f + 3) { fprintf(istream, "0x%04x,0x%04x,0x%04x, //0x%08x", pIndices[f + 0], pIndices[f + 1], pIndices[f + 2], f / 3); fprintf(istream, "\r\n"); } fprintf(istream, "\r\n\r\n"); fclose(istream); //-------------------------------------------------------------------------------- //-- dump all subsets //-------------------------------------------------------------------------------- /*uint32 numSubsets = m_arrSubsets.size(); FILE* sstream = nullptr; fopen_s(&sstream, "c:\\Subsets.txt", "w+b" ); for (uint32 s=0; s<numSubsets; s++) { fprintf(sstream, "0x%08x,0x%08x, 0x%08x,0x%08x, 0x%04x, //0x%08x", m_arrSubsets[s].nFirstVertId,m_arrSubsets[s].nNumVerts, m_arrSubsets[s].nFirstIndexId,m_arrSubsets[s].nNumIndices/3, m_arrSubsets[s].nMatID, s); fprintf(vstream, "\r\n"); } fprintf(sstream, "\r\n\r\n"); fclose(sstream);*/ pIRenderMesh->UnLockForThreadAccess(); --m_iThreadMeshAccessCounter; if (m_iThreadMeshAccessCounter == 0) { pIRenderMesh->UnlockStream(VSF_GENERAL); pIRenderMesh->UnlockStream(VSF_TANGENTS); pIRenderMesh->UnlockStream(VSF_HWSKIN_INFO); } #endif } void CModelMesh::DrawWireframeStatic(const Matrix34& rRenderMat34, uint32 color) { if (m_pIRenderMesh == 0) { return; } uint32 numExtIndices = m_pIRenderMesh->GetIndicesCount(); uint32 numExtVertices = m_pIRenderMesh->GetVerticesCount(); assert(numExtVertices); static std::vector<Vec3> arrExtSkinnedStream; uint32 vsize = arrExtSkinnedStream.size(); if (vsize < numExtVertices) { arrExtSkinnedStream.resize(numExtVertices); } m_pIRenderMesh->LockForThreadAccess(); uint32 numIndices = m_pIRenderMesh->GetIndicesCount(); vtx_idx* pIndices = m_pIRenderMesh->GetIndexPtr(FSL_READ); int32 nPositionStride; uint8* pPositions = m_pIRenderMesh->GetPosPtr(nPositionStride, FSL_READ); if (pPositions == 0) { return; } ++m_iThreadMeshAccessCounter; for (uint32 e = 0; e < numExtVertices; e++) { Vec3 v = *(Vec3*)(pPositions + e * nPositionStride); arrExtSkinnedStream[e] = rRenderMat34 * (v + m_vRenderMeshOffset); } m_pIRenderMesh->UnLockForThreadAccess(); --m_iThreadMeshAccessCounter; if (m_iThreadMeshAccessCounter == 0) { m_pIRenderMesh->UnlockStream(VSF_GENERAL); m_pIRenderMesh->UnlockStream(VSF_TANGENTS); m_pIRenderMesh->UnlockStream(VSF_HWSKIN_INFO); } SAuxGeomRenderFlags renderFlags(e_Def3DPublicRenderflags); renderFlags.SetFillMode(e_FillModeWireframe); renderFlags.SetDrawInFrontMode(e_DrawInFrontOn); renderFlags.SetAlphaBlendMode(e_AlphaAdditive); g_pAuxGeom->SetRenderFlags(renderFlags); g_pAuxGeom->DrawTriangles(&arrExtSkinnedStream[0], numExtVertices, pIndices, numExtIndices, color); } #endif void CModelMesh::DrawDebugInfo(CDefaultSkeleton* pCSkel, int nLOD, const Matrix34& rRenderMat34, int DebugMode, const _smart_ptr<IMaterial>& pMaterial, CRenderObject* pObj, const SRendParams& RendParams, bool isGeneralPass, IRenderNode* pRenderNode, const AABB& aabb) { if (m_pIRenderMesh == 0) { return; } bool bNoText = DebugMode < 0; int32 numLODs = 1; int index = 0; Vec3 trans = rRenderMat34.GetTranslation(); float color[4] = {1, 1, 1, 1}; int nTris = m_pIRenderMesh->GetVerticesCount(); int nMats = m_pIRenderMesh->GetChunks().size(); int nRenderMats = 0; string shortName = PathUtil::GetFile(pCSkel->GetModelFilePath()); IRenderAuxGeom* pAuxGeom = g_pIRenderer->GetIRenderAuxGeom(); if (nMats) { for (int i = 0; i < nMats; ++i) { CRenderChunk& rc = m_pIRenderMesh->GetChunks()[i]; if (rc.pRE && rc.nNumIndices && rc.nNumVerts && ((rc.m_nMatFlags & MTL_FLAG_NODRAW) == 0)) { ++nRenderMats; } } } switch (DebugMode) { case 1: g_pIRenderer->DrawLabelEx(trans, 1.3f, color, true, true, "%s\n%d LOD(%i\\%i)", shortName.c_str(), nTris, nLOD + 1, numLODs); pAuxGeom->DrawAABB(pCSkel->m_ModelAABB, rRenderMat34, false, ColorB(0, 255, 255, 128), eBBD_Faceted); break; case 2: { IMaterialManager* pMatMan = g_pI3DEngine->GetMaterialManager(); int fMult = 1; //int nTris = m_pDefaultSkeleton->GetRenderMesh(nLOD)->GetSysVertCount(); ColorB clr = ColorB(255, 255, 255, 255); if (nTris >= 20000 * fMult) { clr = ColorB(255, 0, 0, 255); } else if (nTris >= 10000 * fMult) { clr = ColorB(255, 255, 0, 255); } else if (nTris >= 5000 * fMult) { clr = ColorB(0, 255, 0, 255); } else if (nTris >= 2500 * fMult) { clr = ColorB(0, 255, 255, 255); } else if (nTris > 1250 * fMult) { clr = ColorB(0, 0, 255, 255); } else { clr = ColorB(nTris / 10, nTris / 10, nTris / 10, 255); } //if (pMaterial) // pMaterial = pMatMan->GetDefaultHelperMaterial(); //if (pObj) pObj->m_II.m_AmbColor = ColorF(clr.r /*/155.0f*/, clr.g /*/155.0f*/, clr.b /*/155.0f*/, 1); if (!bNoText) { g_pIRenderer->DrawLabelEx(trans, 1.3f, color, true, true, "%d", nTris); } } break; case 3: { ////////////////////////////////////////////////////////////////////////// // Show Lods ////////////////////////////////////////////////////////////////////////// ColorB clr; if (numLODs < 2) { if (nTris <= 30) { clr = ColorB(50, 50, 50, 255); } else { clr = ColorB(255, 0, 0, 255); float fAngle = gEnv->pTimer->GetFrameStartTime().GetPeriodicFraction(1.0f) * gf_PI2; clr.g = 127 + (int)(sin(fAngle) * 120); // flashing color } } else { if (nLOD == 1) { clr = ColorB(255, 0, 0, 255); } else if (nLOD == 2) { clr = ColorB(0, 255, 0, 255); } else if (nLOD == 3) { clr = ColorB(0, 0, 255, 255); } else if (nLOD == 4) { clr = ColorB(0, 255, 255, 255); } else { clr = ColorB(255, 255, 255, 255); } } //if (pMaterial) // pMaterial = GetMatMan()->GetDefaultHelperMaterial(); if (pObj) { pObj->m_II.m_AmbColor = ColorF(clr.r, clr.g, clr.b, 1); } if (numLODs > 1 && !bNoText) { g_pIRenderer->DrawLabelEx(trans, 1.3f, color, true, true, "%d/%d", nLOD + 1, numLODs); } } break; case 4: if (m_pIRenderMesh) { int nTexMemUsage = m_pIRenderMesh->GetTextureMemoryUsage(pMaterial); g_pIRenderer->DrawLabelEx(trans, 1.3f, color, true, true, "%d", nTexMemUsage / 1024); } break; case 5: { ColorB clr; if (nRenderMats == 1) { clr = ColorB(0, 0, 255, 255); } else if (nRenderMats == 2) { clr = ColorB(0, 255, 255, 255); } else if (nRenderMats == 3) { clr = ColorB(0, 255, 0, 255); } else if (nRenderMats == 4) { clr = ColorB(255, 0, 255, 255); } else if (nRenderMats == 5) { clr = ColorB(255, 255, 0, 255); } else if (nRenderMats >= 6) { clr = ColorB(255, 0, 0, 255); } else if (nRenderMats >= 11) { clr = ColorB(255, 255, 255, 255); } pObj->m_II.m_AmbColor = ColorF(clr.r, clr.g, clr.b, 1); if (!bNoText) { g_pIRenderer->DrawLabelEx(trans, 1.3f, color, true, true, "%d", nRenderMats); } } break; case 6: { g_pIRenderer->DrawLabelEx(trans, 1.3f, color, true, true, "%d,%d,%d,%d", (int)(RendParams.AmbientColor.r * 255.0f), (int)(RendParams.AmbientColor.g * 255.0f), (int)(RendParams.AmbientColor.b * 255.0f), (int)(RendParams.AmbientColor.a * 255.0f) ); } break; case 7: if (m_pIRenderMesh) { int nTexMemUsage = m_pIRenderMesh->GetTextureMemoryUsage(pMaterial); g_pIRenderer->DrawLabelEx(trans, 1.3f, color, true, true, "%d,%d,%d", nTris, nRenderMats, nTexMemUsage / 1024); } break; case 21: if (m_pIRenderMesh) { AABB bbox; m_pIRenderMesh->GetBBox(bbox.min, bbox.max); bbox.SetTransformedAABB(rRenderMat34, bbox); trans = (bbox.max + bbox.min) / 2; Vec3 pos = g_pI3DEngine->GetRenderingCamera().GetPosition(); float fEntDistance = sqrt_tpl(Distance::Point_AABBSq(pos, bbox)); // activate objects before they get really visible g_pIRenderer->DrawLabelEx(trans, 1.3f, color, true, true, "%.2f", fEntDistance); } break; case -21: if (m_pIRenderMesh) { AABB bbox; m_pIRenderMesh->GetBBox(bbox.min, bbox.max); bbox.SetTransformedAABB(rRenderMat34, bbox); trans = (bbox.max + bbox.min) / 2; Vec3 pos = g_pI3DEngine->GetRenderingCamera().GetPosition(); float fEntDistance = sqrt_tpl(Distance::Point_AABBSq(pos, bbox)); // activate objects before they get really visible g_pIRenderer->DrawLabelEx(trans, 1.3f, color, true, true, "%.2f (%s)", fEntDistance, m_pIRenderMesh->GetSourceName()); } break; case 10: if (m_pIRenderMesh) { SGeometryDebugDrawInfo dd; dd.tm = *RendParams.pMatrix; m_pIRenderMesh->DebugDraw(dd); } break; case 19: // Displays the triangle count of physic proxies. if (!bNoText) { int nPhysTrisCount = 0; #if ENABLE_CRY_PHYSICS const phys_geometry* pgeom; for (int i = pCSkel->GetJointCount() - 1; i >= 0; --i) { if (pgeom = pCSkel->GetJointPhysGeom((uint32)i)) { nPhysTrisCount += pgeom->pGeom->GetPrimitiveCount(); } } #endif // ENABLE_CRY_PHYSICS if (nPhysTrisCount == 0) { color[3] = 0.1f; } g_pIRenderer->DrawLabelEx(trans, 1.3f, color, true, true, "%d", nPhysTrisCount); } break; default: break; } #ifndef _RELEASE if (isGeneralPass && gEnv->p3DEngine->IsDebugDrawListEnabled()) { I3DEngine::SObjectInfoToAddToDebugDrawList objectInfo; objectInfo.pFileName = pCSkel->GetModelFilePath(); objectInfo.pName = pRenderNode ? pRenderNode->GetName() : ""; objectInfo.pClassName = pRenderNode ? pRenderNode->GetEntityClassName() : ""; objectInfo.texMemory = m_pIRenderMesh->GetTextureMemoryUsage(pMaterial); objectInfo.numTris = nTris; objectInfo.numVerts = nTris; objectInfo.meshMemory = m_pIRenderMesh->GetMemoryUsage(NULL, IRenderMesh::MEM_USAGE_COMBINED); objectInfo.pBox = &aabb; objectInfo.pMat = &rRenderMat34; objectInfo.type = I3DEngine::DLOT_CHARACTER; objectInfo.pRenderNode = pRenderNode; gEnv->p3DEngine->AddObjToDebugDrawList(objectInfo); } #endif }
32.802198
329
0.533892
brianherrera
e1a08f272c70065ddbe48cda94d555c2cb83ee76
4,168
cpp
C++
samples/cpp/monitoring/monitoring_reg/src/monitoring_reg.cpp
FlorianReimold/ecal
e21e52c14f58e1cae38e3867940bf0292f5ccb9a
[ "Apache-2.0" ]
null
null
null
samples/cpp/monitoring/monitoring_reg/src/monitoring_reg.cpp
FlorianReimold/ecal
e21e52c14f58e1cae38e3867940bf0292f5ccb9a
[ "Apache-2.0" ]
null
null
null
samples/cpp/monitoring/monitoring_reg/src/monitoring_reg.cpp
FlorianReimold/ecal
e21e52c14f58e1cae38e3867940bf0292f5ccb9a
[ "Apache-2.0" ]
null
null
null
/* ========================= eCAL LICENSE ================================= * * Copyright (C) 2016 - 2019 Continental Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * ========================= eCAL LICENSE ================================= */ #include <ecal/ecal.h> #include <iostream> #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable: 4100 4127 4146 4505 4800 4189 4592) // disable proto warnings #endif #include "ecal/pb/ecal.pb.h" #ifdef _MSC_VER #pragma warning(pop) #endif void OnProcessRegistration(const char* sample_, int sample_size_) { eCAL::pb::Sample sample; if (sample.ParseFromArray(sample_, sample_size_)) { std::cout << std::endl; std::cout << "----------------------------------" << std::endl; std::cout << "Process Registration" << std::endl; std::cout << "----------------------------------" << std::endl; std::cout << sample.DebugString(); std::cout << std::endl; } } void OnServiceRegistration(const char* sample_, int sample_size_) { eCAL::pb::Sample sample; if (sample.ParseFromArray(sample_, sample_size_)) { std::cout << std::endl; std::cout << "----------------------------------" << std::endl; std::cout << "Service Registration" << std::endl; std::cout << "----------------------------------" << std::endl; std::cout << sample.DebugString(); std::cout << std::endl; } } void OnSubscriberRegistration(const char* sample_, int sample_size_) { eCAL::pb::Sample sample; if (sample.ParseFromArray(sample_, sample_size_)) { std::cout << std::endl; std::cout << "----------------------------------" << std::endl; std::cout << "Subscriber Registration" << std::endl; std::cout << "----------------------------------" << std::endl; std::cout << sample.DebugString(); std::cout << std::endl; } } void OnPublisherRegistration(const char* sample_, int sample_size_) { eCAL::pb::Sample sample; if (sample.ParseFromArray(sample_, sample_size_)) { std::cout << std::endl; std::cout << "----------------------------------" << std::endl; std::cout << "Publisher Registration" << std::endl; std::cout << "----------------------------------" << std::endl; std::cout << sample.DebugString(); std::cout << std::endl; } } int main(int argc, char **argv) { // initialize eCAL API eCAL::Initialize(argc, argv, "monitoring registrations", eCAL::Init::None); // set process state eCAL::Process::SetState(proc_sev_healthy, proc_sev_level1, "I feel good !"); // add process register callback function eCAL::Process::AddRegistrationCallback(reg_event_process, std::bind(OnProcessRegistration, std::placeholders::_1, std::placeholders::_2)); // add service register callback function eCAL::Process::AddRegistrationCallback(reg_event_service, std::bind(OnServiceRegistration, std::placeholders::_1, std::placeholders::_2)); // add subscriber register callback function eCAL::Process::AddRegistrationCallback(reg_event_subscriber, std::bind(OnSubscriberRegistration, std::placeholders::_1, std::placeholders::_2)); // add publisher register callback function eCAL::Process::AddRegistrationCallback(reg_event_publisher, std::bind(OnPublisherRegistration, std::placeholders::_1, std::placeholders::_2)); while(eCAL::Ok()) { // sleep 100 ms eCAL::Process::SleepMS(100); } // finalize eCAL API eCAL::Finalize(); return(0); }
34.733333
146
0.584693
FlorianReimold
e1a2c5aaa65f9c17263bfe8ba6a8f79237b2b78c
3,198
cpp
C++
study/cyan/ACLB.cpp
rajyan/AtCoder
2c1187994016d4c19b95489d2f2d2c0eab43dd8e
[ "MIT" ]
1
2021-06-01T17:13:44.000Z
2021-06-01T17:13:44.000Z
study/cyan/ACLB.cpp
rajyan/AtCoder
2c1187994016d4c19b95489d2f2d2c0eab43dd8e
[ "MIT" ]
null
null
null
study/cyan/ACLB.cpp
rajyan/AtCoder
2c1187994016d4c19b95489d2f2d2c0eab43dd8e
[ "MIT" ]
null
null
null
//#ifdef _DEBUG //#include "../../../library/src/debug_template.hpp" //#define DMP(...) dump(#__VA_ARGS__, __VA_ARGS__) //#else //#define DMP(...) ((void)0) //#endif // //#include <cassert> //#include <cstdio> //#include <cmath> //#include <iostream> //#include <iomanip> //#include <vector> //#include <set> //#include <map> //#include <unordered_map> //#include <queue> //#include <numeric> //#include <algorithm> //#include <bitset> //#include <functional> // //using namespace std; //using lint = long long; //constexpr int MOD = 1000000007, INF = 1010101010; //constexpr lint LINF = 1LL << 60; // //struct init { // init() { // cin.tie(nullptr); ios::sync_with_stdio(false); // cout << fixed << setprecision(10); // } //} init_; // //template <typename T> //struct SegmentTree { // using F = function<T(T, T)>; // int n; // F f; // T ti; // vector<T> dat; // // SegmentTree(F f, T ti) :f(f), ti(ti) {} // // void init(int n_) { // n = 1; // while (n < n_) n <<= 1; // dat.assign(n << 1, ti); // } // // void build(const vector<T>& v) { // int n_ = v.size(); // init(n_); // for (int i = 0; i < n_; i++) dat[n + i] = v[i]; // for (int i = n - 1; i; i--) // dat[i] = f(dat[(i << 1) | 0], dat[(i << 1) | 1]); // } // // void set_val(int k, T x) { // dat[k += n] = x; // while (k >>= 1) // dat[k] = f(dat[(k << 1) | 0], dat[(k << 1) | 1]); // } // // T query(int a, int b) { // if (a >= b) return ti; // T vl = ti, vr = ti; // for (int l = a + n, r = b + n; l < r; l >>= 1, r >>= 1) { // if (l & 1) vl = f(vl, dat[l++]); // if (r & 1) vr = f(dat[--r], vr); // } // return f(vl, vr); // } // // template<typename C> // int find(int st, C& check, T& acc, int k, int l, int r) { // if (l + 1 == r) { // acc = f(acc, dat[k]); // return check(acc) ? k - n : -1; // } // int m = (l + r) >> 1; // if (m <= st) return find(st, check, acc, (k << 1) | 1, m, r); // if (st <= l and !check(f(acc, dat[k]))) { // acc = f(acc, dat[k]); // return -1; // } // int vl = find(st, check, acc, (k << 1) | 0, l, m); // if (~vl) return vl; // return find(st, check, acc, (k << 1) | 1, m, r); // } // // template<typename C> // int find(int st, C& check) { // T acc = ti; // return find(st, check, acc, 1, 0, n); // } //}; // //template<class T> //inline bool chmax(T& a, const T b) { return a < b && (a = b, true); } // //int main() { // // int N, K; // cin >> N >> K; // // vector<int> A(N); // for (int i = 0; i < N; i++) cin >> A[i]; // // constexpr int A_max = 333333; // auto f = [](int a, int b) { return max(a, b); }; // SegmentTree<int> sg(f, 0); // sg.init(A_max); // // int ans = 0; // for (int i = 0; i < N; i++) { // int L = max(A[i] - K, 0); // int R = min(A[i] + K + 1, A_max); // int now = sg.query(L, R) + 1; // sg.set_val(A[i], now); // chmax(ans, now); // } // // cout << ans << "\n"; // // return 0; //}
24.984375
71
0.430894
rajyan
e1a5494cbf657c73e653eb7cf9d07be18a4ce751
1,778
cc
C++
2020/PTA/Contest/13.cc
slowbear/TrainingCode
688872b9dab784a410069b787457f8c0871648aa
[ "CC0-1.0" ]
null
null
null
2020/PTA/Contest/13.cc
slowbear/TrainingCode
688872b9dab784a410069b787457f8c0871648aa
[ "CC0-1.0" ]
null
null
null
2020/PTA/Contest/13.cc
slowbear/TrainingCode
688872b9dab784a410069b787457f8c0871648aa
[ "CC0-1.0" ]
null
null
null
#include <bits/stdc++.h> using namespace std; using LL = long long; using Pii = pair<int, int>; using Pll = pair<LL, LL>; using VI = vector<int>; using VP = vector<pair<int, int>>; #define rep(i, a, b) for (auto i = (a); i < (b); ++i) #define rev(i, a, b) for (auto i = (b - 1); i >= (a); --i) #define grep(i, u) for (auto i = gh[u]; i != -1; i = gn[i]) #define mem(x, v) memset(x, v, sizeof(x)) #define cpy(x, y) memcpy(x, y, sizeof(x)) #define SZ(V) static_cast<int>(V.size()) #define pb push_back #define mp make_pair constexpr int maxn = 10400000; int fa[maxn], vis[maxn], sz[maxn]; int n, m, l, t; inline int get_id(int x, int y, int z) { return z * n * m + x * m + y; } int find_fa(int x) { return x == fa[x] ? x : fa[x] = find_fa(fa[x]); } bool is_union(int x, int y) { return find_fa(x) == find_fa(y); } void join(int u, int v) { u = find_fa(u); v = find_fa(v); if (u != v) { fa[v] = u; sz[u] += sz[v]; } } int main() { // freopen("input.in", "r", stdin); scanf("%d%d%d%d", &n, &m, &l, &t); rep(k, 0, l) rep(i, 0, n) rep(j, 0, m) { int id = get_id(i, j, k); scanf("%d", &sz[id]); fa[id] = id; } rep(k, 0, l) rep(i, 0, n) rep(j, 0, m) { int id = get_id(i, j, k), new_id; if (!sz[id]) continue; if (i + 1 < n) { new_id = get_id(i + 1, j, k); if (sz[new_id]) join(id, new_id); } if (j + 1 < m) { new_id = get_id(i, j + 1, k); if (sz[new_id]) join(id, new_id); } if (k + 1 < l) { new_id = get_id(i, j, k + 1); if (sz[new_id]) join(id, new_id); } } LL ans = 0; rep(k, 0, l) rep(i, 0, n) rep(j, 0, m) { int id = find_fa(get_id(i, j, k)); if (vis[id]) continue; vis[id] = true; if (sz[id] >= t) ans += sz[id]; } printf("%lld\n", ans); }
25.042254
72
0.505062
slowbear
e1a8c9db065a7914aee2192ed44df63707f63045
284
cxx
C++
src/resources/components_loader/fbx_lod_group_loader.cxx
Frozen-Team/3DEngine
f0b7002a1e5912b8f49377570b226b22eec662cf
[ "MIT" ]
1
2015-10-09T22:33:43.000Z
2015-10-09T22:33:43.000Z
src/resources/components_loader/fbx_lod_group_loader.cxx
Frozen-Team/FEngine
f0b7002a1e5912b8f49377570b226b22eec662cf
[ "MIT" ]
1
2015-10-09T16:43:47.000Z
2015-10-09T22:18:52.000Z
src/resources/components_loader/fbx_lod_group_loader.cxx
Frozen-Team/FEngine
f0b7002a1e5912b8f49377570b226b22eec662cf
[ "MIT" ]
null
null
null
#include "fbx_lod_group_loader.hpp" #include <utils/f_typedefs.hpp> namespace fengine { float FbxLodGroupLoader::RetrieveThreshold(int index) const { FbxDistance threshold; auto result = this->GetThreshold(index, threshold); return result ? threshold.value() : FLT_MAX; } }
21.846154
60
0.760563
Frozen-Team
e1aa033a6952d512f8880ae9e954b1ca65d41b68
32,104
cpp
C++
src/native/QmlNet/QmlNet/qml/NetVariant.cpp
shartte/qmlnet
f7d70aa581440ae68c646dc5210acb372feaa121
[ "MIT" ]
null
null
null
src/native/QmlNet/QmlNet/qml/NetVariant.cpp
shartte/qmlnet
f7d70aa581440ae68c646dc5210acb372feaa121
[ "MIT" ]
null
null
null
src/native/QmlNet/QmlNet/qml/NetVariant.cpp
shartte/qmlnet
f7d70aa581440ae68c646dc5210acb372feaa121
[ "MIT" ]
null
null
null
#include <QmlNet/types/NetReference.h> #include <QmlNet/types/NetTypeArrayFacade.h> #include <QmlNet/qml/NetVariant.h> #include <QmlNet/qml/NetValue.h> #include <QmlNet/qml/NetJsValue.h> #include <QmlNet/qml/NetQObject.h> #include <QmlNetUtilities.h> #include <QDateTime> #include <QDebug> #include <QJSEngine> #include <QmlNet/qml/QQmlApplicationEngine.h> namespace { struct NetReferenceQmlContainer { QSharedPointer<NetReference> netReference; }; struct NetJsValueQmlContainer { QSharedPointer<NetJSValue> jsValue; }; struct NetQObjectQmlContainer { QSharedPointer<NetQObject> netQObject; }; struct NetVariantListQmlContainer { QSharedPointer<NetVariantList> netVariantList; }; } Q_DECLARE_METATYPE(NetReferenceQmlContainer) Q_DECLARE_METATYPE(NetJsValueQmlContainer) Q_DECLARE_METATYPE(NetQObjectQmlContainer) Q_DECLARE_METATYPE(NetVariantListQmlContainer) namespace { const int NetReferenceQmlContainerTypeId = qMetaTypeId<NetReferenceQmlContainer>(); const int NetJsValueQmlContainerTypeId = qMetaTypeId<NetJsValueQmlContainer>(); const int NetQObjectQmlContainerTypeId = qMetaTypeId<NetQObjectQmlContainer>(); const int NetVariantListQmlContainerTypeId = qMetaTypeId<NetVariantListQmlContainer>(); } NetVariant::NetVariant() = default; NetVariant::~NetVariant() { clearNetReference(); } NetVariantTypeEnum NetVariant::getVariantType() const { const int type = _variant.userType(); switch(type) { case QMetaType::UnknownType: return NetVariantTypeEnum_Invalid; case QMetaType::Nullptr: return NetVariantTypeEnum_Null; case QMetaType::Bool: return NetVariantTypeEnum_Bool; case QMetaType::QChar: return NetVariantTypeEnum_Char; case qMetaTypeId<qint32>(): return NetVariantTypeEnum_Int; case qMetaTypeId<quint32>(): return NetVariantTypeEnum_UInt; case qMetaTypeId<qint64>(): return NetVariantTypeEnum_Long; case qMetaTypeId<quint64>(): return NetVariantTypeEnum_ULong; case QMetaType::Float: return NetVariantTypeEnum_Float; case QMetaType::Double: return NetVariantTypeEnum_Double; case QMetaType::QString: return NetVariantTypeEnum_String; case QMetaType::QDateTime: return NetVariantTypeEnum_DateTime; case QMetaType::QSize: return NetVariantTypeEnum_Size; case QMetaType::QSizeF: return NetVariantTypeEnum_SizeF; case QMetaType::QRect: return NetVariantTypeEnum_Rect; case QMetaType::QRectF: return NetVariantTypeEnum_RectF; case QMetaType::QPoint: return NetVariantTypeEnum_Point; case QMetaType::QPointF: return NetVariantTypeEnum_PointF; case QMetaType::QVector2D: return NetVariantTypeEnum_Vector2D; case QMetaType::QVector3D: return NetVariantTypeEnum_Vector3D; case QMetaType::QVector4D: return NetVariantTypeEnum_Vector4D; case QMetaType::QQuaternion: return NetVariantTypeEnum_Quaternion; case QMetaType::QMatrix4x4: return NetVariantTypeEnum_Matrix4x4; case QMetaType::QColor: return NetVariantTypeEnum_Color; case QMetaType::QByteArray: return NetVariantTypeEnum_ByteArray; default: if(type == NetReferenceQmlContainerTypeId) { return NetVariantTypeEnum_Object; } else if(type == NetJsValueQmlContainerTypeId) { return NetVariantTypeEnum_JSValue; } else if(type == NetQObjectQmlContainerTypeId) { return NetVariantTypeEnum_QObject; } else if(type == NetVariantListQmlContainerTypeId) { return NetVariantTypeEnum_NetVariantList; } else { qWarning() << "Unknown type for NetVariant: " << _variant.typeName(); return NetVariantTypeEnum_Invalid; } } } void NetVariant::setNull() { clearNetReference(); _variant.setValue(nullptr); } void NetVariant::setNetReference(QSharedPointer<NetReference> netReference) { clearNetReference(); _variant.setValue(NetReferenceQmlContainer{ std::move(netReference) }); } QSharedPointer<NetReference> NetVariant::getNetReference() const { return getValue<NetReferenceQmlContainer>().netReference; } void NetVariant::setBool(bool value) { setValue(value); } bool NetVariant::getBool() const { return getValue<bool>(); } void NetVariant::setChar(QChar value) { setValue(value); } QChar NetVariant::getChar() const { // Try to convert the internal QString into a Char if(_variant.userType() == QMetaType::QString) { QString str = _variant.value<QString>(); if(str.length() == 1) { return str.at(0); } qWarning() << "Can't convert '" << str << "' to QChar"; return QChar::Null; } return getValue<QChar>(); } void NetVariant::setInt(qint32 value) { setValue(value); } qint32 NetVariant::getInt() const { return getValue<qint32>(); } void NetVariant::setUInt(quint32 value) { setValue(value); } quint32 NetVariant::getUInt() const { return getValue<quint32>(); } void NetVariant::setLong(qint64 value) { setValue(value); } qint64 NetVariant::getLong() const { return getValue<qint64>(); } void NetVariant::setULong(quint64 value) { setValue(value); } quint64 NetVariant::getULong() const { return getValue<quint64>(); } void NetVariant::setFloat(float value) { setValue(value); } float NetVariant::getFloat() const { return getValue<float>(); } void NetVariant::setDouble(double value) { setValue(value); } double NetVariant::getDouble() const { return getValue<double>(); } QSize NetVariant::getSize() const { return getValue<QSize>(); } void NetVariant::setSize(const QSize &value) { setValue(value); } QSizeF NetVariant::getSizeF() const { return getValue<QSizeF>(); } void NetVariant::setSizeF(const QSizeF &value) { setValue(value); } QRect NetVariant::getRect() const { return getValue<QRect>(); } void NetVariant::setRect(const QRect &value) { setValue(value); } QRectF NetVariant::getRectF() const { return getValue<QRectF>(); } void NetVariant::setRectF(const QRectF &value) { setValue(value); } QPoint NetVariant::getPoint() const { return getValue<QPoint>(); } void NetVariant::setPoint(const QPoint &value) { setValue(value); } QPointF NetVariant::getPointF() const { return getValue<QPointF>(); } void NetVariant::setPointF(const QPointF &value) { setValue(value); } QVector2D NetVariant::getVector2D() const { return getValue<QVector2D>(); } void NetVariant::setVector2D(const QVector2D &value) { setValue(value); } QVector3D NetVariant::getVector3D() const { return getValue<QVector3D>(); } void NetVariant::setVector3D(const QVector3D &value) { setValue(value); } QVector4D NetVariant::getVector4D() const { return getValue<QVector4D>(); } void NetVariant::setVector4D(const QVector4D &value) { setValue(value); } QQuaternion NetVariant::getQuaternion() const { return getValue<QQuaternion>(); } void NetVariant::setQuaternion(const QQuaternion &value) { setValue(value); } QMatrix4x4 NetVariant::getMatrix4x4() const { return getValue<QMatrix4x4>(); } void NetVariant::setMatrix4x4(const QMatrix4x4 &value) { setValue(value); } void NetVariant::setColor(const QColor& value) { setValue(value); } QColor NetVariant::getColor() const { return getValue<QColor>(); } void NetVariant::setString(const QString* value) { setValuePtr(value); } void NetVariant::setString(const QString& value) { setValue(value); } QString NetVariant::getString() const { return _variant.toString(); } void NetVariant::setBytes(QByteArray values) { setValue(values); } QByteArray NetVariant::getBytes() const { return _variant.toByteArray(); } void NetVariant::setDateTime(const QDateTime& value) { setValue(value); } QDateTime NetVariant::getDateTime() const { return getValue<QDateTime>(); } void NetVariant::setJsValue(QSharedPointer<NetJSValue> jsValue) { setValue(NetJsValueQmlContainer{ std::move(jsValue) }); } QSharedPointer<NetJSValue> NetVariant::getJsValue() const { return getValue<NetJsValueQmlContainer>().jsValue; } void NetVariant::setQObject(QSharedPointer<NetQObject> netQObject) { setValue(NetQObjectQmlContainer{ std::move(netQObject) }); } QSharedPointer<NetQObject> NetVariant::getQObject() const { return getValue<NetQObjectQmlContainer>().netQObject; } void NetVariant::setNetVariantList(QSharedPointer<NetVariantList> netVariantList) { setValue(NetVariantListQmlContainer{ std::move(netVariantList) }); } QSharedPointer<NetVariantList> NetVariant::getNetVariantList() const { return getValue<NetVariantListQmlContainer>().netVariantList; } void NetVariant::clear() { clearNetReference(); _variant.clear(); } QVariantList NetVariant::toQVariantList() const { NetVariantTypeEnum variantType = getVariantType(); if(variantType == NetVariantTypeEnum_NetVariantList) { QVariantList list; QSharedPointer<NetVariantList> netVariantList = getValue<NetVariantListQmlContainer>().netVariantList; for(int x = 0; x < netVariantList->count(); x++) { QSharedPointer<NetVariant> variant = netVariantList->get(x); list.append(variant->toQVariant()); } return list; } if(variantType == NetVariantTypeEnum_Object) { // This may be a .NET list type. // If it is, try to enumerate it. QSharedPointer<NetReference> netReference = getNetReference(); QSharedPointer<NetTypeArrayFacade> facade = netReference->getTypeInfo()->getArrayFacade(); if(facade == nullptr) { qWarning() << "The given .NET type" << netReference->getTypeInfo()->getClassName() << "can't be converted to a QVariantList"; return QVariantList(); } QVariantList list; uint count = facade->getLength(netReference); for(uint x = 0; x < count; x++) { QSharedPointer<NetVariant> item = facade->getIndexed(netReference, x); list.append(item->toQVariant()); } return list; } qWarning() << "Can't convert value" << _variant << "from" << _variant.typeName() << "to QVariantList"; return QVariantList(); } QSharedPointer<NetVariant> NetVariant::fromQJSValue(const QJSValue& qJsValue) { QSharedPointer<NetVariant> result; if(qJsValue.isNull() || qJsValue.isUndefined()) { // Nothing! } else if(qJsValue.isQObject()) { result = QSharedPointer<NetVariant>(new NetVariant()); QObject* qObject = qJsValue.toQObject(); NetValueInterface* netValue = qobject_cast<NetValueInterface*>(qObject); if(!netValue) { result->setQObject(QSharedPointer<NetQObject>(new NetQObject(qObject))); } else { result->setNetReference(netValue->getNetReference()); } } else if(qJsValue.isObject()) { result = QSharedPointer<NetVariant>(new NetVariant()); result->setJsValue(QSharedPointer<NetJSValue>(new NetJSValue(qJsValue))); } else { result = QSharedPointer<NetVariant>(new NetVariant()); QVariant variant = qJsValue.toVariant(); result->_variant = variant; } return result; } QJSValue NetVariant::toQJSValue() const { switch(getVariantType()) { case NetVariantTypeEnum_Object: { NetValue* netValue = NetValue::forInstance(getNetReference()); return sharedQmlEngine()->newQObject(netValue); } case NetVariantTypeEnum_JSValue: { return getJsValue()->getJsValue(); } default: { return sharedQmlEngine()->toScriptValue<QVariant>(toQVariant()); } } } void NetVariant::fromQVariant(const QVariant* variant, const QSharedPointer<NetVariant>& destination) { const int type = variant->userType(); switch(type) { case QMetaType::UnknownType: destination->clear(); break; case QMetaType::Bool: case QMetaType::QChar: case qMetaTypeId<qint32>(): case qMetaTypeId<quint32>(): case qMetaTypeId<qint64>(): case qMetaTypeId<quint64>(): case QMetaType::Float: case QMetaType::Double: case QMetaType::QString: case QMetaType::QByteArray: case QMetaType::QDateTime: case QMetaType::QSize: case QMetaType::QSizeF: case QMetaType::QRect: case QMetaType::QRectF: case QMetaType::QPoint: case QMetaType::QPointF: case QMetaType::QVector2D: case QMetaType::QVector3D: case QMetaType::QVector4D: case QMetaType::QQuaternion: case QMetaType::QMatrix4x4: case QMetaType::QColor: destination->setValueVariant(*variant); break; // Generally, we can convert from QUrl to QString. // QML internally uses a string for the url basic type, // but we can still get a QUrl if someone passes through // a QUrl property found on a native QQuickItem (i.e. QQuickImage::source). case QMetaType::QUrl: destination->setValueVariant(variant->value<QUrl>().toString()); break; case QMetaType::ULong: destination->setULong(variant->value<quint64>()); break; case QMetaType::Long: destination->setLong(variant->value<qint64>()); break; case QMetaType::QObjectStar: { QObject* value = variant->value<QObject*>(); if(value == nullptr) { destination->clear(); return; } NetValueInterface* netValue = qobject_cast<NetValueInterface*>(value); if(netValue) { destination->setNetReference(netValue->getNetReference()); } else { destination->setQObject(QSharedPointer<NetQObject>(new NetQObject(value))); } break; } case QMetaType::QVariantList: { QSharedPointer<NetVariantList> netVariantList = QSharedPointer<NetVariantList>(new NetVariantList()); QVariantList list = variant->value<QVariantList>(); QVariantList::iterator i; for (i = list.begin(); i != list.end(); ++i) { QVariant item = *i; netVariantList->add(NetVariant::fromQVariant(&item)); } destination->setNetVariantList(netVariantList); break; } default: if(type == qMetaTypeId<QJSValue>()) { // TODO: Either serialize this type to a string, to be deserialized in .NET, or // pass raw value to .NET to be dynamically invoked (using dynamic). // See qtdeclarative\src\plugins\qmltooling\qmldbg_debugger\qqmlenginedebugservice.cpp:184 // for serialization methods. QSharedPointer<NetJSValue> netJsValue(new NetJSValue(variant->value<QJSValue>())); destination->setJsValue(netJsValue); break; } QMetaType::TypeFlags flags = QMetaType::typeFlags(type); if(flags & QMetaType::PointerToQObject) { QObject* value = variant->value<QObject*>(); if(value == nullptr) { destination->clear(); break; } destination->setQObject(QSharedPointer<NetQObject>(new NetQObject(value))); break; } qDebug() << "Unsupported variant type: " << variant->type() << variant->typeName(); break; } } QSharedPointer<NetVariant> NetVariant::fromQVariant(const QVariant* variant) { QSharedPointer<NetVariant> result(new NetVariant()); fromQVariant(variant, result); return result; } QVariant NetVariant::toQVariant() const { QVariant variant; toQVariant(&variant); return variant; } void NetVariant::toQVariant(QVariant* variant) const { switch(getVariantType()) { case NetVariantTypeEnum_JSValue: *variant = getJsValue()->getJsValue().toVariant(); break; case NetVariantTypeEnum_Object: *variant = QVariant::fromValue<QObject*>(NetValue::forInstance(getNetReference())); break; case NetVariantTypeEnum_QObject: *variant = QVariant::fromValue<QObject*>(this->getQObject()->getQObject()); break; case NetVariantTypeEnum_NetVariantList: *variant = QVariant::fromValue(toQVariantList()); break; default: *variant = _variant; break; } } QString NetVariant::getDisplayValue() const { switch(getVariantType()) { case NetVariantTypeEnum_JSValue: return getJsValue()->getJsValue().toString(); case NetVariantTypeEnum_Object: return getNetReference()->displayName(); case NetVariantTypeEnum_QObject: return getQObject()->getQObject()->objectName(); default: return _variant.toString(); } } void NetVariant::clearNetReference() { if(_variant.canConvert<NetReferenceQmlContainer>()) { _variant.value<NetReferenceQmlContainer>().netReference.clear(); _variant.clear(); } else if(_variant.canConvert<NetJsValueQmlContainer>()) { _variant.value<NetJsValueQmlContainer>().jsValue.clear(); _variant.clear(); } else if(_variant.canConvert<NetQObjectQmlContainer>()) { _variant.value<NetQObjectQmlContainer>().netQObject.clear(); _variant.clear(); } } template<typename T> void NetVariant::setValue(const T& value) { clearNetReference(); _variant.setValue(value); } void NetVariant::setValueVariant(const QVariant& value) { Q_ASSERT(value.userType() != QMetaType::QObjectStar); Q_ASSERT(value.userType() != qMetaTypeId<QJSValue>()); Q_ASSERT(value.userType() < QMetaType::User); clearNetReference(); _variant = value; } template<typename T> void NetVariant::setValuePtr(const T* value) { if(value) { setValue(*value); } else { clear(); } } template<typename T> T NetVariant::getValue() const { if(!_variant.canConvert(qMetaTypeId<T>())) { qDebug() << "Can't convert value" << _variant << "from" << _variant.typeName() << "to" << QMetaType::typeName(qMetaTypeId<T>()); } return _variant.value<T>(); } extern "C" { struct Q_DECL_EXPORT DateTimeContainer { uchar isNull; int month; int day; int year; int hour; int minute; int second; int msec; int offsetSeconds; }; struct ColorContainer { uchar isNull; quint8 r; quint8 g; quint8 b; quint8 a; }; Q_DECL_EXPORT NetVariantContainer* net_variant_create() { NetVariantContainer* result = new NetVariantContainer(); result->variant = QSharedPointer<NetVariant>(new NetVariant()); return result; } Q_DECL_EXPORT void net_variant_destroy(NetVariantContainer* container) { delete container; } Q_DECL_EXPORT NetVariantTypeEnum net_variant_getVariantType(NetVariantContainer* container) { return container->variant->getVariantType(); } Q_DECL_EXPORT void net_variant_setNull(NetVariantContainer* container) { container->variant->setNull(); } Q_DECL_EXPORT void net_variant_setNetReference(NetVariantContainer* container, NetReferenceContainer* instanceContainer) { if(instanceContainer == nullptr) { container->variant->setNetReference(nullptr); } else { container->variant->setNetReference(instanceContainer->instance); } } Q_DECL_EXPORT NetReferenceContainer* net_variant_getNetReference(NetVariantContainer* container) { QSharedPointer<NetReference> instance = container->variant->getNetReference(); if(instance == nullptr) { return nullptr; } NetReferenceContainer* result = new NetReferenceContainer(); result->instance = instance; return result; } Q_DECL_EXPORT void net_variant_setBool(NetVariantContainer* container, uchar value) { container->variant->setBool(value == 1 ? true : false); } Q_DECL_EXPORT uchar net_variant_getBool(NetVariantContainer* container) { if(container->variant->getBool()) { return 1; } else { return 0; } } Q_DECL_EXPORT void net_variant_setChar(NetVariantContainer* container, quint16 value) { container->variant->setChar(value); } Q_DECL_EXPORT quint16 net_variant_getChar(NetVariantContainer* container) { return quint16(container->variant->getChar().unicode()); } Q_DECL_EXPORT void net_variant_setInt(NetVariantContainer* container, qint32 value) { container->variant->setInt(value); } Q_DECL_EXPORT qint32 net_variant_getInt(NetVariantContainer* container) { return container->variant->getInt(); } Q_DECL_EXPORT void net_variant_setUInt(NetVariantContainer* container, quint32 value) { container->variant->setUInt(value); } Q_DECL_EXPORT quint32 net_variant_getUInt(NetVariantContainer* container) { return container->variant->getUInt(); } Q_DECL_EXPORT void net_variant_setLong(NetVariantContainer* container, qint64 value) { container->variant->setLong(value); } Q_DECL_EXPORT qint64 net_variant_getLong(NetVariantContainer* container) { return container->variant->getLong(); } Q_DECL_EXPORT void net_variant_setULong(NetVariantContainer* container, quint64 value) { container->variant->setULong(value); } Q_DECL_EXPORT quint64 net_variant_getULong(NetVariantContainer* container) { return container->variant->getULong(); } Q_DECL_EXPORT void net_variant_setFloat(NetVariantContainer* container, float value) { container->variant->setFloat(value); } Q_DECL_EXPORT float net_variant_getFloat(NetVariantContainer* container) { return container->variant->getFloat(); } Q_DECL_EXPORT void net_variant_setDouble(NetVariantContainer* container, double value) { container->variant->setDouble(value); } Q_DECL_EXPORT double net_variant_getDouble(NetVariantContainer* container) { return container->variant->getDouble(); } Q_DECL_EXPORT void net_variant_setSize(NetVariantContainer* container, int w, int h) { container->variant->setSize(QSize(w, h)); } Q_DECL_EXPORT void net_variant_getSize(NetVariantContainer* container, int *w, int *h) { auto qtValue = container->variant->getSize(); *w = qtValue.width(); *h = qtValue.height(); } Q_DECL_EXPORT void net_variant_setSizeF(NetVariantContainer* container, float w, float h) { container->variant->setSizeF(QSizeF(w, h)); } Q_DECL_EXPORT void net_variant_getSizeF(NetVariantContainer* container, float *w, float *h) { auto qtValue = container->variant->getSizeF(); // .NET type is always single precision *w = static_cast<float>(qtValue.width()); *h = static_cast<float>(qtValue.height()); } Q_DECL_EXPORT void net_variant_setRect(NetVariantContainer* container, int x, int y, int w, int h) { container->variant->setRect(QRect(x, y, w, h)); } Q_DECL_EXPORT void net_variant_getRect(NetVariantContainer* container, int *x, int *y, int *w, int *h) { auto qtValue = container->variant->getRect(); *x = qtValue.x(); *y = qtValue.y(); *w = qtValue.width(); *h = qtValue.height(); } Q_DECL_EXPORT void net_variant_setRectF(NetVariantContainer* container, float x, float y, float w, float h) { container->variant->setRectF(QRectF(x, y, w, h)); } Q_DECL_EXPORT void net_variant_getRectF(NetVariantContainer* container, float *x, float *y, float *w, float *h) { auto qtValue = container->variant->getRectF(); // .NET type is always single precision *x = static_cast<float>(qtValue.x()); *y = static_cast<float>(qtValue.y()); *w = static_cast<float>(qtValue.width()); *h = static_cast<float>(qtValue.height()); } Q_DECL_EXPORT void net_variant_setPoint(NetVariantContainer* container, int x, int y) { container->variant->setPoint(QPoint(x, y)); } Q_DECL_EXPORT void net_variant_getPoint(NetVariantContainer* container, int *x, int *y) { auto qtValue = container->variant->getPoint(); *x = qtValue.x(); *y = qtValue.y(); } Q_DECL_EXPORT void net_variant_setPointF(NetVariantContainer* container, float x, float y) { container->variant->setPointF(QPointF(x, y)); } Q_DECL_EXPORT void net_variant_getPointF(NetVariantContainer* container, float *x, float *y) { auto qtValue = container->variant->getPointF(); // .NET type is always single precision *x = static_cast<float>(qtValue.x()); *y = static_cast<float>(qtValue.y()); } Q_DECL_EXPORT void net_variant_setVector2D(NetVariantContainer* container, float x, float y) { container->variant->setVector2D(QVector2D(x, y)); } Q_DECL_EXPORT void net_variant_getVector2D(NetVariantContainer* container, float *x, float *y) { auto qtValue = container->variant->getVector2D(); *x = qtValue.x(); *y = qtValue.y(); } Q_DECL_EXPORT void net_variant_setVector3D(NetVariantContainer* container, float x, float y, float z) { container->variant->setVector3D(QVector3D(x, y, z)); } Q_DECL_EXPORT void net_variant_getVector3D(NetVariantContainer* container, float *x, float *y, float *z) { auto qtValue = container->variant->getVector3D(); *x = qtValue.x(); *y = qtValue.y(); *z = qtValue.z(); } Q_DECL_EXPORT void net_variant_setVector4D(NetVariantContainer* container, float x, float y, float z, float w) { container->variant->setVector4D(QVector4D(x, y, z, w)); } Q_DECL_EXPORT void net_variant_getVector4D(NetVariantContainer* container, float *x, float *y, float *z, float *w) { auto qtValue = container->variant->getVector4D(); *x = qtValue.x(); *y = qtValue.y(); *z = qtValue.z(); *w = qtValue.w(); } Q_DECL_EXPORT void net_variant_setQuaternion(NetVariantContainer* container, float w, float x, float y, float z) { container->variant->setQuaternion(QQuaternion(w, x, y, z)); } Q_DECL_EXPORT void net_variant_getQuaternion(NetVariantContainer* container, float *w, float *x, float *y, float *z) { auto qtValue = container->variant->getQuaternion(); *w = qtValue.scalar(); *x = qtValue.x(); *y = qtValue.y(); *z = qtValue.z(); } Q_DECL_EXPORT void net_variant_setMatrix4x4(NetVariantContainer* container, float m11, float m12, float m13, float m14, float m21, float m22, float m23, float m24, float m31, float m32, float m33, float m34, float m41, float m42, float m43, float m44) { container->variant->setMatrix4x4(QMatrix4x4(m11, m12, m13, m14, m21, m22, m23, m24, m31, m32, m33, m34, m41, m42, m43, m44)); } Q_DECL_EXPORT void net_variant_getMatrix4x4(NetVariantContainer* container, float* m11, float* m12, float* m13, float* m14, float* m21, float* m22, float* m23, float* m24, float* m31, float* m32, float* m33, float* m34, float* m41, float* m42, float* m43, float* m44) { auto qtValue = container->variant->getMatrix4x4(); *m11 = qtValue(0, 0); *m12 = qtValue(0, 1); *m13 = qtValue(0, 2); *m14 = qtValue(0, 3); *m21 = qtValue(1, 0); *m22 = qtValue(1, 1); *m23 = qtValue(1, 2); *m24 = qtValue(1, 3); *m31 = qtValue(2, 0); *m32 = qtValue(2, 1); *m33 = qtValue(2, 2); *m34 = qtValue(2, 3); *m41 = qtValue(3, 0); *m42 = qtValue(3, 1); *m43 = qtValue(3, 2); *m44 = qtValue(3, 3); } Q_DECL_EXPORT void net_variant_setColor(NetVariantContainer* container, const ColorContainer* value) { if(value == nullptr || value->isNull) { container->variant->setColor(QColor()); } else { container->variant->setColor(QColor(value->r, value->g, value->b, value->a)); } } Q_DECL_EXPORT void net_variant_getColor(NetVariantContainer* container, ColorContainer* value) { const QColor& c = container->variant->getColor(); if(!c.isValid()) { value->isNull = 1; return; } value->isNull = 0; value->r = c.red(); value->g = c.green(); value->b = c.blue(); value->a = c.alpha(); return; } Q_DECL_EXPORT void net_variant_setString(NetVariantContainer* container, QChar* value) { if(value == nullptr) { container->variant->setString(nullptr); } else { container->variant->setString(QString(value)); } } Q_DECL_EXPORT QmlNetStringContainer* net_variant_getString(NetVariantContainer* container) { const QString& string = container->variant->getString(); if(string.isNull()) { return nullptr; } return createString(string); } Q_DECL_EXPORT void net_variant_setBytes(NetVariantContainer* container, const char* value, int count) { if(value == nullptr) { container->variant->setBytes(nullptr); } else { container->variant->setBytes(QByteArray::fromRawData(value, count)); } } Q_DECL_EXPORT const char* net_variant_getBytes(NetVariantContainer* container, int &count) { const QByteArray byteArray = container->variant->getBytes(); if(byteArray.isNull()) { count = 0; return nullptr; } else { count = byteArray.count();; return byteArray.constData(); } } Q_DECL_EXPORT void net_variant_setDateTime(NetVariantContainer* container, const DateTimeContainer* value) { if(value == nullptr || value->isNull) { container->variant->setDateTime(QDateTime()); } else { container->variant->setDateTime(QDateTime(QDate(value->year, value->month, value->day), QTime(value->hour, value->minute, value->second, value->msec), Qt::OffsetFromUTC, value->offsetSeconds)); } } Q_DECL_EXPORT void net_variant_getDateTime(NetVariantContainer* container, DateTimeContainer* value) { const QDateTime& dt = container->variant->getDateTime(); if(dt.isNull()) { value->isNull = 1; return; } if(!dt.isValid()) { qWarning() << "QDateTime is invalid"; value->isNull = 1; return; } value->isNull = 0; const QDate& date = dt.date(); const QTime& time = dt.time(); value->year = date.year(); value->month = date.month(); value->day = date.day(); value->hour = time.hour(); value->minute = time.minute(); value->second = time.second(); value->msec = time.msec(); value->offsetSeconds = dt.offsetFromUtc(); } Q_DECL_EXPORT void net_variant_setJsValue(NetVariantContainer* container, NetJSValueContainer* jsValueContainer) { if(jsValueContainer == nullptr) { container->variant->setJsValue(nullptr); } else { container->variant->setJsValue(jsValueContainer->jsValue); } } Q_DECL_EXPORT NetJSValueContainer* net_variant_getJsValue(NetVariantContainer* container) { const QSharedPointer<NetJSValue>& instance = container->variant->getJsValue(); if(instance == nullptr) { return nullptr; } NetJSValueContainer* result = new NetJSValueContainer(); result->jsValue = instance; return result; } Q_DECL_EXPORT void net_variant_setQObject(NetVariantContainer* container, NetQObjectContainer* qObjectContainer) { if(qObjectContainer == nullptr) { container->variant->setQObject(nullptr); } else { container->variant->setQObject(qObjectContainer->qObject); } } Q_DECL_EXPORT NetQObjectContainer* net_variant_getQObject(NetVariantContainer* container) { const QSharedPointer<NetQObject>& instance = container->variant->getQObject(); if(instance == nullptr) { return nullptr; } NetQObjectContainer* result = new NetQObjectContainer(); result->qObject = instance; return result; } Q_DECL_EXPORT void net_variant_setNetVariantList(NetVariantContainer* container, NetVariantListContainer* netVariantListContainer) { if(netVariantListContainer == nullptr) { container->variant->setNetVariantList(nullptr); } else { container->variant->setNetVariantList(netVariantListContainer->list); } } Q_DECL_EXPORT NetVariantListContainer* net_variant_getNetVariantList(NetVariantContainer* container) { const QSharedPointer<NetVariantList>& netVariantList = container->variant->getNetVariantList(); if(netVariantList == nullptr) { return nullptr; } return new NetVariantListContainer { netVariantList }; } Q_DECL_EXPORT void net_variant_clear(NetVariantContainer* container) { container->variant->clear(); } }
29.291971
269
0.688637
shartte
e1ad661419da55fdae9db64d98fe71cd237068be
4,385
cpp
C++
cpp_Midterm_Project/Polynomial.cpp
NgocNguyenGit/cpp-programming
54dc1ce7b5ae8c80f790c677faea6ad2ddb29e22
[ "MIT" ]
null
null
null
cpp_Midterm_Project/Polynomial.cpp
NgocNguyenGit/cpp-programming
54dc1ce7b5ae8c80f790c677faea6ad2ddb29e22
[ "MIT" ]
null
null
null
cpp_Midterm_Project/Polynomial.cpp
NgocNguyenGit/cpp-programming
54dc1ce7b5ae8c80f790c677faea6ad2ddb29e22
[ "MIT" ]
null
null
null
// // Polynomial.cpp // cpp_Midterm2 // // Created by Nguyen Le Khanh Ngoc on 11/11/2020. // Copyright © 2020 Nguyen Le Khanh Ngoc. All rights reserved. // #include "Polynomial.h" #include <string> //string type #include <string.h> #include <vector> //vector #include <ctype.h> //isalpha #include <iostream> #include <algorithm> #include <cctype> using namespace std; //Constructor Polynomial::Polynomial (string num){ //Polynomial cout<<"p"<<num<<": "; string f; cin>>f; parsePoly(f); } //Constructor Polynomial::Polynomial(vector<Term> terms){ t.reserve(terms.size()); t.insert(t.end(), terms.begin(), terms.end()); } //Parse and set string to each term void Polynomial::parsePoly(const string str){ size_t position = 0; //point each char in string string temp, term; for (int i = 0; i < str.size(); i++){ //reach + or - => save to temp data on the left if (str[i] != '+' && str[i] != '-'){ temp += str[i]; } else{ temp += ";"; temp += str[i]; } } //add ; after an element temp += ";"; //error handling e.g. ;-4xy;+2 if (temp[0] == ';'){ temp.erase(0,1); } while ((position = temp.find(";")) != string::npos) { //reach ; => push back the left term && erase it term = temp.substr(0, position); t.push_back(Term(term)); temp.erase(0, position + 1); } } Polynomial Polynomial::operator* (const Polynomial& p){ vector<Term> new_terms; for (int i = 0; i < t.size(); i++){ for (int j = 0; j < p.t.size(); j++){ new_terms.push_back(t[i] * p.t[j]); } } return Polynomial(new_terms); } ostream& operator<< (ostream& output, const Polynomial& p){ cout<<"p1 * p2 = p3: "; for (int i = 0; i < p.t.size(); ++i){ for (int j = 0; j < p.t[i].getElement().size(); ++j){ //first element always contains coeff if (j == 0){ //if 1x => x if(p.t[i].getElement()[j+1].getCoeff() == 1){ //e.g. test: p1:-3x^2-1 result = 3x^2+3x^3y+1+xy // p2:-1-xy instead= 3x^2+3x^3y+1+1xy if(p.t[i].getElement()[j].getCoeff() == 1){ output<<""; } else if (p.t[i].getElement()[j].getCoeff() == -1){ output<<"-"; } else { output<<p.t[i].getElement()[j].getCoeff(); } } else { output<<p.t[i].getElement()[j].getCoeff(); } } else { //if 1x^1 => print only 1x else print e.g. x^2 if (p.t[i].getElement()[j].getExp() == 1){ output<<p.t[i].getElement()[j].getVar(); } else { output<<p.t[i].getElement()[j].getVar()<<"^"<< p.t[i].getElement()[j].getExp(); } } } if (i != p.t.size() -1){ //error handling: trailing plus otherwise -4x^2y+3+ //error handling: no add + before negative coeff e.g. -36x^2 instead +-36x^2 if (p.t[i+1].getElement()[0].getCoeff() < 0){ continue; } cout << "+"; } } return output << endl; } //evaluate void Polynomial::evaluate(){ vector<char> store_var; vector<double> store_value; double temp; long double sum{0.0}; for (int i = 0; i < t.size(); ++i){ for (int j = 0; j < t[i].getElement().size(); ++j){ if (isalpha (t[i].getElement()[j].getVar())){ //check if variable already print or not if (find(store_var.begin(), store_var.end(), t[i].getElement()[j].getVar()) != store_var.end()) { continue; } cout<<t[i].getElement()[j].getVar()<<": "; cin>>temp; store_value.push_back(temp); store_var.push_back(t[i].getElement()[j].getVar()); //sum of terms } } } for (int i = 0; i < t.size(); ++i){ sum += t[i].evaluateTerm(store_var, store_value); } cout<<"Result: "<<sum<<endl; }
30.880282
113
0.461345
NgocNguyenGit
e1adc846bdf3d52c36fcf7fd7ec9c5f3e7b03cec
958
cpp
C++
d2suite/src/test/test_orl.cpp
bobye/d2suite
b5a76af2be8a35ac2194865d58fe6424394c042d
[ "Apache-2.0" ]
1
2019-08-21T04:47:05.000Z
2019-08-21T04:47:05.000Z
d2suite/src/test/test_orl.cpp
bobye/d2suite
b5a76af2be8a35ac2194865d58fe6424394c042d
[ "Apache-2.0" ]
null
null
null
d2suite/src/test/test_orl.cpp
bobye/d2suite
b5a76af2be8a35ac2194865d58fe6424394c042d
[ "Apache-2.0" ]
null
null
null
#include "../common/d2.hpp" #include "../learn/wm3.hpp" #include <string> #include <sstream> #include <time.h> int main(int argc, char** argv) { using namespace d2; server::Init(argc, argv); size_t len = 864, size=400; Block<Elem<def::Histogram, 0> > data (size, len); std::string filename("data/orl/orl.d2s"); data.read(filename, size); size_t k = 40; Block<Elem<def::Histogram, 0> > wm3 (k, 864); for (size_t i=0; i<k; ++i) { std::string uniform_sample = "0 864 "; srand (i); for (size_t i=1; i<=864; ++i) { uniform_sample += std::to_string(rand()%100+1) + " "; } std::istringstream istr (uniform_sample); wm3.append(istr); } WM3_SA(wm3, data, 1000, .05, 2., 20); wm3.write("data/orl/mixture_" + std::to_string(k) + "n.txt"); std::ofstream f; f.open("data/orl/real.d2s"); for (size_t i=0; i<size; ++i) operator<<(f, data[i]); f.close(); server::Finalize(); return 0; }
22.27907
63
0.590814
bobye
e1adde2c1b645b57cf885cfbaed40e1f564842da
4,730
tcc
C++
libiop/algebra/utils.tcc
alexander-zw/libiop
a2ed2ec2f3e85f29b6035951553b02cb737c817a
[ "MIT" ]
null
null
null
libiop/algebra/utils.tcc
alexander-zw/libiop
a2ed2ec2f3e85f29b6035951553b02cb737c817a
[ "MIT" ]
null
null
null
libiop/algebra/utils.tcc
alexander-zw/libiop
a2ed2ec2f3e85f29b6035951553b02cb737c817a
[ "MIT" ]
null
null
null
#include <cassert> #include <sodium/randombytes.h> #include <libff/common/utils.hpp> namespace libiop { template<typename T> std::vector<T> all_subset_sums(const std::vector<T> &basis, const T& shift) { const size_t m = basis.size(); std::vector<T> result; /* as we are I/O-bound here, reserve + emplace_back is ~2x faster then pre-initializing with zero and then overwriting (as per benchmark_vector_op.cpp) */ result.reserve(1ull<<m); result.emplace_back(shift); for (size_t i = 0; i < m; ++i) { const size_t l = (1ull<<i); for (size_t j = 0; j < l; ++j) { result.emplace_back(result[j] + basis[i]); } } return result; } template<typename FieldT> std::vector<FieldT> batch_inverse(const std::vector<FieldT> &vec, const bool has_zeroes) { return batch_inverse_and_mul(vec, FieldT::one(), has_zeroes); } template<typename FieldT> std::vector<FieldT> batch_inverse_and_mul_internal(const std::vector<FieldT> &vec, const FieldT &k) { /** Montgomery batch inversion trick. * This assumes that all elements of the input are non-zero. * It also multiplies every element by k, which can be done with one multiplication. */ std::vector<FieldT> R; R.reserve(vec.size()); FieldT c = vec[0]; R.emplace_back(c); // Set R[i] to be the product of all vec[j], where j <= 0 <= i for (size_t i = 1; i < vec.size(); ++i) { c *= vec[i]; R.emplace_back(c); } FieldT c_inv = c.inverse() * k; for (size_t i = vec.size()-1; i > 0; --i) { R[i] = R[i-1] * c_inv; c_inv *= vec[i]; } R[0] = c_inv; return R; } template<typename FieldT> std::vector<FieldT> batch_inverse_and_mul(const std::vector<FieldT> &vec, const FieldT &k, const bool has_zeroes) { /** Montgomery batch inversion trick. * This wraps the internal batch inverse and mul to handle 0's. * If we need more efficiency, we can make an entirely separate codepath for the case with zeroes, * and get rid of the loop that searches for zeroes. * We omit this optimization, as has_zeroes=false in the verifiers code path. */ if (has_zeroes) { std::vector<FieldT> vec_copy(vec); std::vector<size_t> zero_locations; FieldT zero = FieldT::zero(); for (std::size_t i = 0; i < vec.size(); i++) { if (vec_copy[i] == zero) { zero_locations.emplace_back(i); vec_copy[i] = FieldT::one(); } } std::vector<FieldT> result = batch_inverse_and_mul_internal(vec_copy, k); for (std::size_t i = 0; i < zero_locations.size(); i++) { result[zero_locations[i]] = zero; } return result; } else { return batch_inverse_and_mul_internal(vec, k); } } template<typename FieldT> void mut_batch_inverse(std::vector<FieldT> &vec) { /** Montgomery batch inversion trick, which mutates vec. * This assumes that all elements of the input are non-zero. * * The primary advantage of mut_batch_inverse is that instead of * heap allocating a vector of size vec.size() internally, an array * can be stack allocated. This matters more as the size of vec grows. */ /* Not using std::vector in order to make this stack allocated. */ FieldT vec_copy[vec.size()]; FieldT c = vec[0]; vec_copy[0] = c; // Set R[i] to be the product of all vec[j], where j <= 0 <= i for (size_t i = 1; i < vec.size(); ++i) { vec_copy[i] = vec[i]; c *= vec[i]; vec[i] = c; } FieldT c_inv = c.inverse(); for (size_t i = vec.size()-1; i > 0; --i) { vec[i] = vec[i-1] * c_inv; c_inv *= vec_copy[i]; } vec[0] = c_inv; return; } template<typename T> void bitreverse_vector(std::vector<T> &a) { const size_t n = a.size(); const size_t logn = libff::log2(n); assert(n == 1ull<<logn); for (size_t k = 0; k < n; ++k) { const size_t rk = libff::bitreverse(k, logn); if (k < rk) { std::swap(a[k], a[rk]); } } } template<typename T> std::vector<T> random_vector(const std::size_t count) { std::vector<T> result(count); randombytes_buf(result.data(), count * sizeof(T)); return result; } template<typename FieldT> std::vector<FieldT> random_FieldT_vector(const std::size_t count) { std::vector<FieldT> result; result.reserve(count); for (std::size_t i = 0; i < count; i++) { result.emplace_back(FieldT::random_element()); } return result; } } // namespace libiop
25.430108
113
0.591543
alexander-zw
e1adefc9a6192f02aa870f75ccd1c88aaea5c927
57
hh
C++
RAVL2/MSVC/include/Ravl/BfAcc2Iter.hh
isuhao/ravl2
317e0ae1cb51e320b877c3bad6a362447b5e52ec
[ "BSD-Source-Code" ]
null
null
null
RAVL2/MSVC/include/Ravl/BfAcc2Iter.hh
isuhao/ravl2
317e0ae1cb51e320b877c3bad6a362447b5e52ec
[ "BSD-Source-Code" ]
null
null
null
RAVL2/MSVC/include/Ravl/BfAcc2Iter.hh
isuhao/ravl2
317e0ae1cb51e320b877c3bad6a362447b5e52ec
[ "BSD-Source-Code" ]
null
null
null
#include "../.././Core/Container/Buffer/BfAcc2Iter.hh"
14.25
54
0.666667
isuhao
e1afc9eb1cdad6636ab0b6bab12740e3a39228dc
1,329
hh
C++
emu-ex-plus-alpha/imagine/src/base/iphone/ICadeHelper.hh
damoonvisuals/GBA4iOS
95bfce0aca270b68484535ecaf0d3b2366739c77
[ "MIT" ]
1
2018-11-14T23:40:35.000Z
2018-11-14T23:40:35.000Z
emu-ex-plus-alpha/imagine/src/base/iphone/ICadeHelper.hh
damoonvisuals/GBA4iOS
95bfce0aca270b68484535ecaf0d3b2366739c77
[ "MIT" ]
null
null
null
emu-ex-plus-alpha/imagine/src/base/iphone/ICadeHelper.hh
damoonvisuals/GBA4iOS
95bfce0aca270b68484535ecaf0d3b2366739c77
[ "MIT" ]
null
null
null
#pragma once #include <input/Input.hh> #include <input/common/iCade.hh> struct ICadeHelper { UIView *mainView, *dummyInputView; uint active, cycleResponder; void init(UIView *mainView) { if(!dummyInputView) { logMsg("init iCade helper"); dummyInputView = [[UIView alloc] initWithFrame:CGRectZero]; var_selfs(mainView); if(active) { [mainView becomeFirstResponder]; } } } void setActive(uint active) { var_selfs(active); logMsg("set iCade active %d", active); if(!mainView) return; if(active) { [mainView becomeFirstResponder]; } else { [mainView resignFirstResponder]; } } uint isActive() { return active; } void didEnterBackground() { if(active) [mainView resignFirstResponder]; } void didBecomeActive() { if(active) [mainView becomeFirstResponder]; } void insertText(NSString *text) { using namespace Input; //logMsg("got text %s", [text cStringUsingEncoding: NSUTF8StringEncoding]); char c = [text characterAtIndex:0]; Input::processICadeKey(c, PUSHED, *devList.first()); // iCade device is always added first on app init if (++cycleResponder > 20) { // necessary to clear a buffer that accumulates internally cycleResponder = 0; [mainView resignFirstResponder]; [mainView becomeFirstResponder]; } } };
17.72
104
0.68623
damoonvisuals
e1b1b6e61e6f9923adac20d196739d8053b590c1
15,878
cpp
C++
JsonDocument.cpp
JCodeARM/JSON
1447fb92e75b3cceeb90f46e3ba90e2ff1ed4a1c
[ "Unlicense" ]
null
null
null
JsonDocument.cpp
JCodeARM/JSON
1447fb92e75b3cceeb90f46e3ba90e2ff1ed4a1c
[ "Unlicense" ]
null
null
null
JsonDocument.cpp
JCodeARM/JSON
1447fb92e75b3cceeb90f46e3ba90e2ff1ed4a1c
[ "Unlicense" ]
null
null
null
// // JsonDocument.cpp // JSON // // Created by Iulian on 13.03.2013. // #include "JsonDocument.hpp" #define SHOW_LIST( list ) for (auto iteratorBeing=list.begin(); iteratorBeing != list.end(); iteratorBeing++) {\ std::cout<<(*iteratorBeing)<<std::endl;} #define SHOW_LIST_POINT( list ) for (auto iteratorBeing=list->begin(); iteratorBeing != list->end(); iteratorBeing++) {\ std::cout<<(*iteratorBeing)<<std::endl;} enum class TokenNext{ None, Start, End, }; JsonDocument::JsonDocument():lJsonRootObject(nullptr){ } JsonDocument::~JsonDocument(){ if (lJsonRootObject != nullptr) { delete lJsonRootObject; lJsonRootObject=nullptr; } } JsonDocument::JsonDocument(JsonDocument & ldoc){ lJsonRootObject=ldoc.lJsonRootObject; ldoc.lJsonRootObject=nullptr; } JsonDocument::JsonDocument(JsonDocument && ldoc){ lJsonRootObject=ldoc.lJsonRootObject; ldoc.lJsonRootObject=nullptr; } JsonObject * JsonDocument::getNodeRoot(){ if (lJsonRootObject == nullptr) { lJsonRootObject=new JsonObject(); } return lJsonRootObject; } JsonObject * JsonDocument::addObject(JsonObject * lObject,std::string &lProperty){ JsonObject *lReturn; lReturn=new JsonObject(); std::string s("\""+lProperty+"\""); lObject->addProperty(s, lReturn); return lReturn; } JsonArray * JsonDocument::addArray(JsonObject * lObject,std::string &lProperty){ JsonArray *lReturn; lReturn=new JsonArray(); std::string s("\""+lProperty+"\""); lObject->addProperty(s, lReturn); return lReturn; } void JsonDocument::addNumber(JsonObject * lObject,std::string &lProperty,double lValue){ std::string s("\""+lProperty+"\""); lObject->addProperty(s, new JsonNumber(lValue)); } void JsonDocument::addString(JsonObject * lObject,std::string &lProperty,std::string &lValue){ std::string s("\""+lProperty+"\""); lObject->addProperty(lProperty, new JsonString(s)); } void JsonDocument::addBoolean(JsonObject * lObject,std::string &lProperty,bool lValue){ std::string s("\""+lProperty+"\""); lObject->addProperty(s, new JsonBoolean(lValue)); } void JsonDocument::addNull(JsonObject * lObject,std::string &lProperty){ std::string s("\""+lProperty+"\""); lObject->addProperty(s, new JsonNull()); } JsonObject * JsonDocument::addObject(JsonArray * lArray){ JsonObject *lReturn; lReturn=new JsonObject(); lArray->additem(lReturn); return lReturn; } JsonArray * JsonDocument::addArray(JsonArray * lArray){ JsonArray *lReturn; lReturn=new JsonArray(); lArray->additem(lReturn); return lReturn; } void JsonDocument::addNumber(JsonArray * lArray,double lValue){ lArray->additem(new JsonNumber(lValue)); } void JsonDocument::addString(JsonArray * lArray,std::string &lValue){ std::string s("\""+lValue+"\""); lArray->additem(new JsonString(s)); } void JsonDocument::addBoolean(JsonArray * lArray,bool lValue){ lArray->additem(new JsonBoolean(lValue)); } void JsonDocument::addNull(JsonArray * lArray){ lArray->additem(new JsonNull()); } std::vector<char> JsonDocument::getVectorJson(JsonDocumentFormat lFormat){ std::vector<char> lReturn; switch (lFormat) { case JsonDocumentFormat::Inndenter:{ }break; case JsonDocumentFormat::Compact:{ }break; default: break; } return lReturn; } void JsonDocument::parseJson(const char* iBegin , const char* iEnd){ // BEGIN PARSS TOKEN const char *iSearch=iBegin; std::list<std::string_view> listToken; while (iSearch < iEnd) { if((*iSearch) == ':' || (*iSearch) == '{' || (*iSearch) == '}' || (*iSearch) == '[' || (*iSearch) == ']' || (*iSearch) == ','){ listToken.push_back(std::string_view(iSearch,1)); iSearch++; continue; }else if ((*iSearch) == '"'){ const char *iStart=iSearch; iSearch++; while (iSearch < iEnd) { if (std::strncmp(iSearch, "\\\"", 2) == 0){ iSearch+=2; continue; }else if((*iSearch) == '"'){ listToken.push_back(std::string_view(iStart,(iSearch-iStart)+1)); iSearch++; break; } iSearch++; } continue; }else if ((std::strncmp(iSearch, "null", 4) == 0) || (std::strncmp(iSearch, "true", 4) == 0)){ listToken.push_back(std::string_view(iSearch,4)); iSearch+=4; continue; }else if ( std::strncmp(iSearch, "false", 5) == 0){ listToken.push_back(std::string_view(iSearch,5)); iSearch+=5; continue; }else if (std::isdigit(*iSearch)){ const char *iStart=iSearch; int pointSize=0; while (iSearch < iEnd && ((std::isdigit(*iSearch)) || (*iSearch == '.' && ++pointSize)) ) { if (pointSize > 1) { throw std::string("Error Token Multi Point: File Name:"+std::string(__FILE_NAME__)+" Line:"+std::to_string(__LINE__)); } iSearch++; } listToken.push_back(std::string_view(iStart,(iSearch-iStart))); continue; } iSearch++; } // END PARSS TOKEN // BEGIN SHOW PARSS TOKEN #ifdef SHOW_TOKEN_TERMINAL SHOW_LIST(listToken) #endif // END SHOW PARSS TOKEN // BEGIN CREATE THREE OBJECT if (listToken.size() > 1 && listToken.front() == "{" && listToken.back() == "}" ) { listToken.pop_back(); listToken.pop_front(); lJsonRootObject=new JsonObject(); parseObject(lJsonRootObject,&listToken); }else{ throw std::string("Error root "); } // END CREATE THREE OBJECT } void JsonDocument::parseObject(JsonObject *lObject,std::list<std::string_view> *listStringView){ TokenNext lNextItem=TokenNext::None; for (auto iBegin=listStringView->begin(); iBegin != listStringView->end(); iBegin++) { auto iSearch=&(*iBegin); if((*iSearch).length() > 1 && (*iSearch).back() == '"' && (*iSearch).front() == '"'){ iBegin++; if ( iBegin != listStringView->end()) { if ((*iBegin) == ":") { iBegin++; if(iBegin != listStringView->end()){ if ((*iBegin) == "{"){ std::list<std::string_view> sObjectList; int tNumber=1; for ( iBegin++; iBegin != listStringView->end(); iBegin++) { if ((*iBegin) == "{") { tNumber++; }else if ((*iBegin) == "}"){ tNumber--; if (tNumber == 0) { break; } } sObjectList.push_back(*iBegin); } if (tNumber == 0 ) { std::string s(*iSearch); JsonObject *tObject= new JsonObject(); lObject->addProperty(s, tObject); parseObject(tObject,&sObjectList); lNextItem=TokenNext::End; }else{ throw std::string("Error Token {}: File Name:"+std::string(__FILE_NAME__)+" Line:"+std::to_string(__LINE__)); } }else if ((*iBegin) == "["){ std::list<std::string_view> sArrayList; int tNumber=1; for ( iBegin++; iBegin != listStringView->end(); iBegin++) { if ((*iBegin) == "[") { tNumber++; }else if ((*iBegin) == "]"){ tNumber--; if (tNumber == 0) { break; } } sArrayList.push_back(*iBegin); } if (tNumber == 0 ) { std::string s(*iSearch); JsonArray *tArray= new JsonArray(); lObject->addProperty(s, tArray); parseArray(tArray,&sArrayList); lNextItem=TokenNext::End; }else{ throw std::string("Error Token []: File Name:"+std::string(__FILE_NAME__)+" Line:"+std::to_string(__LINE__)); } }else if ((*iBegin).length() > 1 && (*iBegin).front() == '"' && (*iBegin).back() == '"'){ std::string s(*iSearch); std::string v(*iBegin); lObject->addProperty(s, new JsonString(v)); lNextItem=TokenNext::End; }else if ((*iBegin) == "null"){ std::string s(*iSearch); lObject->addProperty(s, new JsonNull()); lNextItem=TokenNext::End; }else if((*iBegin) == "true" ){ std::string s(*iSearch); lObject->addProperty(s, new JsonBoolean(true)); lNextItem=TokenNext::End; }else if ((*iBegin) == "false"){ std::string s(*iSearch); lObject->addProperty(s, new JsonBoolean(false)); lNextItem=TokenNext::End; }else if ((*iBegin).length() > 0 && std::isdigit((*iBegin).front()) ){ std::string s(*iSearch); double d=std::atof(std::string(*iBegin).data()); lObject->addProperty(s, new JsonNumber(d)); lNextItem=TokenNext::End; }else if ((*iBegin) == ",") { throw std::string("Error Token (,): File Name:"+std::string(__FILE_NAME__)+" Line:"+std::to_string(__LINE__)); } auto iteratorNextItem=iBegin; iteratorNextItem++; if (TokenNext::End == lNextItem && iteratorNextItem != listStringView->end() && (*iteratorNextItem) == ",") { iBegin=iteratorNextItem; lNextItem=TokenNext::Start; } }else{ throw std::string("Error Token : File Name:"+std::string(__FILE_NAME__)+" Line:"+std::to_string(__LINE__)); } }else{ throw std::string("Error Token : File Name:"+std::string(__FILE_NAME__)+" Line:"+std::to_string(__LINE__)); } }else{ throw std::string("Error Token : File Name:"+std::string(__FILE_NAME__)+" Line:"+std::to_string(__LINE__)); } }else{ throw std::string("Error Token ("+std::string(*iSearch)+"): File Name:"+std::string(__FILE_NAME__)+" Line:"+std::to_string(__LINE__)); } } if (lNextItem == TokenNext::Start) { throw std::string("Error Token (,): File Name:"+std::string(__FILE_NAME__)+" Line:"+std::to_string(__LINE__)); } } void JsonDocument::parseArray(JsonArray *lArray,std::list<std::string_view> *listStringView){ TokenNext lNextItem=TokenNext::None; for (auto iBegin=listStringView->begin(); iBegin != listStringView->end(); iBegin++) { if ((*iBegin) == "{") { std::list<std::string_view> sObjectList; int tNumber=1; for ( iBegin++; iBegin != listStringView->end(); iBegin++) { if ((*iBegin) == "{") { tNumber++; }else if ((*iBegin) == "}"){ tNumber--; if (tNumber == 0) { break; } } sObjectList.push_back(*iBegin); } if (tNumber == 0) { JsonObject *tObject= new JsonObject(); lArray->additem(tObject); parseObject(tObject,&sObjectList); lNextItem=TokenNext::End; }else{ throw std::string("Error Token {}: File Name:"+std::string(__FILE_NAME__)+" Line:"+std::to_string(__LINE__)); } }else if((*iBegin) == "["){ std::list<std::string_view> sArrayList; int tNumber=1; for ( iBegin++; iBegin != listStringView->end(); iBegin++) { if ((*iBegin) == "[") { tNumber++; }else if ((*iBegin) == "]"){ tNumber--; if (tNumber == 0) { break; } } sArrayList.push_back(*iBegin); } if (tNumber == 0) { JsonArray *tArray= new JsonArray(); lArray->additem( tArray); parseArray(tArray,&sArrayList); lNextItem=TokenNext::End; }else{ throw std::string("Error Token []: File Name:"+std::string(__FILE_NAME__)+" Line:"+std::to_string(__LINE__)); } }else if ((*iBegin).length() > 1 && (*iBegin).front() == '"' && (*iBegin).back() == '"'){ std::string s(*iBegin); lArray->additem(new JsonString(s)); lNextItem=TokenNext::End; }else if (std::isdigit((*iBegin).front())){ double d=std::atof(std::string(*iBegin).data()); lArray->additem(new JsonNumber(d)); lNextItem=TokenNext::End; }else if ((*iBegin) == "true"){ lArray->additem(new JsonBoolean(true)); lNextItem=TokenNext::End; }else if ((*iBegin) == "false"){ lArray->additem(new JsonBoolean(false)); lNextItem=TokenNext::End; }else if ((*iBegin) == "null"){ lArray->additem(new JsonNull()); lNextItem=TokenNext::End; }else if ((*iBegin) == ","){ throw std::string("Error Token , : File Name:"+std::string(__FILE_NAME__)+" Line:"+std::to_string(__LINE__)); } auto iteratorNextItem=iBegin; iteratorNextItem++; if (TokenNext::End == lNextItem && iteratorNextItem != listStringView->end() && (*iteratorNextItem) == ",") { iBegin=iteratorNextItem; lNextItem=TokenNext::Start; } } if (lNextItem == TokenNext::Start) { throw std::string("Error Token (,): File Name:"+std::string(__FILE_NAME__)+" Line:"+std::to_string(__LINE__)); } } JsonDocument JsonDocument::fromVecotr(std::vector<char> & lArray){ JsonDocument lReturnDoc; if(lArray.empty() == false){ const char *iBegine=lArray.data(); const char *iEnd=iBegine+lArray.size(); lReturnDoc.parseJson(iBegine, iEnd); } return lReturnDoc; } // BEGIN OPERATOR << JsonStream & operator <<(JsonStream & lout, JsonDocument & lin){ if (lin.lJsonRootObject) { lout<<(*lin.lJsonRootObject); } return lout; } // END OPERATOR <<
37.985646
146
0.489293
JCodeARM
e1b29b2cfe8efc5d2a21aa7970112f76e7e7296b
16,706
cpp
C++
Ogitor/qtOgitor/src/settingsdialog.cpp
lockie/HiveGame
bb1aa12561f1dfd956d78a53bfb7a746e119692a
[ "MIT" ]
4
2018-01-08T10:15:52.000Z
2020-11-15T14:05:50.000Z
Ogitor/qtOgitor/src/settingsdialog.cpp
lockie/HiveGame
bb1aa12561f1dfd956d78a53bfb7a746e119692a
[ "MIT" ]
null
null
null
Ogitor/qtOgitor/src/settingsdialog.cpp
lockie/HiveGame
bb1aa12561f1dfd956d78a53bfb7a746e119692a
[ "MIT" ]
1
2019-08-29T18:19:56.000Z
2019-08-29T18:19:56.000Z
/*///////////////////////////////////////////////////////////////////////////////// /// An /// ___ ____ ___ _____ ___ ____ /// / _ \ / ___|_ _|_ _/ _ \| _ \ /// | | | | | _ | | | || | | | |_) | /// | |_| | |_| || | | || |_| | _ < /// \___/ \____|___| |_| \___/|_| \_\ /// File /// /// Copyright (c) 2008-2011 Ismail TARIM <ismail@royalspor.com> and the Ogitor Team // /// The MIT License /// /// Permission is hereby granted, free of charge, to any person obtaining a copy /// of this software and associated documentation files (the "Software"), to deal /// in the Software without restriction, including without limitation the rights /// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell /// copies of the Software, and to permit persons to whom the Software is /// furnished to do so, subject to the following conditions: /// /// The above copyright notice and this permission notice shall be included in /// all copies or substantial portions of the Software. /// /// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR /// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, /// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE /// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER /// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, /// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN /// THE SOFTWARE. ////////////////////////////////////////////////////////////////////////////////*/ #include <QtGui/QMenu> #include <QtGui/QMessageBox> #include <QtGui/QFileDialog> #include <QtGui/QPainter> #include <QtGui/QColorDialog> #include <QtCore/QEvent> #include <QtCore/QDirIterator> #include <QtGui/QDragEnterEvent> #include <QtCore/QUrl> #include "settingsdialog.hxx" #include "OgitorsRoot.h" #include "OgitorsSystem.h" #include "BaseEditor.h" #include "ViewGrid.h" using namespace Ogitors; const int RES_LOC_DIR = 1; const int RES_LOC_ZIP = 2; extern QString ConvertToQString(Ogre::UTFString& value); //---------------------------------------------------------------------------------- SettingsDialog::SettingsDialog(QWidget *parent, PROJECTOPTIONS *options) : QDialog(parent, Qt::Dialog | Qt::CustomizeWindowHint | Qt::WindowTitleHint) { setupUi(this); connect(buttonBox, SIGNAL(accepted()), this, SLOT(onAccept())); connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject())); connect(mBrowseProjectDirButton, SIGNAL(clicked()), this, SLOT(browse())); mOptions = options; mProjectDirTextBox->setText(mOptions->ProjectDir.c_str()); mProjectNameTextBox->setText(mOptions->ProjectName.c_str()); mSceneMgrNameMenu->addItem("OctreeSceneManager"); mSceneMgrNameMenu->setCurrentIndex(0); mConfigFileTextBox->setText(mOptions->SceneManagerConfigFile.c_str()); mTerrainDirTextBox->setText(mOptions->TerrainDirectory.c_str()); if(!mOptions->IsNewProject) { mProjectNameTextBox->setText(QApplication::translate("QtOgitorSystem", "<Enter New Name>")); mProjectDirTextBox->setEnabled(false); mProjectNameTextBox->setEnabled(false); mSceneMgrNameMenu->setEnabled(false); mConfigFileTextBox->setEnabled(false); mTerrainDirTextBox->setEnabled(false); mBrowseProjectDirButton->setEnabled(false); } unsigned int i; QString value; for(i = 0;i < mOptions->ResourceDirectories.size();i++) { value = mOptions->ResourceDirectories[i].c_str(); value = value.right(value.length() - 3); if(mOptions->ResourceDirectories[i].find("FS:") == 0) { addResourceLocation(RES_LOC_DIR, value); } else if(mOptions->ResourceDirectories[i].find("ZP:") == 0) { addResourceLocation(RES_LOC_ZIP, value); } } mResourceListBox->installEventFilter(this); mSelRectColourWidget = new ColourPickerWidget(this, QColor(mOptions->SelectionRectColour.r * 255, mOptions->SelectionRectColour.g * 255, mOptions->SelectionRectColour.b * 255)); mSelColourWidget = new ColourPickerWidget(this, QColor(mOptions->SelectionBBColour.r * 255, mOptions->SelectionBBColour.g * 255, mOptions->SelectionBBColour.b * 255)); mHighlightColourWidget = new ColourPickerWidget(this, QColor(mOptions->HighlightBBColour.r * 255, mOptions->HighlightBBColour.g * 255, mOptions->HighlightBBColour.b * 255)); mSelectHighlightColourWidget = new ColourPickerWidget(this, QColor(mOptions->SelectHighlightBBColour.r * 255, mOptions->SelectHighlightBBColour.g * 255, mOptions->SelectHighlightBBColour.b * 255)); mSelectionGridLayout->addWidget(mSelRectColourWidget,0,1,1,1); mSelectionGridLayout->addWidget(mSelColourWidget,1,1,1,1); mSelectionGridLayout->addWidget(mHighlightColourWidget,2,1,1,1); mSelectionGridLayout->addWidget(mSelectHighlightColourWidget,3,1,1,1); mGridColourWidget = new ColourPickerWidget(this, QColor(mOptions->GridColour.r * 255, mOptions->GridColour.g * 255, mOptions->GridColour.b * 255)); mGridAppearanceLayout->addWidget(mGridColourWidget,1,1,1,1); mGridSpacingMenu->setValue(ViewportGrid::getGridSpacing()); mSnapAngleMenu->setValue(0); mSelectionDepthMenu->setValue(mOptions->VolumeSelectionDepth); mSelRectColourWidget->setMaximumSize(40,20); mSelRectColourWidget->setMinimumSize(40,20); mSelColourWidget->setMaximumSize(40,20); mSelColourWidget->setMinimumSize(40,20); mHighlightColourWidget->setMaximumSize(40,20); mHighlightColourWidget->setMinimumSize(40,20); mSelectHighlightColourWidget->setMaximumSize(40,20); mSelectHighlightColourWidget->setMinimumSize(40,20); mGridColourWidget->setMaximumSize(40,20); mGridColourWidget->setMinimumSize(40,20); tabWidget->setCurrentIndex(0); // Enable dropping on the widget setAcceptDrops(true); } //---------------------------------------------------------------------------------- SettingsDialog::~SettingsDialog() { } //---------------------------------------------------------------------------------- void SettingsDialog::browse() { QString path = QFileDialog::getExistingDirectory(QApplication::activeWindow(), "",QApplication::applicationDirPath() #if OGRE_PLATFORM == OGRE_PLATFORM_LINUX , QFileDialog::DontUseNativeDialog | QFileDialog::ShowDirsOnly); #else ); #endif if(!path.isEmpty()) mProjectDirTextBox->setText(path); } //---------------------------------------------------------------------------------- bool IsValidName(QString strName, QString strDisplayName, QString exkeys = "") { strName = strName.trimmed(); bool found = false; QString mask = "%\"<>#,?&;" + exkeys; for(int i = 0;i < mask.size();i++) { if(strName.contains(mask[i])) found = true; } if(found) { Ogre::UTFString msgTemp = OgitorsSystem::getSingletonPtr()->Translate("%1 can not contain (\"<>,\"#?&;%2\")"); QString msg = ConvertToQString(msgTemp).arg(strDisplayName).arg(exkeys); QMessageBox::warning(QApplication::activeWindow(),"qtOgitor", msg, QMessageBox::Ok); return false; } if(strName.isEmpty()) { Ogre::UTFString msgTemp = OgitorsSystem::getSingletonPtr()->Translate("%1 does not contain a valid value!"); QString msg = ConvertToQString(msgTemp).arg(strDisplayName); QMessageBox::warning(QApplication::activeWindow(),"qtOgitor", msg, QMessageBox::Ok); return false; } return true; } //---------------------------------------------------------------------------------- QString lastDirPath = ""; void SettingsDialog::addResourceLocation(int loctype, QString path) { bool found = false; for(int i = 0;i < mResourceListBox->count();i++) { if(mResourceListBox->item(i)->text() == path) { found = true; break; } } if(!found) { mResourceListBox->addItem(path); mResourceFileTypes.push_back(loctype); } } //---------------------------------------------------------------------------------- void SettingsDialog::onAddDirectory() { QString path; if(lastDirPath == "") path = QApplication::applicationDirPath(); else path = lastDirPath; path = QFileDialog::getExistingDirectory(QApplication::activeWindow(), "", path #if OGRE_PLATFORM == OGRE_PLATFORM_LINUX , QFileDialog::DontUseNativeDialog | QFileDialog::ShowDirsOnly); #else ); #endif if(!path.isEmpty()) { addResourceLocation(RES_LOC_DIR, path); lastDirPath = path; } } //---------------------------------------------------------------------------------- void SettingsDialog::onAddDirectoryRecursive() { QString path; if(lastDirPath == "") path = QApplication::applicationDirPath(); else path = lastDirPath; path = QFileDialog::getExistingDirectory(QApplication::activeWindow(), "", path #if OGRE_PLATFORM == OGRE_PLATFORM_LINUX , QFileDialog::DontUseNativeDialog | QFileDialog::ShowDirsOnly); #else ); #endif // DO NOT MAKE RELATIVE CONVERSION HERE, IT WILL BE DONE WHEN OK IS CLICKED, // THE PROJECT DIRECTORY MAY NOT BE DETERMINED AT THIS POINT if(!path.isEmpty()) { lastDirPath = path; addResourceLocation(RES_LOC_DIR, path); QDirIterator it(path, QDir::AllDirs, QDirIterator::Subdirectories); while (it.hasNext()) { QString dir = it.next(); QFileInfo inf(dir); if(!dir.endsWith(".")) { addResourceLocation(RES_LOC_DIR, dir); } } } } //---------------------------------------------------------------------------------- void SettingsDialog::onAddArchive() { QString path; if(lastDirPath == "") path = QApplication::applicationDirPath(); else path = lastDirPath; path = QFileDialog::getOpenFileName(QApplication::activeWindow(), tr("Archive Files"), path, QString(tr("Zip Files (*.zip)")), 0 #if OGRE_PLATFORM == OGRE_PLATFORM_LINUX , QFileDialog::DontUseNativeDialog); #else ); #endif if(!path.isEmpty()) { addResourceLocation(RES_LOC_ZIP, path); } } //---------------------------------------------------------------------------------- void SettingsDialog::onRemoveEntry() { if(mResourceListBox->currentIndex().isValid()) { int index = mResourceListBox->currentIndex().row(); if(index >= 0) { mResourceFileTypes.erase(mResourceFileTypes.begin() + index); mResourceListBox->takeItem(index); } } } //---------------------------------------------------------------------------------- bool SettingsDialog::eventFilter ( QObject * watched, QEvent * e ) { if(watched == mResourceListBox) { if(e->type() == QEvent::ContextMenu) { QMenu *menu = new QMenu(this); menu->addAction(tr("Add Directory"), this, SLOT(onAddDirectory())); menu->addAction(tr("Add Directories Recursively"), this, SLOT(onAddDirectoryRecursive())); menu->addAction(tr("Add Archive"), this, SLOT(onAddArchive())); QAction *removeAction = menu->addAction(tr("Remove Entry"), this, SLOT(onRemoveEntry())); removeAction->setEnabled(mResourceListBox->currentIndex().row() >= 0); menu->exec(QCursor::pos()); delete menu; e->ignore(); return true; } else if(e->type() == QEvent::KeyRelease) { QKeyEvent *evt = static_cast<QKeyEvent*>(e); if(evt->key() == Qt::Key_Delete) { onRemoveEntry(); return true; } } } return false; } //---------------------------------------------------------------------------------- void SettingsDialog::onAccept() { if(mOptions->IsNewProject) { QString ProjectDir = mProjectDirTextBox->text(); QString ProjectName = mProjectNameTextBox->text(); QString SceneManagerName = mSceneMgrNameMenu->itemText(mSceneMgrNameMenu->currentIndex()); QString SceneManagerConfigFile = mConfigFileTextBox->text(); QString TerrainDir = mTerrainDirTextBox->text(); if(!IsValidName(ProjectDir, qApp->translate("SettingsDialog", "Project Directory"))) return; if(!IsValidName(ProjectName, qApp->translate("SettingsDialog", "Project Name"), "\\/")) return; if(!IsValidName(TerrainDir, qApp->translate("SettingsDialog", "Terrain Directory"))) return; Ogre::String sProjectDir = OgitorsUtils::QualifyPath(QString(ProjectDir + QString("/") + ProjectName).toStdString()); OgitorsSystem::getSingletonPtr()->MakeDirectory(sProjectDir); mOptions->CreatedIn = ""; mOptions->ProjectDir = sProjectDir; mOptions->ProjectName = ProjectName.toStdString(); mOptions->SceneManagerName = SceneManagerName.toStdString(); mOptions->SceneManagerConfigFile = SceneManagerConfigFile.toStdString(); mOptions->TerrainDirectory = TerrainDir.toStdString(); } mOptions->ResourceDirectories.clear(); Ogre::String pathTo = mOptions->ProjectDir; HashMap<Ogre::String, int> resDirMap; unsigned int i; unsigned int itemcount = mResourceListBox->count(); for(i = 0;i < itemcount;i++) { Ogre::String strTemp = mResourceListBox->item(i)->text().toStdString(); int stype = mResourceFileTypes[i]; if(strTemp.substr(0,1) != ".") strTemp = OgitorsUtils::GetRelativePath(pathTo,strTemp); Ogre::String val; if(stype == RES_LOC_DIR) { val = Ogre::String("FS:") + strTemp; if(resDirMap.find(val) == resDirMap.end()) { resDirMap[val] = 0; } } else if(stype == RES_LOC_ZIP) { val = Ogre::String("ZP:") + strTemp; if(resDirMap.find(val) == resDirMap.end()) { resDirMap[val] = 0; } } } HashMap<Ogre::String, int>::const_iterator rit = resDirMap.begin(); while(rit != resDirMap.end()) { mOptions->ResourceDirectories.push_back(rit->first); rit++; } mOptions->SelectionRectColour = mSelRectColourWidget->getColour(); mOptions->SelectionBBColour = mSelColourWidget->getColour(); mOptions->HighlightBBColour = mHighlightColourWidget->getColour(); mOptions->SelectHighlightBBColour = mSelectHighlightColourWidget->getColour(); mOptions->GridColour = mGridColourWidget->getColour(); mOptions->GridSpacing = mGridSpacingMenu->value(); mOptions->SnapAngle = mSnapAngleMenu->value(); mOptions->VolumeSelectionDepth = mSelectionDepthMenu->value(); accept(); } //---------------------------------------------------------------------------------- void SettingsDialog::dragEnterEvent(QDragEnterEvent * e) { // Only accept drags on the resources tab if(tabWidget->currentIndex() != 1) { e->ignore(); return; } // Get the filenames QStringList filenames = getFilenames(e->mimeData()); // Don't accept empty drags if(filenames.empty()) { e->ignore(); return; } // Accept when only directories and zip-files are being dragged for(int i = 0; i < filenames.size(); ++i) { QFileInfo file(filenames.at(i)); QString extension = file.suffix().toLower(); if(!file.isDir() && extension != "zip") { e->ignore(); return; } } e->accept(); } //---------------------------------------------------------------------------------- void SettingsDialog::dropEvent(QDropEvent * e) { // This should only occur when the resource tab is active assert(tabWidget->currentIndex() == 1); // Get the dropped filenames QStringList filenames = getFilenames(e->mimeData()); if(filenames.empty()) e->ignore(); // Handle the dropped items for(int i = 0; i < filenames.size(); ++i) { // All dropped items should be directories QFileInfo file(filenames.at(i)); QString extension = file.suffix().toLower(); if(file.isDir()) { addResourceLocation(RES_LOC_DIR, filenames.at(i)); } else if(extension == "zip") { addResourceLocation(RES_LOC_ZIP, filenames.at(i)); } } } //---------------------------------------------------------------------------------- QStringList SettingsDialog::getFilenames(const QMimeData * data) { QStringList result; QList<QUrl> urls = data->urls(); for(int i = 0; i < urls.size(); ++i) result.push_back(urls.at(i).toLocalFile()); return result; } //----------------------------------------------------------------------------------
34.516529
203
0.607446
lockie
e1b63c5b853e2abdc310d3432b9948c2dc2cf64a
472
cpp
C++
BinPlayer/BinPlayer/global.cpp
yangyuan/open-media-player
c812b6e1850951e59cc029a3f38d476cfeb03a33
[ "MIT" ]
null
null
null
BinPlayer/BinPlayer/global.cpp
yangyuan/open-media-player
c812b6e1850951e59cc029a3f38d476cfeb03a33
[ "MIT" ]
null
null
null
BinPlayer/BinPlayer/global.cpp
yangyuan/open-media-player
c812b6e1850951e59cc029a3f38d476cfeb03a33
[ "MIT" ]
null
null
null
#include "common.h" HMENU hMenuMain; HMENU hMenuTray; HMENU hMenuPlayListPop; ConfigReference BP_ConfigReference; CurrentFileInfomation BP_CurrentInfomation; MainWindowInfomation BP_MainWindowInfomation; ClassInfoTrackbar BP_tris, BP_trie; SkinConfiguration SkinConfig; publicInfo BP_PublicInfo; HICON hIcon_Tray; HICON hIcon_Tray_V; HWND hButton_Play; HWND hButton_Stop; HWND hButton_Back; HWND hButton_Next; HWND hWndPlayList; HICON hIcon_False; HICON hIcon_True;
18.153846
45
0.855932
yangyuan
e1b76bba41d281dc935f55001e5017b07942ef84
21,927
cpp
C++
src/mongo/db/ops/update.cpp
andremussche/minimongo
820d678f3561abb5660e27ff3204bd0e69dfe66c
[ "Apache-2.0" ]
1
2017-02-13T10:29:02.000Z
2017-02-13T10:29:02.000Z
src/mongo/db/ops/update.cpp
andremussche/minimongo
820d678f3561abb5660e27ff3204bd0e69dfe66c
[ "Apache-2.0" ]
null
null
null
src/mongo/db/ops/update.cpp
andremussche/minimongo
820d678f3561abb5660e27ff3204bd0e69dfe66c
[ "Apache-2.0" ]
null
null
null
//@file update.cpp /** * Copyright (C) 2008 10gen Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "mongo/pch.h" #include "mongo/db/ops/update.h" #include <cstring> // for memcpy #include "mongo/bson/mutable/damage_vector.h" #include "mongo/bson/mutable/document.h" #include "mongo/client/dbclientinterface.h" #include "mongo/db/clientcursor.h" #include "mongo/db/index_set.h" #include "mongo/db/namespace_details.h" #include "mongo/db/ops/update_driver.h" #include "mongo/db/pagefault.h" #include "mongo/db/pdfile.h" #include "mongo/db/query_optimizer.h" #include "mongo/db/query_runner.h" #include "mongo/db/queryutil.h" #include "mongo/db/storage/record.h" #include "mongo/db/repl/oplog.h" #include "mongo/platform/unordered_set.h" namespace mongo { namespace { // TODO: Make this a function on NamespaceString, or make it cleaner. inline void validateUpdate( const char* ns , const BSONObj& updateobj, const BSONObj& patternOrig ) { uassert( 10155 , "cannot update reserved $ collection", strchr(ns, '$') == 0 ); if ( strstr(ns, ".system.") ) { /* dm: it's very important that system.indexes is never updated as IndexDetails has pointers into it */ uassert( 10156, str::stream() << "cannot update system collection: " << ns << " q: " << patternOrig << " u: " << updateobj, legalClientSystemNS( ns , true ) ); } } /** * return a BSONObj with the _id field of the doc passed in. If no _id and multi, error. */ BSONObj makeOplogEntryQuery(const BSONObj doc, bool multi) { BSONObjBuilder idPattern; BSONElement id; // NOTE: If the matching object lacks an id, we'll log // with the original pattern. This isn't replay-safe. // It might make sense to suppress the log instead // if there's no id. if ( doc.getObjectID( id ) ) { idPattern.append( id ); return idPattern.obj(); } else { uassert( 10157, "multi-update requires all modified objects to have an _id" , ! multi ); return doc; } } } // namespace UpdateResult update(const UpdateRequest& request, OpDebug* opDebug) { // Should the modifiers validate their embedded docs via okForStorage // Only user updates should be checked. Any system or replication stuff should pass through. // Config db docs shouldn't get checked for valid field names since the shard key can have // a dot (".") in it. bool shouldValidate = !(request.isFromReplication() || request.getNamespaceString().isConfigDB()); // TODO: Consider some sort of unification between the UpdateDriver, ModifierInterface // and UpdateRequest structures. UpdateDriver::Options opts; opts.multi = request.isMulti(); opts.upsert = request.isUpsert(); opts.logOp = request.shouldUpdateOpLog(); opts.modOptions = ModifierInterface::Options( request.isFromReplication(), shouldValidate ); UpdateDriver driver( opts ); Status status = driver.parse( request.getUpdates() ); if ( !status.isOK() ) { uasserted( 16840, status.reason() ); } return update(request, opDebug, &driver); } UpdateResult update(const UpdateRequest& request, OpDebug* opDebug, UpdateDriver* driver) { const NamespaceString& nsString = request.getNamespaceString(); validateUpdate( nsString.ns().c_str(), request.getUpdates(), request.getQuery() ); NamespaceDetails* nsDetails = nsdetails( nsString.ns() ); NamespaceDetailsTransient* nsDetailsTransient = &NamespaceDetailsTransient::get( nsString.ns().c_str() ); // TODO: This seems a bit circuitious. opDebug->updateobj = request.getUpdates(); driver->refreshIndexKeys( nsDetailsTransient->indexKeys() ); shared_ptr<Cursor> cursor = getOptimizedCursor( nsString.ns(), request.getQuery(), BSONObj(), request.getQueryPlanSelectionPolicy() ); // If the update was marked with '$isolated' (a.k.a '$atomic'), we are not allowed to // yield while evaluating the update loop below. // // TODO: Old code checks this repeatedly within the update loop. Is that necessary? It seems // that once atomic should be always atomic. const bool isolated = cursor->ok() && cursor->matcher() && cursor->matcher()->docMatcher().atomic(); // The 'cursor' the optimizer gave us may contain query plans that generate duplicate // diskloc's. We set up here the mechanims that will prevent us from processing those // twice if we see them. We also set up a 'ClientCursor' so that we can support // yielding. // // TODO: Is it valid to call this on a non-ok cursor? const bool dedupHere = cursor->autoDedup(); // // We'll start assuming we have one or more documents for this update. (Othwerwise, // we'll fallback to upserting.) // // We record that this will not be an upsert, in case a mod doesn't want to be applied // when in strict update mode. driver->setContext( ModifierInterface::ExecInfo::UPDATE_CONTEXT ); // Let's fetch each of them and pipe them through the update expression, making sure to // keep track of the necessary stats. Recall that we'll be pulling documents out of // cursors and some of them do not deduplicate the entries they generate. We have // deduping logic in here, too -- for now. unordered_set<DiskLoc, DiskLoc::Hasher> seenLocs; int numMatched = 0; opDebug->nscanned = 0; Client& client = cc(); mutablebson::Document doc; // If we are going to be yielding, we will need a ClientCursor scoped to this loop. We // only loop as long as the underlying cursor is OK. for ( auto_ptr<ClientCursor> clientCursor; cursor->ok(); ) { // If we haven't constructed a ClientCursor, and if the client allows us to throw // page faults, and if we are referring to a location that is likely not in // physical memory, then throw a PageFaultException. The entire operation will be // restarted. if ( clientCursor.get() == NULL && client.allowedToThrowPageFaultException() && !cursor->currLoc().isNull() && !cursor->currLoc().rec()->likelyInPhysicalMemory() ) { // We should never throw a PFE if we have already updated items. dassert((numMatched == 0) || (numMatched == opDebug->nupdateNoops)); throw PageFaultException( cursor->currLoc().rec() ); } if ( !isolated && opDebug->nscanned != 0 ) { // We are permitted to yield. To do so we need a ClientCursor, so create one // now if we have not yet done so. if ( !clientCursor.get() ) clientCursor.reset( new ClientCursor( QueryOption_NoCursorTimeout, cursor, nsString.ns() ) ); // Ask the client cursor to yield. We get two bits of state back: whether or not // we yielded, and whether or not we correctly recovered from yielding. bool yielded = false; const bool recovered = clientCursor->yieldSometimes( ClientCursor::WillNeed, &yielded ); if ( !recovered ) { // If we failed to recover from the yield, then the ClientCursor is already // gone. Release it so we don't destroy it a second time. clientCursor.release(); break; } if ( !cursor->ok() ) { // If the cursor died while we were yielded, just get out of the update loop. break; } if ( yielded ) { // We yielded and recovered OK, and our cursor is still good. Details about // our namespace may have changed while we were yielded, so we re-acquire // them here. If we can't do so, escape the update loop. Otherwise, refresh // the driver so that it knows about what is currently indexed. nsDetails = nsdetails( nsString.ns() ); if ( !nsDetails ) break; nsDetailsTransient = &NamespaceDetailsTransient::get( nsString.ns().c_str() ); // TODO: This copies the index keys, but it may not need to do so. driver->refreshIndexKeys( nsDetailsTransient->indexKeys() ); } } // Let's fetch the next candidate object for this update. Record* record = cursor->_current(); DiskLoc loc = cursor->currLoc(); const BSONObj oldObj = loc.obj(); // We count how many documents we scanned even though we may skip those that are // deemed duplicated. The final 'numUpdated' and 'nscanned' numbers may differ for // that reason. opDebug->nscanned++; // Skips this document if it: // a) doesn't match the query portion of the update // b) was deemed duplicate by the underlying cursor machinery // // Now, if we are going to update the document, // c) we don't want to do so while the cursor is at it, as that may invalidate // the cursor. So, we advance to next document, before issuing the update. MatchDetails matchDetails; matchDetails.requestElemMatchKey(); if ( !cursor->currentMatches( &matchDetails ) ) { // a) cursor->advance(); continue; } else if ( cursor->getsetdup( loc ) && dedupHere ) { // b) cursor->advance(); continue; } else if (!driver->isDocReplacement() && request.isMulti()) { // c) cursor->advance(); if ( dedupHere ) { if ( seenLocs.count( loc ) ) { continue; } } // There are certain kind of cursors that hold multiple pointers to data // underneath. $or cursors is one example. In a $or cursor, it may be the case // that when we did the last advance(), we finished consuming documents from // one of $or child and started consuming the next one. In that case, it is // possible that the last document of the previous child is the same as the // first document of the next (see SERVER-5198 and jstests/orp.js). // // So we advance the cursor here until we see a new diskloc. // // Note that we won't be yielding, and we may not do so for a while if we find // a particularly duplicated sequence of loc's. That is highly unlikely, // though. (See SERVER-5725, if curious, but "stage" based $or will make that // ticket moot). while( cursor->ok() && loc == cursor->currLoc() ) { cursor->advance(); } } // For some (unfortunate) historical reasons, not all cursors would be valid after // a write simply because we advanced them to a document not affected by the write. // To protect in those cases, not only we engaged in the advance() logic above, but // we also tell the cursor we're about to write a document that we've just seen. // prepareToTouchEarlierIterate() requires calling later // recoverFromTouchingEarlierIterate(), so we make a note here to do so. bool touchPreviousDoc = request.isMulti() && cursor->ok(); if ( touchPreviousDoc ) { if ( clientCursor.get() ) clientCursor->setDoingDeletes( true ); cursor->prepareToTouchEarlierIterate(); } // Found a matching document numMatched++; // Ask the driver to apply the mods. It may be that the driver can apply those "in // place", that is, some values of the old document just get adjusted without any // change to the binary layout on the bson layer. It may be that a whole new // document is needed to accomodate the new bson layout of the resulting document. doc.reset( oldObj, mutablebson::Document::kInPlaceEnabled ); BSONObj logObj; // If there was a matched field, obtain it. string matchedField; if (matchDetails.hasElemMatchKey()) matchedField = matchDetails.elemMatchKey(); Status status = driver->update( matchedField, &doc, &logObj ); if ( !status.isOK() ) { uasserted( 16837, status.reason() ); } // If the driver applied the mods in place, we can ask the mutable for what // changed. We call those changes "damages". :) We use the damages to inform the // journal what was changed, and then apply them to the original document // ourselves. If, however, the driver applied the mods out of place, we ask it to // generate a new, modified document for us. In that case, the file manager will // take care of the journaling details for us. // // This code flow is admittedly odd. But, right now, journaling is baked in the file // manager. And if we aren't using the file manager, we have to do jounaling // ourselves. bool objectWasChanged = false; BSONObj newObj; const char* source = NULL; mutablebson::DamageVector damages; bool inPlace = doc.getInPlaceUpdates(&damages, &source); if ( inPlace && !damages.empty() && !driver->modsAffectIndices() ) { nsDetails->paddingFits(); // All updates were in place. Apply them via durability and writing pointer. mutablebson::DamageVector::const_iterator where = damages.begin(); const mutablebson::DamageVector::const_iterator end = damages.end(); for( ; where != end; ++where ) { const char* sourcePtr = source + where->sourceOffset; void* targetPtr = getDur().writingPtr( const_cast<char*>(oldObj.objdata()) + where->targetOffset, where->size); std::memcpy(targetPtr, sourcePtr, where->size); } newObj = oldObj; opDebug->fastmod = true; objectWasChanged = true; } else { // The updates were not in place. Apply them through the file manager. newObj = doc.getObject(); DiskLoc newLoc = theDataFileMgr.updateRecord(nsString.ns().c_str(), nsDetails, nsDetailsTransient, record, loc, newObj.objdata(), newObj.objsize(), *opDebug); // If we've moved this object to a new location, make sure we don't apply // that update again if our traversal picks the objecta again. // // We also take note that the diskloc if the updates are affecting indices. // Chances are that we're traversing one of them and they may be multi key and // therefore duplicate disklocs. if ( newLoc != loc || driver->modsAffectIndices() ) { seenLocs.insert( newLoc ); } objectWasChanged = true; } // Log Obj if ( request.shouldUpdateOpLog() ) { if ( driver->isDocReplacement() || !logObj.isEmpty() ) { BSONObj idQuery = driver->makeOplogEntryQuery(newObj, request.isMulti()); logOp("u", nsString.ns().c_str(), logObj , &idQuery, NULL, request.isFromMigration(), &newObj); } } // If it was noop since the document didn't change, record that. if (!objectWasChanged) opDebug->nupdateNoops++; if (!request.isMulti()) { break; } // If we used the cursor mechanism that prepares an earlier seen document for a // write we need to tell such mechanisms that the write is over. if ( touchPreviousDoc ) { cursor->recoverFromTouchingEarlierIterate(); } getDur().commitIfNeeded(); } // TODO: Can this be simplified? if ((numMatched > 0) || (numMatched == 0 && !request.isUpsert()) ) { opDebug->nupdated = numMatched; return UpdateResult( numMatched > 0 /* updated existing object(s) */, !driver->isDocReplacement() /* $mod or obj replacement */, numMatched /* # of docments update, even no-ops */, BSONObj() ); } // // We haven't found any existing document so an insert is done // (upsert is true). // opDebug->upsert = true; // Since this is an insert (no docs found and upsert:true), we will be logging it // as an insert in the oplog. We don't need the driver's help to build the // oplog record, then. We also set the context of the update driver to the INSERT_CONTEXT. // Some mods may only work in that context (e.g. $setOnInsert). driver->setLogOp( false ); driver->setContext( ModifierInterface::ExecInfo::INSERT_CONTEXT ); BSONObj baseObj; // Reset the document we will be writing to doc.reset( baseObj, mutablebson::Document::kInPlaceDisabled ); if ( request.getQuery().hasElement("_id") ) { uassertStatusOK(doc.root().appendElement(request.getQuery().getField("_id"))); } // If this is a $mod base update, we need to generate a document by examining the // query and the mods. Otherwise, we can use the object replacement sent by the user // update command that was parsed by the driver before. // In the following block we handle the query part, and then do the regular mods after. if ( *request.getUpdates().firstElementFieldName() == '$' ) { uassertStatusOK(UpdateDriver::createFromQuery(request.getQuery(), doc)); opDebug->fastmodinsert = true; } // Apply the update modifications and then log the update as an insert manually. Status status = driver->update( StringData(), &doc, NULL /* no oplog record */); if ( !status.isOK() ) { uasserted( 16836, status.reason() ); } BSONObj newObj = doc.getObject(); theDataFileMgr.insertWithObjMod( nsString.ns().c_str(), newObj, false, request.isGod() ); if ( request.shouldUpdateOpLog() ) { logOp( "i", nsString.ns().c_str(), newObj, NULL, NULL, request.isFromMigration(), &newObj ); } opDebug->nupdated = 1; return UpdateResult( false /* updated a non existing document */, !driver->isDocReplacement() /* $mod or obj replacement? */, 1 /* count of updated documents */, newObj /* object that was upserted */ ); } BSONObj applyUpdateOperators( const BSONObj& from, const BSONObj& operators ) { UpdateDriver::Options opts; opts.multi = false; opts.upsert = false; UpdateDriver driver( opts ); Status status = driver.parse( operators ); if ( !status.isOK() ) { uasserted( 16838, status.reason() ); } mutablebson::Document doc( from, mutablebson::Document::kInPlaceDisabled ); status = driver.update( StringData(), &doc, NULL /* not oplogging */ ); if ( !status.isOK() ) { uasserted( 16839, status.reason() ); } return doc.getObject(); } } // namespace mongo
45.968553
109
0.562548
andremussche
e1b79ddc2b315fd132302d01c69295e55d4a5fd9
2,806
cpp
C++
external/libcxx-test/std/algorithms/alg.sorting/alg.min.max/minmax_comp.pass.cpp
SenthilKumarGS/TizenRT
691639aa9667de5d966f040f0291a402727ab6ae
[ "Apache-2.0" ]
511
2017-03-29T09:14:09.000Z
2022-03-30T23:10:29.000Z
external/libcxx-test/std/algorithms/alg.sorting/alg.min.max/minmax_comp.pass.cpp
SenthilKumarGS/TizenRT
691639aa9667de5d966f040f0291a402727ab6ae
[ "Apache-2.0" ]
4,673
2017-03-29T10:43:43.000Z
2022-03-31T08:33:44.000Z
external/libcxx-test/std/algorithms/alg.sorting/alg.min.max/minmax_comp.pass.cpp
SenthilKumarGS/TizenRT
691639aa9667de5d966f040f0291a402727ab6ae
[ "Apache-2.0" ]
642
2017-03-30T20:45:33.000Z
2022-03-24T17:07:33.000Z
/**************************************************************************** * * Copyright 2018 Samsung Electronics 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. * ****************************************************************************/ //===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // <algorithm> // template<class T, StrictWeakOrder<auto, T> Compare> // requires !SameType<T, Compare> && CopyConstructible<Compare> // pair<const T&, const T&> // minmax(const T& a, const T& b, Compare comp); #include <algorithm> #include <functional> #include <cassert> #include "test_macros.h" #include "libcxx_tc_common.h" template <class T, class C> static int test(const T& a, const T& b, C c, const T& x, const T& y) { std::pair<const T&, const T&> p = std::minmax(a, b, c); TC_ASSERT_EXPR(&p.first == &x); TC_ASSERT_EXPR(&p.second == &y); return 0; } int tc_libcxx_algorithms_alg_min_max_minmax_comp(void) { { int x = 0; int y = 0; TC_ASSERT_FUNC((test(x, y, std::greater<int>(), x, y))); TC_ASSERT_FUNC((test(y, x, std::greater<int>(), y, x))); } { int x = 0; int y = 1; TC_ASSERT_FUNC((test(x, y, std::greater<int>(), y, x))); TC_ASSERT_FUNC((test(y, x, std::greater<int>(), y, x))); } { int x = 1; int y = 0; TC_ASSERT_FUNC((test(x, y, std::greater<int>(), x, y))); TC_ASSERT_FUNC((test(y, x, std::greater<int>(), x, y))); } #if TEST_STD_VER >= 14 { // Note that you can't take a reference to a local var, since // its address is not a compile-time constant. constexpr static int x = 1; constexpr static int y = 0; constexpr auto p1 = std::minmax(x, y, std::greater<>()); static_assert(p1.first == x, ""); static_assert(p1.second == y, ""); constexpr auto p2 = std::minmax(y, x, std::greater<>()); static_assert(p2.first == x, ""); static_assert(p2.second == y, ""); } #endif TC_SUCCESS_RESULT(); return 0; }
31.52809
80
0.565574
SenthilKumarGS
e1b99bf480d692c634f1f15a1117bc384215e0d5
904
cpp
C++
Samples/Tests/General/IslandTest.cpp
All8Up/JoltPhysics
751d13891f5bd8850863ad236eaa3c340e90de9a
[ "MIT" ]
1,311
2021-08-16T07:37:05.000Z
2022-03-31T21:13:39.000Z
Samples/Tests/General/IslandTest.cpp
All8Up/JoltPhysics
751d13891f5bd8850863ad236eaa3c340e90de9a
[ "MIT" ]
102
2021-08-28T14:41:32.000Z
2022-03-31T20:25:55.000Z
Samples/Tests/General/IslandTest.cpp
All8Up/JoltPhysics
751d13891f5bd8850863ad236eaa3c340e90de9a
[ "MIT" ]
65
2021-08-16T07:59:04.000Z
2022-03-28T06:18:49.000Z
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe // SPDX-License-Identifier: MIT #include <TestFramework.h> #include <Tests/General/IslandTest.h> #include <Physics/Collision/Shape/BoxShape.h> #include <Physics/Body/BodyCreationSettings.h> #include <Layers.h> JPH_IMPLEMENT_RTTI_VIRTUAL(IslandTest) { JPH_ADD_BASE_CLASS(IslandTest, Test) } void IslandTest::Initialize() { // Floor CreateFloor(); RefConst<Shape> box_shape = new BoxShape(Vec3(1.0f, 1.0f, 1.0f)); // Walls for (int i = 0; i < 10; ++i) for (int j = i / 2; j < 10 - (i + 1) / 2; ++j) for (int k = 0; k < 8; ++k) { Vec3 position(-10 + j * 2.0f + (i & 1? 1.0f : 0.0f), 1.0f + i * 2.0f, 8.0f * (k - 4)); Body &wall = *mBodyInterface->CreateBody(BodyCreationSettings(box_shape, position, Quat::sIdentity(), EMotionType::Dynamic, Layers::MOVING)); mBodyInterface->AddBody(wall.GetID(), EActivation::Activate); } }
28.25
145
0.661504
All8Up
e1b9c4231bd55e728417210379b51b13c59f9aed
465
cpp
C++
estl/test/defer_test.cpp
Eospp/Eospp
bc231908aaf34dfc2f790a259487253a4151be16
[ "MIT" ]
18
2022-01-21T18:19:37.000Z
2022-03-15T05:26:32.000Z
estl/test/defer_test.cpp
Eospp/Eospp
bc231908aaf34dfc2f790a259487253a4151be16
[ "MIT" ]
null
null
null
estl/test/defer_test.cpp
Eospp/Eospp
bc231908aaf34dfc2f790a259487253a4151be16
[ "MIT" ]
3
2022-01-22T14:24:04.000Z
2022-02-23T10:19:11.000Z
#include <gtest/gtest.h> #include <defer.hpp> TEST(DEFER_TEST,BAST_TEST) { bool flag = false; { defer_scope [&flag] { flag = true; }; } EXPECT_TRUE(flag); flag = false; { defer_scope [&flag] { flag = true; }; } EXPECT_TRUE(flag); flag = false; { defer_lamda { flag = true; }; } EXPECT_TRUE(flag); }
12.916667
27
0.423656
Eospp
e1ba17718854334c3af506a5bbdcc11c07b394d9
1,748
cpp
C++
dfs.cpp
rakshitraj/lol
c490916f74f1bdbd4d62a86c279c496417cf2e81
[ "MIT" ]
null
null
null
dfs.cpp
rakshitraj/lol
c490916f74f1bdbd4d62a86c279c496417cf2e81
[ "MIT" ]
null
null
null
dfs.cpp
rakshitraj/lol
c490916f74f1bdbd4d62a86c279c496417cf2e81
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <stack> using namespace std; std::vector<vector<int>> vec; std::vector<bool> visited; void dfs_r(int s){ int i; visited[s] = true; cout << "\nVisited: "<< s; for(i=0; i < vec[s].size(); ++i ){ if (visited[vec[s][i]] == false ) dfs_r(vec[s][i]); } } void dfs(const std::vector<vector<int>> vec, int s){ int node, i; std::stack<int> stk; stk.push(s); visited[s] = true; while(!stk.empty()){ node = stk.top(); stk.pop(); cout << "\nVisited: "<< node; for(int i=0; i < vec[node].size(); ++i) { if(visited[vec[node][i]] == false) { stk.push(vec[node][i]); visited[vec[node][i]] = true; } } } } void init_visited(){ // Initialize visited vector for (int i=0; i<visited.size(); i++) { visited[i] = false; } } int main() { int nodes, edges; int x[] = {1,1,2,2,3,4,4,5,5,6,6,8}; int y[] = {2,4,3,4,6,5,6,7,9,7,8,10}; // setting default for simplicity nodes = 10; edges = 12; vec.resize(nodes+1); visited.resize(nodes+1); // Creating adjacency matrix for(int i=0; i<edges; ++i) { vec[x[i]].push_back(y[i]); vec[y[i]].push_back(x[i]); } int start; cout << "Enter starting node, [1,10] : "; cin >> start; if( start>0 && start <11) { cout << "\nDFS -->\n"; init_visited(); cout << "Recursive dfs\n"; dfs_r(start); init_visited(); cout<< "\n\niterative dfs\n"; dfs(vec, start); } else cout << "\nNo such node.\n"; return 0; }
18.020619
52
0.473684
rakshitraj
e1bb870a8ef713c862ca4637063f875a9c7ed0f1
897
cc
C++
src/nn_acc/CombWrite.cc
leorezende93/gem5
8b6f40c90c58a589f230e27ae4a240ba792840a9
[ "BSD-3-Clause" ]
1
2019-06-26T14:32:39.000Z
2019-06-26T14:32:39.000Z
src/nn_acc/CombWrite.cc
leorezende93/gem5
8b6f40c90c58a589f230e27ae4a240ba792840a9
[ "BSD-3-Clause" ]
null
null
null
src/nn_acc/CombWrite.cc
leorezende93/gem5
8b6f40c90c58a589f230e27ae4a240ba792840a9
[ "BSD-3-Clause" ]
2
2019-06-26T14:33:42.000Z
2019-10-02T02:09:23.000Z
#include "nn_acc/CombWrite.hh" #include "debug/CombWrite.hh" CombWrite::CombWrite(CombWriteParams *params) : CombBase(params), n_of_iterations(params->data.size()), _writeEvent([this]{ writeData(); }, name() + ".event") { for (int i = 0; i < params->data.size(); i++) { _writeDataVector.push_back(params->data[i]); } } CombWrite::~CombWrite() { } void CombWrite::startup() { if(!_writeEvent.scheduled() && n_of_iterations > 0) { schedule(_writeEvent, curTick()); } } CombWrite* CombWriteParams::create() { return new CombWrite(this); } void CombWrite::writeData(){ n_of_iterations--; DPRINTF(CombWrite, "Master %s writing %d\n", _master[0].name(), _writeDataVector[n_of_iterations]); _master[0].newData(_writeDataVector[n_of_iterations]); if(n_of_iterations > 0) { schedule(_writeEvent, curTick() + _latency[0]); } }
23.605263
101
0.654404
leorezende93
e1bc42cf84deec6c3d93f159112bb8f54c603567
48,770
cc
C++
chrome/browser/browser_about_handler.cc
SlimKatLegacy/android_external_chromium
bc611cda58cc18d0dbaa8a7aee05eb3c0742e573
[ "BSD-3-Clause" ]
2
2017-02-20T14:25:04.000Z
2019-12-13T13:58:28.000Z
chrome/browser/browser_about_handler.cc
SlimKatLegacy/android_external_chromium
bc611cda58cc18d0dbaa8a7aee05eb3c0742e573
[ "BSD-3-Clause" ]
2
2017-07-25T09:37:22.000Z
2017-08-04T07:18:56.000Z
chrome/browser/browser_about_handler.cc
SlimKatLegacy/android_external_chromium
bc611cda58cc18d0dbaa8a7aee05eb3c0742e573
[ "BSD-3-Clause" ]
2
2020-01-12T00:55:53.000Z
2020-11-04T06:36:41.000Z
// Copyright (c) 2011 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/browser/browser_about_handler.h" #include <algorithm> #include <string> #include <vector> #include "base/callback.h" #include "base/command_line.h" #include "base/file_util.h" #include "base/i18n/number_formatting.h" #include "base/json/json_writer.h" #include "base/memory/singleton.h" #include "base/metrics/histogram.h" #include "base/metrics/stats_table.h" #include "base/path_service.h" #include "base/string_number_conversions.h" #include "base/string_piece.h" #include "base/string_util.h" #include "base/stringprintf.h" #include "base/threading/thread.h" #include "base/tracked_objects.h" #include "base/utf_string_conversions.h" #include "base/values.h" #include "chrome/browser/about_flags.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/defaults.h" #include "chrome/browser/memory_details.h" #include "chrome/browser/metrics/histogram_synchronizer.h" #include "chrome/browser/net/predictor_api.h" #include "chrome/browser/platform_util.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/ui/browser_dialogs.h" #include "chrome/browser/ui/webui/chrome_url_data_manager.h" #include "chrome/common/about_handler.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_version_info.h" #include "chrome/common/jstemplate_builder.h" #include "chrome/common/net/gaia/google_service_auth_error.h" #include "chrome/common/render_messages.h" #include "chrome/common/url_constants.h" #include "content/browser/browser_thread.h" #include "content/browser/gpu_process_host.h" #include "content/browser/renderer_host/render_process_host.h" #include "content/browser/renderer_host/render_view_host.h" #include "content/common/gpu_messages.h" #include "googleurl/src/gurl.h" #include "grit/browser_resources.h" #include "grit/chromium_strings.h" #include "grit/generated_resources.h" #include "grit/locale_settings.h" #include "net/base/escape.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/resource/resource_bundle.h" #include "webkit/glue/webkit_glue.h" #include "webkit/glue/plugins/plugin_list.h" #include "webkit/plugins/npapi/webplugininfo.h" #ifdef CHROME_V8 #include "v8/include/v8.h" #endif #if defined(OS_WIN) #include "chrome/browser/enumerate_modules_model_win.h" #elif defined(OS_CHROMEOS) #include "chrome/browser/chromeos/cros/cros_library.h" #include "chrome/browser/chromeos/cros/network_library.h" #include "chrome/browser/chromeos/cros/syslogs_library.h" #include "chrome/browser/chromeos/login/wizard_controller.h" #include "chrome/browser/chromeos/version_loader.h" #include "content/browser/zygote_host_linux.h" #elif defined(OS_LINUX) #include "content/browser/zygote_host_linux.h" #endif #if defined(USE_TCMALLOC) #include "third_party/tcmalloc/chromium/src/google/malloc_extension.h" #endif using base::Time; using base::TimeDelta; #if defined(USE_TCMALLOC) // static AboutTcmallocOutputs* AboutTcmallocOutputs::GetInstance() { return Singleton<AboutTcmallocOutputs>::get(); } AboutTcmallocOutputs::AboutTcmallocOutputs() {} AboutTcmallocOutputs::~AboutTcmallocOutputs() {} // Glue between the callback task and the method in the singleton. void AboutTcmallocRendererCallback(base::ProcessId pid, const std::string& output) { AboutTcmallocOutputs::GetInstance()->RendererCallback(pid, output); } #endif namespace { // The (alphabetized) paths used for the about pages. // Note: Keep these in sync with url_constants.h const char kAppCacheInternalsPath[] = "appcache-internals"; const char kBlobInternalsPath[] = "blob-internals"; const char kCreditsPath[] = "credits"; const char kCachePath[] = "view-http-cache"; #if defined(OS_WIN) const char kConflictsPath[] = "conflicts"; #endif const char kDnsPath[] = "dns"; const char kFlagsPath[] = "flags"; const char kGpuPath[] = "gpu-internals"; const char kHistogramsPath[] = "histograms"; const char kMemoryRedirectPath[] = "memory-redirect"; const char kMemoryPath[] = "memory"; const char kStatsPath[] = "stats"; const char kTasksPath[] = "tasks"; const char kTcmallocPath[] = "tcmalloc"; const char kTermsPath[] = "terms"; const char kVersionPath[] = "version"; const char kAboutPath[] = "about"; // Not about:* pages, but included to make about:about look nicer const char kNetInternalsPath[] = "net-internals"; const char kPluginsPath[] = "plugins"; const char kSyncInternalsPath[] = "sync-internals"; #if defined(OS_LINUX) const char kLinuxProxyConfigPath[] = "linux-proxy-config"; const char kSandboxPath[] = "sandbox"; #endif #if defined(OS_CHROMEOS) const char kNetworkPath[] = "network"; const char kOSCreditsPath[] = "os-credits"; const char kEULAPathFormat[] = "/usr/share/chromeos-assets/eula/%s/eula.html"; #endif // Add path here to be included in about:about const char *kAllAboutPaths[] = { kAboutPath, kAppCacheInternalsPath, kBlobInternalsPath, kCachePath, kCreditsPath, #if defined(OS_WIN) kConflictsPath, #endif kDnsPath, kFlagsPath, kGpuPath, kHistogramsPath, kMemoryPath, kNetInternalsPath, kPluginsPath, kStatsPath, kSyncInternalsPath, #ifdef TRACK_ALL_TASK_OBJECTS kTasksPath, #endif // TRACK_ALL_TASK_OBJECTS kTcmallocPath, kTermsPath, kVersionPath, #if defined(OS_LINUX) kSandboxPath, #endif #if defined(OS_CHROMEOS) kNetworkPath, kOSCreditsPath, #endif }; // When you type about:memory, it actually loads an intermediate URL that // redirects you to the final page. This avoids the problem where typing // "about:memory" on the new tab page or any other page where a process // transition would occur to the about URL will cause some confusion. // // The problem is that during the processing of the memory page, there are two // processes active, the original and the destination one. This can create the // impression that we're using more resources than we actually are. This // redirect solves the problem by eliminating the process transition during the // time that about memory is being computed. std::string GetAboutMemoryRedirectResponse() { return "<meta http-equiv=\"refresh\" " "content=\"0;chrome://about/memory\">"; } class AboutSource : public ChromeURLDataManager::DataSource { public: // Creates our datasource. AboutSource(); // Called when the network layer has requested a resource underneath // the path we registered. virtual void StartDataRequest(const std::string& path, bool is_incognito, int request_id); virtual std::string GetMimeType(const std::string&) const { return "text/html"; } // Send the response data. void FinishDataRequest(const std::string& html, int request_id); private: virtual ~AboutSource(); DISALLOW_COPY_AND_ASSIGN(AboutSource); }; // Handling about:memory is complicated enough to encapsulate its related // methods into a single class. The user should create it (on the heap) and call // its |StartFetch()| method. class AboutMemoryHandler : public MemoryDetails { public: AboutMemoryHandler(AboutSource* source, int request_id) : source_(source), request_id_(request_id) {} virtual void OnDetailsAvailable(); private: ~AboutMemoryHandler() {} void BindProcessMetrics(DictionaryValue* data, ProcessMemoryInformation* info); void AppendProcess(ListValue* child_data, ProcessMemoryInformation* info); scoped_refptr<AboutSource> source_; int request_id_; DISALLOW_COPY_AND_ASSIGN(AboutMemoryHandler); }; #if defined(OS_CHROMEOS) // ChromeOSAboutVersionHandler is responsible for loading the Chrome OS // version. // ChromeOSAboutVersionHandler handles deleting itself once the version has // been obtained and AboutSource notified. class ChromeOSAboutVersionHandler { public: ChromeOSAboutVersionHandler(AboutSource* source, int request_id); // Callback from chromeos::VersionLoader giving the version. void OnVersion(chromeos::VersionLoader::Handle handle, std::string version); private: // Where the results are fed to. scoped_refptr<AboutSource> source_; // ID identifying the request. int request_id_; // Handles asynchronously loading the version. chromeos::VersionLoader loader_; // Used to request the version. CancelableRequestConsumer consumer_; DISALLOW_COPY_AND_ASSIGN(ChromeOSAboutVersionHandler); }; class ChromeOSTermsHandler : public base::RefCountedThreadSafe<ChromeOSTermsHandler> { public: static void Start(AboutSource* source, int request_id) { scoped_refptr<ChromeOSTermsHandler> handler( new ChromeOSTermsHandler(source, request_id)); handler->StartOnUIThread(); } private: ChromeOSTermsHandler(AboutSource* source, int request_id) : source_(source), request_id_(request_id), locale_(WizardController::GetInitialLocale()) { } void StartOnUIThread() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); BrowserThread::PostTask( BrowserThread::FILE, FROM_HERE, NewRunnableMethod(this, &ChromeOSTermsHandler::LoadFileOnFileThread)); } void LoadFileOnFileThread() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); std::string path = StringPrintf(kEULAPathFormat, locale_.c_str()); if (!file_util::ReadFileToString(FilePath(path), &contents_)) { // No EULA for given language - try en-US as default. path = StringPrintf(kEULAPathFormat, "en-US"); if (!file_util::ReadFileToString(FilePath(path), &contents_)) { // File with EULA not found, ResponseOnUIThread will load EULA from // resources if contents_ is empty. contents_.clear(); } } BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, NewRunnableMethod(this, &ChromeOSTermsHandler::ResponseOnUIThread)); } void ResponseOnUIThread() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); if (contents_.empty()) { contents_ = ResourceBundle::GetSharedInstance().GetRawDataResource( IDR_TERMS_HTML).as_string(); } source_->FinishDataRequest(contents_, request_id_); } // Where the results are fed to. scoped_refptr<AboutSource> source_; // ID identifying the request. int request_id_; std::string locale_; std::string contents_; DISALLOW_COPY_AND_ASSIGN(ChromeOSTermsHandler); }; #endif // Individual about handlers --------------------------------------------------- std::string AboutAbout() { std::string html("<html><head><title>About Pages</title></head>\n" "<body><h2>List of About pages</h2>\n<ul>"); std::vector<std::string> paths(AboutPaths()); for (std::vector<std::string>::const_iterator i = paths.begin(); i != paths.end(); ++i) { html += "<li><a href='chrome://"; if ((*i != kAppCacheInternalsPath) && (*i != kBlobInternalsPath) && (*i != kCachePath) && #if defined(OS_WIN) (*i != kConflictsPath) && #endif (*i != kFlagsPath) && (*i != kGpuPath) && (*i != kNetInternalsPath) && (*i != kPluginsPath)) { html += "about/"; } html += *i + "/'>about:" + *i + "</a></li>\n"; } const char *debug[] = { "crash", "kill", "hang", "shorthang", "gpucrash", "gpuhang" }; html += "</ul>\n<h2>For Debug</h2>\n" "<p>The following pages are for debugging purposes only. Because they " "crash or hang the renderer, they're not linked directly; you can type " "them into the address bar if you need them.</p>\n<ul>"; for (size_t i = 0; i < arraysize(debug); i++) html += "<li>about:" + std::string(debug[i]) + "</li>\n"; html += "</ul>\n</body></html>"; return html; } #if defined(OS_CHROMEOS) // Html output helper functions // TODO(stevenjb): L10N this. // Helper function to wrap Html with <th> tag. static std::string WrapWithTH(std::string text) { return "<th>" + text + "</th>"; } // Helper function to wrap Html with <td> tag. static std::string WrapWithTD(std::string text) { return "<td>" + text + "</td>"; } // Helper function to create an Html table header for a Network. static std::string ToHtmlTableHeader(const chromeos::Network* network) { std::string str = WrapWithTH("Name") + WrapWithTH("Active") + WrapWithTH("State"); if (network->type() == chromeos::TYPE_WIFI || network->type() == chromeos::TYPE_CELLULAR) { str += WrapWithTH("Auto-Connect"); str += WrapWithTH("Strength"); } if (network->type() == chromeos::TYPE_WIFI) { str += WrapWithTH("Encryption"); str += WrapWithTH("Passphrase"); str += WrapWithTH("Identity"); str += WrapWithTH("Certificate"); } if (network->type() == chromeos::TYPE_CELLULAR) { str += WrapWithTH("Technology"); str += WrapWithTH("Connectivity"); str += WrapWithTH("Activation"); str += WrapWithTH("Roaming"); } if (network->type() == chromeos::TYPE_VPN) { str += WrapWithTH("Host"); str += WrapWithTH("Provider Type"); str += WrapWithTH("PSK Passphrase"); str += WrapWithTH("Username"); str += WrapWithTH("User Passphrase"); } str += WrapWithTH("Error"); str += WrapWithTH("IP Address"); return str; } // Helper function to create an Html table row for a Network. static std::string ToHtmlTableRow(const chromeos::Network* network) { std::string str = WrapWithTD(network->name()) + WrapWithTD(base::IntToString(network->is_active())) + WrapWithTD(network->GetStateString()); if (network->type() == chromeos::TYPE_WIFI || network->type() == chromeos::TYPE_CELLULAR) { const chromeos::WirelessNetwork* wireless = static_cast<const chromeos::WirelessNetwork*>(network); str += WrapWithTD(base::IntToString(wireless->auto_connect())); str += WrapWithTD(base::IntToString(wireless->strength())); } if (network->type() == chromeos::TYPE_WIFI) { const chromeos::WifiNetwork* wifi = static_cast<const chromeos::WifiNetwork*>(network); str += WrapWithTD(wifi->GetEncryptionString()); str += WrapWithTD(std::string(wifi->passphrase().length(), '*')); str += WrapWithTD(wifi->identity()); str += WrapWithTD(wifi->cert_path()); } if (network->type() == chromeos::TYPE_CELLULAR) { const chromeos::CellularNetwork* cell = static_cast<const chromeos::CellularNetwork*>(network); str += WrapWithTH(cell->GetNetworkTechnologyString()); str += WrapWithTH(cell->GetConnectivityStateString()); str += WrapWithTH(cell->GetActivationStateString()); str += WrapWithTH(cell->GetRoamingStateString()); } if (network->type() == chromeos::TYPE_VPN) { const chromeos::VirtualNetwork* vpn = static_cast<const chromeos::VirtualNetwork*>(network); str += WrapWithTH(vpn->server_hostname()); str += WrapWithTH(vpn->GetProviderTypeString()); str += WrapWithTD(std::string(vpn->psk_passphrase().length(), '*')); str += WrapWithTH(vpn->username()); str += WrapWithTD(std::string(vpn->user_passphrase().length(), '*')); } str += WrapWithTD(network->failed() ? network->GetErrorString() : ""); str += WrapWithTD(network->ip_address()); return str; } std::string GetNetworkHtmlInfo(int refresh) { chromeos::NetworkLibrary* cros = chromeos::CrosLibrary::Get()->GetNetworkLibrary(); std::string output; output.append("<html><head><title>About Network</title>"); if (refresh > 0) output.append("<meta http-equiv=\"refresh\" content=\"" + base::IntToString(refresh) + "\"/>"); output.append("</head><body>"); if (refresh > 0) { output.append("(Auto-refreshing page every " + base::IntToString(refresh) + "s)"); } else { output.append("(To auto-refresh this page: about:network/&lt;secs&gt;)"); } if (cros->ethernet_enabled()) { output.append("<h3>Ethernet:</h3><table border=1>"); const chromeos::EthernetNetwork* ethernet = cros->ethernet_network(); if (ethernet) { output.append("<tr>" + ToHtmlTableHeader(ethernet) + "</tr>"); output.append("<tr>" + ToHtmlTableRow(ethernet) + "</tr>"); } } if (cros->wifi_enabled()) { output.append("</table><h3>Wifi Networks:</h3><table border=1>"); const chromeos::WifiNetworkVector& wifi_networks = cros->wifi_networks(); for (size_t i = 0; i < wifi_networks.size(); ++i) { if (i == 0) output.append("<tr>" + ToHtmlTableHeader(wifi_networks[i]) + "</tr>"); output.append("<tr>" + ToHtmlTableRow(wifi_networks[i]) + "</tr>"); } } if (cros->cellular_enabled()) { output.append("</table><h3>Cellular Networks:</h3><table border=1>"); const chromeos::CellularNetworkVector& cellular_networks = cros->cellular_networks(); for (size_t i = 0; i < cellular_networks.size(); ++i) { if (i == 0) output.append("<tr>" + ToHtmlTableHeader(cellular_networks[i]) + "</tr>"); output.append("<tr>" + ToHtmlTableRow(cellular_networks[i]) + "</tr>"); } } { output.append("</table><h3>Virtual Networks:</h3><table border=1>"); const chromeos::VirtualNetworkVector& virtual_networks = cros->virtual_networks(); for (size_t i = 0; i < virtual_networks.size(); ++i) { if (i == 0) output.append("<tr>" + ToHtmlTableHeader(virtual_networks[i]) + "</tr>"); output.append("<tr>" + ToHtmlTableRow(virtual_networks[i]) + "</tr>"); } } { output.append( "</table><h3>Remembered Wi-Fi Networks:</h3><table border=1>"); const chromeos::WifiNetworkVector& remembered_wifi_networks = cros->remembered_wifi_networks(); for (size_t i = 0; i < remembered_wifi_networks.size(); ++i) { if (i == 0) output.append("<tr>" + ToHtmlTableHeader(remembered_wifi_networks[i]) + "</tr>"); output.append("<tr>" + ToHtmlTableRow(remembered_wifi_networks[i]) + "</tr>"); } } output.append("</table></body></html>"); return output; } std::string AboutNetwork(const std::string& query) { int refresh; base::StringToInt(query, &refresh); return GetNetworkHtmlInfo(refresh); } #endif // AboutDnsHandler bounces the request back to the IO thread to collect // the DNS information. class AboutDnsHandler : public base::RefCountedThreadSafe<AboutDnsHandler> { public: static void Start(AboutSource* source, int request_id) { scoped_refptr<AboutDnsHandler> handler( new AboutDnsHandler(source, request_id)); handler->StartOnUIThread(); } private: AboutDnsHandler(AboutSource* source, int request_id) : source_(source), request_id_(request_id) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); } // Calls FinishOnUIThread() on completion. void StartOnUIThread() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, NewRunnableMethod(this, &AboutDnsHandler::StartOnIOThread)); } void StartOnIOThread() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); std::string data; chrome_browser_net::PredictorGetHtmlInfo(&data); BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, NewRunnableMethod(this, &AboutDnsHandler::FinishOnUIThread, data)); } void FinishOnUIThread(const std::string& data) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); source_->FinishDataRequest(data, request_id_); } // Where the results are fed to. scoped_refptr<AboutSource> source_; // ID identifying the request. int request_id_; DISALLOW_COPY_AND_ASSIGN(AboutDnsHandler); }; #if defined(USE_TCMALLOC) std::string AboutTcmalloc(const std::string& query) { std::string data; AboutTcmallocOutputsType* outputs = AboutTcmallocOutputs::GetInstance()->outputs(); // Display any stats for which we sent off requests the last time. data.append("<html><head><title>About tcmalloc</title></head><body>\n"); data.append("<p>Stats as of last page load;"); data.append("reload to get stats as of this page load.</p>\n"); data.append("<table width=\"100%\">\n"); for (AboutTcmallocOutputsType::const_iterator oit = outputs->begin(); oit != outputs->end(); oit++) { data.append("<tr><td bgcolor=\"yellow\">"); data.append(oit->first); data.append("</td></tr>\n"); data.append("<tr><td><pre>\n"); data.append(oit->second); data.append("</pre></td></tr>\n"); } data.append("</table>\n"); data.append("</body></html>\n"); // Reset our collector singleton. outputs->clear(); // Populate the collector with stats from the local browser process // and send off requests to all the renderer processes. char buffer[1024 * 32]; MallocExtension::instance()->GetStats(buffer, sizeof(buffer)); std::string browser("Browser"); AboutTcmallocOutputs::GetInstance()->SetOutput(browser, buffer); RenderProcessHost::iterator it(RenderProcessHost::AllHostsIterator()); while (!it.IsAtEnd()) { it.GetCurrentValue()->Send(new ViewMsg_GetRendererTcmalloc); it.Advance(); } return data; } #endif std::string AboutHistograms(const std::string& query) { TimeDelta wait_time = TimeDelta::FromMilliseconds(10000); HistogramSynchronizer* current_synchronizer = HistogramSynchronizer::CurrentSynchronizer(); DCHECK(current_synchronizer != NULL); current_synchronizer->FetchRendererHistogramsSynchronously(wait_time); std::string data; base::StatisticsRecorder::WriteHTMLGraph(query, &data); return data; } void AboutMemory(AboutSource* source, int request_id) { // The AboutMemoryHandler cleans itself up, but |StartFetch()| will want the // refcount to be greater than 0. scoped_refptr<AboutMemoryHandler> handler(new AboutMemoryHandler(source, request_id)); handler->StartFetch(); } #ifdef TRACK_ALL_TASK_OBJECTS static std::string AboutObjects(const std::string& query) { std::string data; tracked_objects::ThreadData::WriteHTML(query, &data); return data; } #endif // TRACK_ALL_TASK_OBJECTS // Handler for filling in the "about:stats" page, as called by the browser's // About handler processing. // |query| is roughly the query string of the about:stats URL. // Returns a string containing the HTML to render for the about:stats page. // Conditional Output: // if |query| is "json", returns a JSON format of all counters. // if |query| is "raw", returns plain text of counter deltas. // otherwise, returns HTML with pretty JS/HTML to display the data. std::string AboutStats(const std::string& query) { // We keep the DictionaryValue tree live so that we can do delta // stats computations across runs. static DictionaryValue root; static base::TimeTicks last_sample_time = base::TimeTicks::Now(); base::TimeTicks now = base::TimeTicks::Now(); base::TimeDelta time_since_last_sample = now - last_sample_time; last_sample_time = now; base::StatsTable* table = base::StatsTable::current(); if (!table) return std::string(); // We maintain two lists - one for counters and one for timers. // Timers actually get stored on both lists. ListValue* counters; if (!root.GetList("counters", &counters)) { counters = new ListValue(); root.Set("counters", counters); } ListValue* timers; if (!root.GetList("timers", &timers)) { timers = new ListValue(); root.Set("timers", timers); } // NOTE: Counters start at index 1. for (int index = 1; index <= table->GetMaxCounters(); index++) { // Get the counter's full name std::string full_name = table->GetRowName(index); if (full_name.length() == 0) break; DCHECK_EQ(':', full_name[1]); char counter_type = full_name[0]; std::string name = full_name.substr(2); // JSON doesn't allow '.' in names. size_t pos; while ((pos = name.find(".")) != std::string::npos) name.replace(pos, 1, ":"); // Try to see if this name already exists. DictionaryValue* counter = NULL; for (size_t scan_index = 0; scan_index < counters->GetSize(); scan_index++) { DictionaryValue* dictionary; if (counters->GetDictionary(scan_index, &dictionary)) { std::string scan_name; if (dictionary->GetString("name", &scan_name) && scan_name == name) { counter = dictionary; } } else { NOTREACHED(); // Should always be there } } if (counter == NULL) { counter = new DictionaryValue(); counter->SetString("name", name); counters->Append(counter); } switch (counter_type) { case 'c': { int new_value = table->GetRowValue(index); int prior_value = 0; int delta = 0; if (counter->GetInteger("value", &prior_value)) { delta = new_value - prior_value; } counter->SetInteger("value", new_value); counter->SetInteger("delta", delta); } break; case 'm': { // TODO(mbelshe): implement me. } break; case 't': { int time = table->GetRowValue(index); counter->SetInteger("time", time); // Store this on the timers list as well. timers->Append(counter); } break; default: NOTREACHED(); } } std::string data; if (query == "json") { base::JSONWriter::WriteWithOptionalEscape(&root, true, false, &data); } else if (query == "raw") { // Dump the raw counters which have changed in text format. data = "<pre>"; data.append(StringPrintf("Counter changes in the last %ldms\n", static_cast<long int>(time_since_last_sample.InMilliseconds()))); for (size_t i = 0; i < counters->GetSize(); ++i) { Value* entry = NULL; bool rv = counters->Get(i, &entry); if (!rv) continue; // None of these should fail. DictionaryValue* counter = static_cast<DictionaryValue*>(entry); int delta; rv = counter->GetInteger("delta", &delta); if (!rv) continue; if (delta > 0) { std::string name; rv = counter->GetString("name", &name); if (!rv) continue; int value; rv = counter->GetInteger("value", &value); if (!rv) continue; data.append(name); data.append(":"); data.append(base::IntToString(delta)); data.append("\n"); } } data.append("</pre>"); } else { // Get about_stats.html and process a pretty page. static const base::StringPiece stats_html( ResourceBundle::GetSharedInstance().GetRawDataResource( IDR_ABOUT_STATS_HTML)); // Create jstemplate and return. data = jstemplate_builder::GetTemplateHtml( stats_html, &root, "t" /* template root node id */); // Clear the timer list since we stored the data in the timers list as well. for (int index = static_cast<int>(timers->GetSize())-1; index >= 0; index--) { Value* value; timers->Remove(index, &value); // We don't care about the value pointer; it's still tracked // on the counters list. } } return data; } #if defined(OS_LINUX) std::string AboutLinuxProxyConfig() { std::string data; data.append("<!DOCTYPE HTML>\n"); data.append("<html><head><meta charset=\"utf-8\"><title>"); data.append(l10n_util::GetStringUTF8(IDS_ABOUT_LINUX_PROXY_CONFIG_TITLE)); data.append("</title>"); data.append("<style>body { max-width: 70ex; padding: 2ex 5ex; }</style>"); data.append("</head><body>\n"); FilePath binary = CommandLine::ForCurrentProcess()->GetProgram(); data.append(l10n_util::GetStringFUTF8( IDS_ABOUT_LINUX_PROXY_CONFIG_BODY, l10n_util::GetStringUTF16(IDS_PRODUCT_NAME), ASCIIToUTF16(binary.BaseName().value()))); data.append("</body></html>\n"); return data; } void AboutSandboxRow(std::string* data, const std::string& prefix, int name_id, bool good) { data->append("<tr><td>"); data->append(prefix); data->append(l10n_util::GetStringUTF8(name_id)); if (good) { data->append("</td><td style=\"color: green;\">"); data->append( l10n_util::GetStringUTF8(IDS_CONFIRM_MESSAGEBOX_YES_BUTTON_LABEL)); } else { data->append("</td><td style=\"color: red;\">"); data->append( l10n_util::GetStringUTF8(IDS_CONFIRM_MESSAGEBOX_NO_BUTTON_LABEL)); } data->append("</td></tr>"); } std::string AboutSandbox() { std::string data; data.append("<!DOCTYPE HTML>\n"); data.append("<html><head><meta charset=\"utf-8\"><title>"); data.append(l10n_util::GetStringUTF8(IDS_ABOUT_SANDBOX_TITLE)); data.append("</title>"); data.append("</head><body>\n"); data.append("<h1>"); data.append(l10n_util::GetStringUTF8(IDS_ABOUT_SANDBOX_TITLE)); data.append("</h1>"); const int status = ZygoteHost::GetInstance()->sandbox_status(); data.append("<table>"); AboutSandboxRow(&data, "", IDS_ABOUT_SANDBOX_SUID_SANDBOX, status & ZygoteHost::kSandboxSUID); if (status & ZygoteHost::kSandboxPIDNS) { AboutSandboxRow(&data, "&nbsp;&nbsp;", IDS_ABOUT_SANDBOX_PID_NAMESPACES, status & ZygoteHost::kSandboxPIDNS); AboutSandboxRow(&data, "&nbsp;&nbsp;", IDS_ABOUT_SANDBOX_NET_NAMESPACES, status & ZygoteHost::kSandboxNetNS); } AboutSandboxRow(&data, "", IDS_ABOUT_SANDBOX_SECCOMP_SANDBOX, status & ZygoteHost::kSandboxSeccomp); data.append("</table>"); bool good = ((status & ZygoteHost::kSandboxSUID) && (status & ZygoteHost::kSandboxPIDNS)) || (status & ZygoteHost::kSandboxSeccomp); if (good) { data.append("<p style=\"color: green\">"); data.append(l10n_util::GetStringUTF8(IDS_ABOUT_SANDBOX_OK)); } else { data.append("<p style=\"color: red\">"); data.append(l10n_util::GetStringUTF8(IDS_ABOUT_SANDBOX_BAD)); } data.append("</p>"); data.append("</body></html>\n"); return data; } #endif std::string AboutVersion(DictionaryValue* localized_strings) { localized_strings->SetString("title", l10n_util::GetStringUTF16(IDS_ABOUT_VERSION_TITLE)); chrome::VersionInfo version_info; std::string webkit_version = webkit_glue::GetWebKitVersion(); #ifdef CHROME_V8 std::string js_version(v8::V8::GetVersion()); std::string js_engine = "V8"; #else std::string js_version = webkit_version; std::string js_engine = "JavaScriptCore"; #endif localized_strings->SetString("name", l10n_util::GetStringUTF16(IDS_PRODUCT_NAME)); localized_strings->SetString("version", version_info.Version()); // Bug 79458: Need to evaluate the use of getting the version string on // this thread. base::ThreadRestrictions::ScopedAllowIO allow_io; localized_strings->SetString("version_modifier", platform_util::GetVersionStringModifier()); localized_strings->SetString("js_engine", js_engine); localized_strings->SetString("js_version", js_version); // Obtain the version of the first enabled Flash plugin. std::vector<webkit::npapi::WebPluginInfo> info_array; webkit::npapi::PluginList::Singleton()->GetPluginInfoArray( GURL(), "application/x-shockwave-flash", false, &info_array, NULL); string16 flash_version = l10n_util::GetStringUTF16(IDS_PLUGINS_DISABLED_PLUGIN); for (size_t i = 0; i < info_array.size(); ++i) { if (webkit::npapi::IsPluginEnabled(info_array[i])) { flash_version = info_array[i].version; break; } } localized_strings->SetString("flash_plugin", "Flash"); localized_strings->SetString("flash_version", flash_version); localized_strings->SetString("webkit_version", webkit_version); localized_strings->SetString("company", l10n_util::GetStringUTF16(IDS_ABOUT_VERSION_COMPANY_NAME)); localized_strings->SetString("copyright", l10n_util::GetStringUTF16(IDS_ABOUT_VERSION_COPYRIGHT)); localized_strings->SetString("cl", version_info.LastChange()); localized_strings->SetString("official", l10n_util::GetStringUTF16( version_info.IsOfficialBuild() ? IDS_ABOUT_VERSION_OFFICIAL : IDS_ABOUT_VERSION_UNOFFICIAL)); localized_strings->SetString("user_agent_name", l10n_util::GetStringUTF16(IDS_ABOUT_VERSION_USER_AGENT)); localized_strings->SetString("useragent", webkit_glue::GetUserAgent(GURL())); localized_strings->SetString("command_line_name", l10n_util::GetStringUTF16(IDS_ABOUT_VERSION_COMMAND_LINE)); #if defined(OS_WIN) localized_strings->SetString("command_line", WideToUTF16(CommandLine::ForCurrentProcess()->command_line_string())); #elif defined(OS_POSIX) std::string command_line = ""; typedef std::vector<std::string> ArgvList; const ArgvList& argv = CommandLine::ForCurrentProcess()->argv(); for (ArgvList::const_iterator iter = argv.begin(); iter != argv.end(); iter++) command_line += " " + *iter; // TODO(viettrungluu): |command_line| could really have any encoding, whereas // below we assumes it's UTF-8. localized_strings->SetString("command_line", command_line); #endif base::StringPiece version_html( ResourceBundle::GetSharedInstance().GetRawDataResource( IDR_ABOUT_VERSION_HTML)); return jstemplate_builder::GetTemplatesHtml( version_html, localized_strings, "t" /* template root node id */); } std::string VersionNumberToString(uint32 value) { int hi = (value >> 8) & 0xff; int low = value & 0xff; return base::IntToString(hi) + "." + base::IntToString(low); } // AboutSource ----------------------------------------------------------------- AboutSource::AboutSource() : DataSource(chrome::kAboutScheme, MessageLoop::current()) { } AboutSource::~AboutSource() { } void AboutSource::StartDataRequest(const std::string& path_raw, bool is_incognito, int request_id) { std::string path = path_raw; std::string info; if (path.find("/") != std::string::npos) { size_t pos = path.find("/"); info = path.substr(pos + 1, path.length() - (pos + 1)); path = path.substr(0, pos); } path = StringToLowerASCII(path); std::string response; if (path == kDnsPath) { AboutDnsHandler::Start(this, request_id); return; } else if (path == kHistogramsPath) { response = AboutHistograms(info); } else if (path == kMemoryPath) { AboutMemory(this, request_id); return; } else if (path == kMemoryRedirectPath) { response = GetAboutMemoryRedirectResponse(); #ifdef TRACK_ALL_TASK_OBJECTS } else if (path == kTasksPath) { response = AboutObjects(info); #endif } else if (path == kStatsPath) { response = AboutStats(info); #if defined(USE_TCMALLOC) } else if (path == kTcmallocPath) { response = AboutTcmalloc(info); #endif } else if (path == kVersionPath || path.empty()) { #if defined(OS_CHROMEOS) new ChromeOSAboutVersionHandler(this, request_id); return; #else DictionaryValue value; response = AboutVersion(&value); #endif } else if (path == kCreditsPath) { response = ResourceBundle::GetSharedInstance().GetRawDataResource( IDR_CREDITS_HTML).as_string(); } else if (path == kAboutPath) { response = AboutAbout(); #if defined(OS_CHROMEOS) } else if (path == kOSCreditsPath) { response = ResourceBundle::GetSharedInstance().GetRawDataResource( IDR_OS_CREDITS_HTML).as_string(); } else if (path == kNetworkPath) { response = AboutNetwork(info); #endif } else if (path == kTermsPath) { #if defined(OS_CHROMEOS) ChromeOSTermsHandler::Start(this, request_id); return; #else response = ResourceBundle::GetSharedInstance().GetRawDataResource( IDR_TERMS_HTML).as_string(); #endif #if defined(OS_LINUX) } else if (path == kLinuxProxyConfigPath) { response = AboutLinuxProxyConfig(); } else if (path == kSandboxPath) { response = AboutSandbox(); #endif } FinishDataRequest(response, request_id); } void AboutSource::FinishDataRequest(const std::string& response, int request_id) { scoped_refptr<RefCountedBytes> html_bytes(new RefCountedBytes); html_bytes->data.resize(response.size()); std::copy(response.begin(), response.end(), html_bytes->data.begin()); SendResponse(request_id, html_bytes); } // AboutMemoryHandler ---------------------------------------------------------- // Helper for AboutMemory to bind results from a ProcessMetrics object // to a DictionaryValue. Fills ws_usage and comm_usage so that the objects // can be used in caller's scope (e.g for appending to a net total). void AboutMemoryHandler::BindProcessMetrics(DictionaryValue* data, ProcessMemoryInformation* info) { DCHECK(data && info); // Bind metrics to dictionary. data->SetInteger("ws_priv", static_cast<int>(info->working_set.priv)); data->SetInteger("ws_shareable", static_cast<int>(info->working_set.shareable)); data->SetInteger("ws_shared", static_cast<int>(info->working_set.shared)); data->SetInteger("comm_priv", static_cast<int>(info->committed.priv)); data->SetInteger("comm_map", static_cast<int>(info->committed.mapped)); data->SetInteger("comm_image", static_cast<int>(info->committed.image)); data->SetInteger("pid", info->pid); data->SetString("version", info->version); data->SetInteger("processes", info->num_processes); } // Helper for AboutMemory to append memory usage information for all // sub-processes (i.e. renderers, plugins) used by Chrome. void AboutMemoryHandler::AppendProcess(ListValue* child_data, ProcessMemoryInformation* info) { DCHECK(child_data && info); // Append a new DictionaryValue for this renderer to our list. DictionaryValue* child = new DictionaryValue(); child_data->Append(child); BindProcessMetrics(child, info); std::string child_label( ChildProcessInfo::GetFullTypeNameInEnglish(info->type, info->renderer_type)); if (info->is_diagnostics) child_label.append(" (diagnostics)"); child->SetString("child_name", child_label); ListValue* titles = new ListValue(); child->Set("titles", titles); for (size_t i = 0; i < info->titles.size(); ++i) titles->Append(new StringValue(info->titles[i])); } void AboutMemoryHandler::OnDetailsAvailable() { // the root of the JSON hierarchy for about:memory jstemplate DictionaryValue root; ListValue* browsers = new ListValue(); root.Set("browsers", browsers); const std::vector<ProcessData>& browser_processes = processes(); // Aggregate per-process data into browser summary data. std::wstring log_string; for (size_t index = 0; index < browser_processes.size(); index++) { if (browser_processes[index].processes.empty()) continue; // Sum the information for the processes within this browser. ProcessMemoryInformation aggregate; ProcessMemoryInformationList::const_iterator iterator; iterator = browser_processes[index].processes.begin(); aggregate.pid = iterator->pid; aggregate.version = iterator->version; while (iterator != browser_processes[index].processes.end()) { if (!iterator->is_diagnostics || browser_processes[index].processes.size() == 1) { aggregate.working_set.priv += iterator->working_set.priv; aggregate.working_set.shared += iterator->working_set.shared; aggregate.working_set.shareable += iterator->working_set.shareable; aggregate.committed.priv += iterator->committed.priv; aggregate.committed.mapped += iterator->committed.mapped; aggregate.committed.image += iterator->committed.image; aggregate.num_processes++; } ++iterator; } DictionaryValue* browser_data = new DictionaryValue(); browsers->Append(browser_data); browser_data->SetString("name", browser_processes[index].name); BindProcessMetrics(browser_data, &aggregate); // We log memory info as we record it. if (log_string.length() > 0) log_string.append(L", "); log_string.append(UTF16ToWide(browser_processes[index].name)); log_string.append(L", "); log_string.append(UTF8ToWide( base::Int64ToString(aggregate.working_set.priv))); log_string.append(L", "); log_string.append(UTF8ToWide( base::Int64ToString(aggregate.working_set.shared))); log_string.append(L", "); log_string.append(UTF8ToWide( base::Int64ToString(aggregate.working_set.shareable))); } if (log_string.length() > 0) VLOG(1) << "memory: " << log_string; // Set the browser & renderer detailed process data. DictionaryValue* browser_data = new DictionaryValue(); root.Set("browzr_data", browser_data); ListValue* child_data = new ListValue(); root.Set("child_data", child_data); ProcessData process = browser_processes[0]; // Chrome is the first browser. root.SetString("current_browser_name", process.name); for (size_t index = 0; index < process.processes.size(); index++) { if (process.processes[index].type == ChildProcessInfo::BROWSER_PROCESS) BindProcessMetrics(browser_data, &process.processes[index]); else AppendProcess(child_data, &process.processes[index]); } root.SetBoolean("show_other_browsers", browser_defaults::kShowOtherBrowsersInAboutMemory); // Get about_memory.html static const base::StringPiece memory_html( ResourceBundle::GetSharedInstance().GetRawDataResource( IDR_ABOUT_MEMORY_HTML)); // Create jstemplate and return. std::string template_html = jstemplate_builder::GetTemplateHtml( memory_html, &root, "t" /* template root node id */); source_->FinishDataRequest(template_html, request_id_); } #if defined(OS_CHROMEOS) // ChromeOSAboutVersionHandler ----------------------------------------------- ChromeOSAboutVersionHandler::ChromeOSAboutVersionHandler(AboutSource* source, int request_id) : source_(source), request_id_(request_id) { loader_.EnablePlatformVersions(true); loader_.GetVersion(&consumer_, NewCallback(this, &ChromeOSAboutVersionHandler::OnVersion), chromeos::VersionLoader::VERSION_FULL); } void ChromeOSAboutVersionHandler::OnVersion( chromeos::VersionLoader::Handle handle, std::string version) { DictionaryValue localized_strings; localized_strings.SetString("os_name", l10n_util::GetStringUTF16(IDS_PRODUCT_OS_NAME)); localized_strings.SetString("os_version", version); localized_strings.SetBoolean("is_chrome_os", true); source_->FinishDataRequest(AboutVersion(&localized_strings), request_id_); // CancelableRequestProvider isn't happy when it's deleted and servicing a // task, so we delay the deletion. MessageLoop::current()->DeleteSoon(FROM_HERE, this); } #endif // Returns true if |url|'s spec starts with |about_specifier|, and is // terminated by the start of a path. bool StartsWithAboutSpecifier(const GURL& url, const char* about_specifier) { return StartsWithASCII(url.spec(), about_specifier, true) && (url.spec().size() == strlen(about_specifier) || url.spec()[strlen(about_specifier)] == '/'); } // Transforms a URL of the form "about:foo/XXX" to <url_prefix> + "XXX". GURL RemapAboutURL(const std::string& url_prefix, const GURL& url) { std::string path; size_t split = url.spec().find('/'); if (split != std::string::npos) path = url.spec().substr(split + 1); return GURL(url_prefix + path); } } // namespace // ----------------------------------------------------------------------------- bool WillHandleBrowserAboutURL(GURL* url, Profile* profile) { // We only handle about: schemes. if (!url->SchemeIs(chrome::kAboutScheme)) return false; // about:blank is special. Frames are allowed to access about:blank, // but they are not allowed to access other types of about pages. // Just ignore the about:blank and let the TAB_CONTENTS_WEB handle it. if (LowerCaseEqualsASCII(url->spec(), chrome::kAboutBlankURL)) return false; // Rewrite about:cache/* URLs to chrome://view-http-cache/* if (StartsWithAboutSpecifier(*url, chrome::kAboutCacheURL)) { *url = RemapAboutURL(chrome::kNetworkViewCacheURL, *url); return true; } #if defined(OS_WIN) // Rewrite about:conflicts/* URLs to chrome://conflicts/* if (StartsWithAboutSpecifier(*url, chrome::kAboutConflicts)) { *url = GURL(chrome::kChromeUIConflictsURL); return true; } #endif // Rewrite about:flags to chrome://flags/. if (LowerCaseEqualsASCII(url->spec(), chrome::kAboutFlagsURL)) { *url = GURL(chrome::kChromeUIFlagsURL); return true; } // Rewrite about:net-internals/* URLs to chrome://net-internals/* if (StartsWithAboutSpecifier(*url, chrome::kAboutNetInternalsURL)) { *url = RemapAboutURL(chrome::kNetworkViewInternalsURL, *url); return true; } // Rewrite about:gpu/* URLs to chrome://gpu-internals/* if (StartsWithAboutSpecifier(*url, chrome::kAboutGpuURL)) { *url = RemapAboutURL(chrome::kGpuInternalsURL, *url); return true; } // Rewrite about:appcache-internals/* URLs to chrome://appcache/* if (StartsWithAboutSpecifier(*url, chrome::kAboutAppCacheInternalsURL)) { *url = RemapAboutURL(chrome::kAppCacheViewInternalsURL, *url); return true; } // Rewrite about:sync-internals/* URLs (and about:sync, too, for // legacy reasons) to chrome://sync-internals/* if (StartsWithAboutSpecifier(*url, chrome::kAboutSyncInternalsURL) || StartsWithAboutSpecifier(*url, chrome::kAboutSyncURL)) { *url = RemapAboutURL(chrome::kSyncViewInternalsURL, *url); return true; } // Rewrite about:plugins to chrome://plugins/. if (LowerCaseEqualsASCII(url->spec(), chrome::kAboutPluginsURL)) { *url = GURL(chrome::kChromeUIPluginsURL); return true; } // Handle URL to crash the browser process. if (LowerCaseEqualsASCII(url->spec(), chrome::kAboutBrowserCrash)) { // Induce an intentional crash in the browser process. int* bad_pointer = NULL; *bad_pointer = 42; return true; } // Handle URLs to wreck the gpu process. if (LowerCaseEqualsASCII(url->spec(), chrome::kAboutGpuCrashURL)) { GpuProcessHost::SendOnIO( 0, content::CAUSE_FOR_GPU_LAUNCH_ABOUT_GPUCRASH, new GpuMsg_Crash()); } if (LowerCaseEqualsASCII(url->spec(), chrome::kAboutGpuHangURL)) { GpuProcessHost::SendOnIO( 0, content::CAUSE_FOR_GPU_LAUNCH_ABOUT_GPUHANG, new GpuMsg_Hang()); } // There are a few about: URLs that we hand over to the renderer. If the // renderer wants them, don't do any rewriting. if (chrome_about_handler::WillHandle(*url)) return false; // Anything else requires our special handler; make sure it's initialized. InitializeAboutDataSource(profile); // Special case about:memory to go through a redirect before ending up on // the final page. See GetAboutMemoryRedirectResponse above for why. if (LowerCaseEqualsASCII(url->path(), kMemoryPath)) { *url = GURL("chrome://about/memory-redirect"); return true; } // Rewrite the about URL to use chrome:. WebKit treats all about URLS the // same (blank page), so if we want to display content, we need another // scheme. std::string about_url = "chrome://about/"; about_url.append(url->path()); *url = GURL(about_url); return true; } void InitializeAboutDataSource(Profile* profile) { profile->GetChromeURLDataManager()->AddDataSource(new AboutSource()); } // This function gets called with the fixed-up chrome: URLs, so we have to // compare against those instead of "about:blah". bool HandleNonNavigationAboutURL(const GURL& url) { // about:ipc is currently buggy, so we disable it for official builds. #if !defined(OFFICIAL_BUILD) #if (defined(OS_MACOSX) || defined(OS_WIN)) && defined(IPC_MESSAGE_LOG_ENABLED) if (LowerCaseEqualsASCII(url.spec(), chrome::kChromeUIIPCURL)) { // Run the dialog. This will re-use the existing one if it's already up. browser::ShowAboutIPCDialog(); return true; } #endif #endif // OFFICIAL_BUILD return false; } std::vector<std::string> AboutPaths() { std::vector<std::string> paths; paths.reserve(arraysize(kAllAboutPaths)); for (size_t i = 0; i < arraysize(kAllAboutPaths); i++) paths.push_back(kAllAboutPaths[i]); return paths; }
34.835714
80
0.682079
SlimKatLegacy
e1bcf0e1c0f36881dfa16fe003ce5e70fa5f7ae9
13,359
cpp
C++
01_Develop/libXMFFmpeg/Source/libavcodec/elbg.cpp
mcodegeeks/OpenKODE-Framework
d4382d781da7f488a0e7667362a89e8e389468dd
[ "MIT" ]
2
2017-08-03T07:15:00.000Z
2018-06-18T10:32:53.000Z
01_Develop/libXMFFmpeg/Source/libavcodec/elbg.cpp
mcodegeeks/OpenKODE-Framework
d4382d781da7f488a0e7667362a89e8e389468dd
[ "MIT" ]
null
null
null
01_Develop/libXMFFmpeg/Source/libavcodec/elbg.cpp
mcodegeeks/OpenKODE-Framework
d4382d781da7f488a0e7667362a89e8e389468dd
[ "MIT" ]
2
2019-03-04T22:57:42.000Z
2020-03-06T01:32:26.000Z
/* * Copyright (C) 2007 Vitor Sessak <vitor1001@gmail.com> * * 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 * Codebook Generator using the ELBG algorithm */ #include "XMFFmpeg/libavutil/lfg.h" #include "elbg.h" #include "internal.h" #define DELTA_ERR_MAX 0.1 ///< Precision of the ELBG algorithm (as percentual error) /** * In the ELBG jargon, a cell is the set of points that are closest to a * codebook entry. Not to be confused with a RoQ Video cell. */ typedef struct cell_s { int index; struct cell_s *next; } cell; /** * ELBG internal data */ typedef struct{ int error; int dim; int numCB; int *codebook; cell **cells; int *utility; int *utility_inc; int *nearest_cb; int *points; AVLFG *rand_state; int *scratchbuf; } elbg_data; static inline int distance_limited(int *a, int *b, int dim, int limit) { int i, dist=0; for (i=0; i<dim; i++) { dist += (a[i] - b[i])*(a[i] - b[i]); if (dist > limit) return INT_MAX; } return dist; } static inline void vect_division(int *res, int *vect, int div, int dim) { int i; if (div > 1) for (i=0; i<dim; i++) res[i] = ROUNDED_DIV(vect[i],div); else if (res != vect) memcpy(res, vect, dim*sizeof(int)); } static int eval_error_cell(elbg_data *elbg, int *centroid, cell *cells) { int error=0; for (; cells; cells=cells->next) error += distance_limited(centroid, elbg->points + cells->index*elbg->dim, elbg->dim, INT_MAX); return error; } static int get_closest_codebook(elbg_data *elbg, int index) { int i, pick=0, diff, diff_min = INT_MAX; for (i=0; i<elbg->numCB; i++) if (i != index) { diff = distance_limited(elbg->codebook + i*elbg->dim, elbg->codebook + index*elbg->dim, elbg->dim, diff_min); if (diff < diff_min) { pick = i; diff_min = diff; } } return pick; } static int get_high_utility_cell(elbg_data *elbg) { int i=0; /* Using linear search, do binary if it ever turns to be speed critical */ int r = av_lfg_get(elbg->rand_state)%elbg->utility_inc[elbg->numCB-1] + 1; while (elbg->utility_inc[i] < r) i++; assert(!elbg->cells[i]); return i; } /** * Implementation of the simple LBG algorithm for just two codebooks */ static int simple_lbg(elbg_data *elbg, int dim, int *centroid[3], int newutility[3], int *points, cell *cells) { int i, idx; int numpoints[2] = {0,0}; int *newcentroid[2] = { elbg->scratchbuf + 3*dim, elbg->scratchbuf + 4*dim }; cell *tempcell; memset(newcentroid[0], 0, 2 * dim * sizeof(*newcentroid[0])); newutility[0] = newutility[1] = 0; for (tempcell = cells; tempcell; tempcell=tempcell->next) { idx = distance_limited(centroid[0], points + tempcell->index*dim, dim, INT_MAX)>= distance_limited(centroid[1], points + tempcell->index*dim, dim, INT_MAX); numpoints[idx]++; for (i=0; i<dim; i++) newcentroid[idx][i] += points[tempcell->index*dim + i]; } vect_division(centroid[0], newcentroid[0], numpoints[0], dim); vect_division(centroid[1], newcentroid[1], numpoints[1], dim); for (tempcell = cells; tempcell; tempcell=tempcell->next) { int dist[2] = {distance_limited(centroid[0], points + tempcell->index*dim, dim, INT_MAX), distance_limited(centroid[1], points + tempcell->index*dim, dim, INT_MAX)}; int idx = dist[0] > dist[1]; newutility[idx] += dist[idx]; } return newutility[0] + newutility[1]; } static void get_new_centroids(elbg_data *elbg, int huc, int *newcentroid_i, int *newcentroid_p) { cell *tempcell; int *min = newcentroid_i; int *max = newcentroid_p; int i; for (i=0; i< elbg->dim; i++) { min[i]=INT_MAX; max[i]=0; } for (tempcell = elbg->cells[huc]; tempcell; tempcell = tempcell->next) for(i=0; i<elbg->dim; i++) { min[i]=FFMIN(min[i], elbg->points[tempcell->index*elbg->dim + i]); max[i]=FFMAX(max[i], elbg->points[tempcell->index*elbg->dim + i]); } for (i=0; i<elbg->dim; i++) { int ni = min[i] + (max[i] - min[i])/3; int np = min[i] + (2*(max[i] - min[i]))/3; newcentroid_i[i] = ni; newcentroid_p[i] = np; } } /** * Add the points in the low utility cell to its closest cell. Split the high * utility cell, putting the separed points in the (now empty) low utility * cell. * * @param elbg Internal elbg data * @param indexes {luc, huc, cluc} * @param newcentroid A vector with the position of the new centroids */ static void shift_codebook(elbg_data *elbg, int *indexes, int *newcentroid[3]) { cell *tempdata; cell **pp = &elbg->cells[indexes[2]]; while(*pp) pp= &(*pp)->next; *pp = elbg->cells[indexes[0]]; elbg->cells[indexes[0]] = NULL; tempdata = elbg->cells[indexes[1]]; elbg->cells[indexes[1]] = NULL; while(tempdata) { cell *tempcell2 = tempdata->next; int idx = distance_limited(elbg->points + tempdata->index*elbg->dim, newcentroid[0], elbg->dim, INT_MAX) > distance_limited(elbg->points + tempdata->index*elbg->dim, newcentroid[1], elbg->dim, INT_MAX); tempdata->next = elbg->cells[indexes[idx]]; elbg->cells[indexes[idx]] = tempdata; tempdata = tempcell2; } } static void evaluate_utility_inc(elbg_data *elbg) { int i, inc=0; for (i=0; i < elbg->numCB; i++) { if (elbg->numCB*elbg->utility[i] > elbg->error) inc += elbg->utility[i]; elbg->utility_inc[i] = inc; } } static void update_utility_and_n_cb(elbg_data *elbg, int idx, int newutility) { cell *tempcell; elbg->utility[idx] = newutility; for (tempcell=elbg->cells[idx]; tempcell; tempcell=tempcell->next) elbg->nearest_cb[tempcell->index] = idx; } /** * Evaluate if a shift lower the error. If it does, call shift_codebooks * and update elbg->error, elbg->utility and elbg->nearest_cb. * * @param elbg Internal elbg data * @param idx {luc (low utility cell, huc (high utility cell), cluc (closest cell to low utility cell)} */ static void try_shift_candidate(elbg_data *elbg, int idx[3]) { int j, k, olderror=0, newerror, cont=0; int newutility[3]; int *newcentroid[3] = { elbg->scratchbuf, elbg->scratchbuf + elbg->dim, elbg->scratchbuf + 2*elbg->dim }; cell *tempcell; for (j=0; j<3; j++) olderror += elbg->utility[idx[j]]; memset(newcentroid[2], 0, elbg->dim*sizeof(int)); for (k=0; k<2; k++) for (tempcell=elbg->cells[idx[2*k]]; tempcell; tempcell=tempcell->next) { cont++; for (j=0; j<elbg->dim; j++) newcentroid[2][j] += elbg->points[tempcell->index*elbg->dim + j]; } vect_division(newcentroid[2], newcentroid[2], cont, elbg->dim); get_new_centroids(elbg, idx[1], newcentroid[0], newcentroid[1]); newutility[2] = eval_error_cell(elbg, newcentroid[2], elbg->cells[idx[0]]); newutility[2] += eval_error_cell(elbg, newcentroid[2], elbg->cells[idx[2]]); newerror = newutility[2]; newerror += simple_lbg(elbg, elbg->dim, newcentroid, newutility, elbg->points, elbg->cells[idx[1]]); if (olderror > newerror) { shift_codebook(elbg, idx, newcentroid); elbg->error += newerror - olderror; for (j=0; j<3; j++) update_utility_and_n_cb(elbg, idx[j], newutility[j]); evaluate_utility_inc(elbg); } } /** * Implementation of the ELBG block */ static void do_shiftings(elbg_data *elbg) { int idx[3]; evaluate_utility_inc(elbg); for (idx[0]=0; idx[0] < elbg->numCB; idx[0]++) if (elbg->numCB*elbg->utility[idx[0]] < elbg->error) { if (elbg->utility_inc[elbg->numCB-1] == 0) return; idx[1] = get_high_utility_cell(elbg); idx[2] = get_closest_codebook(elbg, idx[0]); if (idx[1] != idx[0] && idx[1] != idx[2]) try_shift_candidate(elbg, idx); } } #define BIG_PRIME 433494437LL void ff_init_elbg(int *points, int dim, int numpoints, int *codebook, int numCB, int max_steps, int *closest_cb, AVLFG *rand_state) { int i, k; if (numpoints > 24*numCB) { /* ELBG is very costly for a big number of points. So if we have a lot of them, get a good initial codebook to save on iterations */ int *temp_points = (int *)av_malloc(dim*(numpoints/8)*sizeof(int)); for (i=0; i<numpoints/8; i++) { k = (i*BIG_PRIME) % numpoints; memcpy(temp_points + i*dim, points + k*dim, dim*sizeof(int)); } ff_init_elbg(temp_points, dim, numpoints/8, codebook, numCB, 2*max_steps, closest_cb, rand_state); ff_do_elbg(temp_points, dim, numpoints/8, codebook, numCB, 2*max_steps, closest_cb, rand_state); av_free(temp_points); } else // If not, initialize the codebook with random positions for (i=0; i < numCB; i++) memcpy(codebook + i*dim, points + ((i*BIG_PRIME)%numpoints)*dim, dim*sizeof(int)); } void ff_do_elbg(int *points, int dim, int numpoints, int *codebook, int numCB, int max_steps, int *closest_cb, AVLFG *rand_state) { int dist; elbg_data elbg_d; elbg_data *elbg = &elbg_d; int i, j, k, last_error, steps=0; int *dist_cb = (int *)av_malloc(numpoints*sizeof(int)); int *size_part = (int *)av_malloc(numCB*sizeof(int)); cell *list_buffer = (cell *)av_malloc(numpoints*sizeof(cell)); cell *free_cells; int best_dist, best_idx = 0; elbg->error = INT_MAX; elbg->dim = dim; elbg->numCB = numCB; elbg->codebook = codebook; elbg->cells = (cell **)av_malloc(numCB*sizeof(cell *)); elbg->utility = (int *)av_malloc(numCB*sizeof(int)); elbg->nearest_cb = closest_cb; elbg->points = points; elbg->utility_inc = (int *)av_malloc(numCB*sizeof(int)); elbg->scratchbuf = (int *)av_malloc(5*dim*sizeof(int)); elbg->rand_state = rand_state; do { free_cells = list_buffer; last_error = elbg->error; steps++; memset(elbg->utility, 0, numCB*sizeof(int)); memset(elbg->cells, 0, numCB*sizeof(cell *)); elbg->error = 0; /* This loop evaluate the actual Voronoi partition. It is the most costly part of the algorithm. */ for (i=0; i < numpoints; i++) { best_dist = distance_limited(elbg->points + i*elbg->dim, elbg->codebook + best_idx*elbg->dim, dim, INT_MAX); for (k=0; k < elbg->numCB; k++) { dist = distance_limited(elbg->points + i*elbg->dim, elbg->codebook + k*elbg->dim, dim, best_dist); if (dist < best_dist) { best_dist = dist; best_idx = k; } } elbg->nearest_cb[i] = best_idx; dist_cb[i] = best_dist; elbg->error += dist_cb[i]; elbg->utility[elbg->nearest_cb[i]] += dist_cb[i]; free_cells->index = i; free_cells->next = elbg->cells[elbg->nearest_cb[i]]; elbg->cells[elbg->nearest_cb[i]] = free_cells; free_cells++; } do_shiftings(elbg); memset(size_part, 0, numCB*sizeof(int)); memset(elbg->codebook, 0, elbg->numCB*dim*sizeof(int)); for (i=0; i < numpoints; i++) { size_part[elbg->nearest_cb[i]]++; for (j=0; j < elbg->dim; j++) elbg->codebook[elbg->nearest_cb[i]*elbg->dim + j] += elbg->points[i*elbg->dim + j]; } for (i=0; i < elbg->numCB; i++) vect_division(elbg->codebook + i*elbg->dim, elbg->codebook + i*elbg->dim, size_part[i], elbg->dim); } while(((last_error - elbg->error) > DELTA_ERR_MAX*elbg->error) && (steps < max_steps)); av_free(dist_cb); av_free(size_part); av_free(elbg->utility); av_free(list_buffer); av_free(elbg->cells); av_free(elbg->utility_inc); av_free(elbg->scratchbuf); }
30.710345
121
0.583352
mcodegeeks
e1c07c5359b23b757bdd414a27ae76a23c864f28
685
hpp
C++
examples/simple/src/MagicItem.hpp
mohibqureshi/CXXCTP
db7c80da469fe3511f7d8ac7f7dee7391122dac6
[ "MIT" ]
63
2019-08-30T11:53:47.000Z
2021-05-19T06:17:47.000Z
examples/simple/src/MagicItem.hpp
mohibqureshi/CXXCTP
db7c80da469fe3511f7d8ac7f7dee7391122dac6
[ "MIT" ]
96
2019-09-16T05:03:31.000Z
2020-10-14T14:33:50.000Z
examples/simple/src/MagicItem.hpp
mohibqureshi/CXXCTP
db7c80da469fe3511f7d8ac7f7dee7391122dac6
[ "MIT" ]
27
2019-09-25T10:12:37.000Z
2020-05-06T02:59:44.000Z
#pragma once #include <vector> #include <string> // like `trait` struct MagicItem { virtual void has_enough_mana(const char* spellname) const noexcept = 0; /// \note same for all types // @gen(inject_to_all) //S interface_data; }; template<typename T1> struct ParentTemplated_1 { virtual void has_P1(T1 name1) const noexcept = 0; }; template<typename T1> struct ParentTemplated_2 { virtual void has_P2(T1 name1) const noexcept = 0; }; // like `trait` template<typename T1, typename T2> struct MagicTemplated { virtual void has_T(const T1& name1, const T2& name2) const noexcept = 0; /// \note same for all types // @gen(inject_to_all) //S interface_data; };
18.026316
74
0.710949
mohibqureshi
e1c195158e1ba471ea00b780d2d32151efee812b
1,891
cpp
C++
src/core/blendmode.cpp
egormkn/sdlxx
6cb834f391dca629ac3cc38eae94d4d1d74ad040
[ "Zlib" ]
9
2018-05-25T05:50:50.000Z
2021-09-16T19:12:01.000Z
src/core/blendmode.cpp
egormkn/sdlxx
6cb834f391dca629ac3cc38eae94d4d1d74ad040
[ "Zlib" ]
5
2017-04-05T00:57:10.000Z
2021-08-29T07:46:46.000Z
src/core/blendmode.cpp
egormkn/sdlxx
6cb834f391dca629ac3cc38eae94d4d1d74ad040
[ "Zlib" ]
4
2018-10-29T15:59:31.000Z
2021-12-19T05:20:10.000Z
#include "sdlxx/core/blendmode.h" #include <SDL_blendmode.h> #include "sdlxx/utils/bitmask.h" using namespace sdlxx; #define ASSERT_BLENDMODE(x) \ static_assert(static_cast<SDL_BlendMode>(BlendMode::x) == SDL_BLENDMODE_##x); ASSERT_BLENDMODE(NONE); ASSERT_BLENDMODE(BLEND); ASSERT_BLENDMODE(ADD); ASSERT_BLENDMODE(MOD); ASSERT_BLENDMODE(MUL); ASSERT_BLENDMODE(INVALID); #define ASSERT_BLENDOPERATION(x) \ static_assert(static_cast<SDL_BlendOperation>(BlendOperation::x) == SDL_BLENDOPERATION_##x); ASSERT_BLENDOPERATION(ADD); ASSERT_BLENDOPERATION(SUBTRACT); ASSERT_BLENDOPERATION(REV_SUBTRACT); ASSERT_BLENDOPERATION(MINIMUM); ASSERT_BLENDOPERATION(MAXIMUM); #define ASSERT_BLENDFACTOR(x) \ static_assert(static_cast<SDL_BlendFactor>(BlendFactor::x) == SDL_BLENDFACTOR_##x); ASSERT_BLENDFACTOR(ZERO); ASSERT_BLENDFACTOR(ONE); ASSERT_BLENDFACTOR(SRC_COLOR); ASSERT_BLENDFACTOR(ONE_MINUS_SRC_COLOR); ASSERT_BLENDFACTOR(SRC_ALPHA); ASSERT_BLENDFACTOR(ONE_MINUS_SRC_ALPHA); ASSERT_BLENDFACTOR(DST_COLOR); ASSERT_BLENDFACTOR(ONE_MINUS_DST_COLOR); ASSERT_BLENDFACTOR(DST_ALPHA); ASSERT_BLENDFACTOR(ONE_MINUS_DST_ALPHA); BitMask<BlendMode> ComposeCustomBlendMode( BlendFactor src_color_factor, BlendFactor dst_color_factor, BlendOperation color_operation, BlendFactor src_alpha_factor, BlendFactor dst_alpha_factor, BlendOperation alpha_operation) { return BitMask<BlendMode>{ SDL_ComposeCustomBlendMode(static_cast<SDL_BlendFactor>(src_color_factor), static_cast<SDL_BlendFactor>(dst_color_factor), static_cast<SDL_BlendOperation>(color_operation), static_cast<SDL_BlendFactor>(src_alpha_factor), static_cast<SDL_BlendFactor>(dst_alpha_factor), static_cast<SDL_BlendOperation>(alpha_operation))}; }
35.679245
97
0.763617
egormkn
e1c25902040a3b76343d34dadd5d30c95e9f78a0
813
cpp
C++
lib/expression.cpp
julienlopez/DifferentialGeometry2
f720ac4f2966a347ab69eb4df1350fb271b63ed6
[ "MIT" ]
null
null
null
lib/expression.cpp
julienlopez/DifferentialGeometry2
f720ac4f2966a347ab69eb4df1350fb271b63ed6
[ "MIT" ]
1
2021-01-31T14:34:39.000Z
2021-01-31T14:34:39.000Z
lib/expression.cpp
julienlopez/DifferentialGeometry2
f720ac4f2966a347ab69eb4df1350fb271b63ed6
[ "MIT" ]
null
null
null
#include "expression.hpp" #include "comparison.hpp" bool operator==(const Constant& c1, const Constant& c2) { return c1.name == c2.name; } bool operator==(const Value& v1, const Value& v2) { return v1.value == v2.value; } bool operator==(const Variable& v1, const Variable& v2) { return v1.name == v2.name; } bool operator==(const Sum& s1, const Sum& s2) { return std::equal(begin(s1.operands), end(s1.operands), begin(s2.operands), end(s2.operands)); } bool operator==(const Product& s1, const Product& s2) { return std::equal(begin(s1.operands), end(s1.operands), begin(s2.operands), end(s2.operands)); } bool operator==(const Cos& c1, const Cos& c2) { return areEqual(c1.expr, c2.expr); } bool operator==(const Sin& s1, const Sin& s2) { return areEqual(s1.expr, s2.expr); }
20.846154
98
0.669127
julienlopez
e1c266de503102c06917d44280aceeeb9642c139
1,465
cpp
C++
src/impl/DgBinaryReader.cpp
int-Frank/DgLib
34363649a5eb802ed237efeb9237d459b1920c9c
[ "MIT" ]
1
2020-01-04T20:17:44.000Z
2020-01-04T20:17:44.000Z
src/impl/DgBinaryReader.cpp
int-Frank/DgLib
34363649a5eb802ed237efeb9237d459b1920c9c
[ "MIT" ]
7
2016-05-28T22:41:57.000Z
2020-12-22T00:10:11.000Z
src/impl/DgBinaryReader.cpp
int-Frank/DgLib
34363649a5eb802ed237efeb9237d459b1920c9c
[ "MIT" ]
null
null
null
//@group Misc/impl #include "../DgBinaryReader.h" namespace Dg { BinaryReader::BinaryReader(EndianConverter const a_ec) : BinaryIO(a_ec) { } BinaryReader::BinaryReader(Stream * a_pStream, EndianConverter const a_ec) : BinaryIO(a_ec) { Open(a_pStream); } BinaryReader::~BinaryReader() { } BinaryReader::BinaryReader(BinaryReader && a_rhs) noexcept : BinaryIO(std::move(a_rhs)) { } BinaryReader & BinaryReader::operator=(BinaryReader && a_rhs) noexcept { if (this != &a_rhs) { BinaryIO::operator=(std::move(a_rhs)); } return *this; } ErrorCode BinaryReader::Open(Stream * a_pStream) { Close(); if (a_pStream == nullptr) return ErrorCode::InvalidInput; if (!a_pStream->IsReadable()) return ErrorCode::Disallowed; m_pStream = a_pStream; return ErrorCode::None; } IO::ReturnType BinaryReader::Read_string(std::string * a_out, IO::myInt const a_count) { if (a_count < 0 || a_out == nullptr) return IO::ReturnType{ErrorCode::InvalidInput, 0}; IO::myInt curSze = static_cast<IO::myInt>(a_out->size()); a_out->resize(curSze + a_count); return Read<char>(&(*a_out)[curSze], a_count); } IO::ReturnType BinaryReader::ReadRaw(void * a_buffer, IO::myInt const a_count) { if (m_pStream == nullptr) return IO::ReturnType{ErrorCode::NullObject, IO::INVALID_VALUE}; return m_pStream->Read(a_buffer, a_count); } }
20.928571
88
0.653925
int-Frank