hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 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 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 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 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
25db8cf7a5ca8f23db9e1b15505d7c17828426e7 | 4,016 | cpp | C++ | src/Graph.cpp | pimmen89/Overseer | cc92aa13a875b573d509034a16354b515b575afc | [
"MIT"
] | 10 | 2017-09-25T18:00:38.000Z | 2018-02-12T06:09:30.000Z | src/Graph.cpp | pimmen89/Overseer | cc92aa13a875b573d509034a16354b515b575afc | [
"MIT"
] | 4 | 2017-09-25T18:23:41.000Z | 2018-01-24T19:33:59.000Z | src/Graph.cpp | pimmen89/Overseer | cc92aa13a875b573d509034a16354b515b575afc | [
"MIT"
] | null | null | null | #include "Graph.h"
namespace Overseer{
/*
****************************
*** Public members start ***
****************************
*/
Graph::Graph(){}
Graph::Graph(Map* map):p_map(map){}
std::vector<ChokePoint> Graph::getChokePoints(size_t region_id_a, size_t region_id_b) const {
assert(ValidId(region_id_a) && ValidId(region_id_b));
if (region_id_a > region_id_b) {
std::swap(region_id_a, region_id_b);
}
return m_ChokePointsMatrix[region_id_b][region_id_a];
}
void Graph::CreateChokePoints() {
num_regions = p_map->getRegions().size();
std::vector<ChokePoint> chokePoints;
std::vector<std::deque<TilePosition>> clusters;
for(auto const & frontierByRegionPair : p_map->getRawFrontier()) {
//Flag to signify if the frontierPosition was added to cluster
size_t regionIdA = frontierByRegionPair.first.first;
size_t regionIdB = frontierByRegionPair.first.second;
std::vector<TilePosition> frontierPositions = frontierByRegionPair.second;
std::sort(frontierPositions.begin(), frontierPositions.end(), GreaterTileInstance());
for(auto frontierPosition : frontierPositions) {
bool added = false;
for(auto & cluster : clusters) {
float dist_front = sc2::Distance2D(frontierPosition.first, cluster.front().first);
float dist_back = sc2::Distance2D(frontierPosition.first, cluster.back().first);
if(std::min(dist_front, dist_back) <= min_cluster_distance) {
if(dist_front < dist_back) {
cluster.push_front(frontierPosition);
} else {
cluster.push_back(frontierPosition);
}
added = true;
break;
}
}
if(!added) {
std::deque<TilePosition> clusterPositions;
clusterPositions.push_back(frontierPosition);
clusters.push_back(clusterPositions);
}
}
for(auto cluster : clusters) {
std::vector<TilePosition> clusterPositions;
while (!cluster.empty()) {
TilePosition clusterPosition = cluster.front();
clusterPositions.push_back(clusterPosition);
cluster.pop_front();
}
ChokePoint cp(this, p_map->getRegion(regionIdA), p_map->getRegion(regionIdB),clusterPositions);
chokePoints.emplace_back(cp);
}
}
ComputeAdjacencyMatrix(chokePoints);
}
void Graph::ComputeAdjacencyMatrix(std::vector<ChokePoint> chokePoints) {
m_ChokePointsMatrix.resize(num_regions + 1);
for(size_t i = 1; i <= num_regions; ++i) {
m_ChokePointsMatrix[i].resize(i);
}
for(auto & chokePoint : chokePoints) {
size_t region_id_a = chokePoint.getRegions().first->getId();
size_t region_id_b = chokePoint.getRegions().second->getId();
if (region_id_a > region_id_b) {
std::swap(region_id_a, region_id_b);
}
m_ChokePointsMatrix[region_id_b][region_id_a].push_back(chokePoint);
}
}
void Graph::setMap(Map *map) {
p_map = map;
}
/*
***************************
*** Public members stop ***
***************************
***************************
***************************
***************************
*****************************
*** Priavte members start ***
*****************************
*/
bool Graph::ValidId(size_t id_arg) const {
return (id_arg >= 1) && (id_arg <= (num_regions + 1));
}
/*
****************************
*** Priavte members stop ***
****************************
*/
} | 31.622047 | 111 | 0.513446 | [
"vector"
] |
25dd73c9b07483ec25868959f26d76918819fa0c | 29,149 | cpp | C++ | src/modules/osgParticle/generated_code/Particle.pypp.cpp | cmbruns/osgpyplusplus | f8bfca2cf841e15f6ddb41c958f3ad0d0b9e4b75 | [
"BSD-3-Clause"
] | 3 | 2017-04-20T09:11:47.000Z | 2021-04-29T19:24:03.000Z | src/modules/osgParticle/generated_code/Particle.pypp.cpp | cmbruns/osgpyplusplus | f8bfca2cf841e15f6ddb41c958f3ad0d0b9e4b75 | [
"BSD-3-Clause"
] | null | null | null | src/modules/osgParticle/generated_code/Particle.pypp.cpp | cmbruns/osgpyplusplus | f8bfca2cf841e15f6ddb41c958f3ad0d0b9e4b75 | [
"BSD-3-Clause"
] | null | null | null | // This file has been generated by Py++.
#include "boost/python.hpp"
#include "wrap_osgParticle.h"
#include "Particle.pypp.hpp"
namespace bp = boost::python;
void register_Particle_class(){
{ //::osgParticle::Particle
typedef bp::class_< osgParticle::Particle > Particle_exposer_t;
Particle_exposer_t Particle_exposer = Particle_exposer_t( "Particle", "\n Implementation of a <B>particle</B>.\n Objects of this class are particles, they have some graphical properties\n and some physical properties. Particles are created by emitters and then placed\n into Particle Systems, where they live and get updated at each frame.\n Particles can either live forever (lifeTime < 0), or die after a specified\n time (lifeTime >= 0). For each property which is defined as a range of values, a\n current value will be evaluated at each frame by interpolating the <I>min</I>\n and <I>max</I> values so that <I>curr_value = min</I> when <I>t == 0</I>, and\n <I>curr_value = max</I> when <I>t == lifeTime</I>.\n You may customize the interpolator objects to achieve any kind of transition.\n If you want the particle to live forever, set its lifetime to any value <= 0;\n in that case, no interpolation is done to compute real-time properties, and only\n minimum values are used.\n", bp::init< >() );
bp::scope Particle_scope( Particle_exposer );
bp::scope().attr("INVALID_INDEX") = (int)osgParticle::Particle::INVALID_INDEX;
bp::enum_< osgParticle::Particle::Shape>("Shape")
.value("POINT", osgParticle::Particle::POINT)
.value("QUAD", osgParticle::Particle::QUAD)
.value("QUAD_TRIANGLESTRIP", osgParticle::Particle::QUAD_TRIANGLESTRIP)
.value("HEXAGON", osgParticle::Particle::HEXAGON)
.value("LINE", osgParticle::Particle::LINE)
.value("USER", osgParticle::Particle::USER)
.export_values()
;
{ //::osgParticle::Particle::addAngularVelocity
typedef void ( ::osgParticle::Particle::*addAngularVelocity_function_type )( ::osg::Vec3 const & ) ;
Particle_exposer.def(
"addAngularVelocity"
, addAngularVelocity_function_type( &::osgParticle::Particle::addAngularVelocity )
, ( bp::arg("dv") ) );
}
{ //::osgParticle::Particle::addVelocity
typedef void ( ::osgParticle::Particle::*addVelocity_function_type )( ::osg::Vec3 const & ) ;
Particle_exposer.def(
"addVelocity"
, addVelocity_function_type( &::osgParticle::Particle::addVelocity )
, ( bp::arg("dv") ) );
}
{ //::osgParticle::Particle::beginRender
typedef void ( ::osgParticle::Particle::*beginRender_function_type )( ::osg::GLBeginEndAdapter * ) const;
Particle_exposer.def(
"beginRender"
, beginRender_function_type( &::osgParticle::Particle::beginRender )
, ( bp::arg("gl") ) );
}
{ //::osgParticle::Particle::endRender
typedef void ( ::osgParticle::Particle::*endRender_function_type )( ::osg::GLBeginEndAdapter * ) const;
Particle_exposer.def(
"endRender"
, endRender_function_type( &::osgParticle::Particle::endRender )
, ( bp::arg("gl") ) );
}
{ //::osgParticle::Particle::getAge
typedef double ( ::osgParticle::Particle::*getAge_function_type )( ) const;
Particle_exposer.def(
"getAge"
, getAge_function_type( &::osgParticle::Particle::getAge ) );
}
{ //::osgParticle::Particle::getAlphaInterpolator
typedef ::osgParticle::Interpolator const * ( ::osgParticle::Particle::*getAlphaInterpolator_function_type )( ) const;
Particle_exposer.def(
"getAlphaInterpolator"
, getAlphaInterpolator_function_type( &::osgParticle::Particle::getAlphaInterpolator )
, bp::return_internal_reference< >() );
}
{ //::osgParticle::Particle::getAlphaRange
typedef ::osgParticle::rangef const & ( ::osgParticle::Particle::*getAlphaRange_function_type )( ) const;
Particle_exposer.def(
"getAlphaRange"
, getAlphaRange_function_type( &::osgParticle::Particle::getAlphaRange )
, bp::return_internal_reference< >() );
}
{ //::osgParticle::Particle::getAngle
typedef ::osg::Vec3 const & ( ::osgParticle::Particle::*getAngle_function_type )( ) const;
Particle_exposer.def(
"getAngle"
, getAngle_function_type( &::osgParticle::Particle::getAngle )
, bp::return_internal_reference< >() );
}
{ //::osgParticle::Particle::getAngularVelocity
typedef ::osg::Vec3 const & ( ::osgParticle::Particle::*getAngularVelocity_function_type )( ) const;
Particle_exposer.def(
"getAngularVelocity"
, getAngularVelocity_function_type( &::osgParticle::Particle::getAngularVelocity )
, bp::return_internal_reference< >() );
}
{ //::osgParticle::Particle::getColorInterpolator
typedef ::osgParticle::Interpolator const * ( ::osgParticle::Particle::*getColorInterpolator_function_type )( ) const;
Particle_exposer.def(
"getColorInterpolator"
, getColorInterpolator_function_type( &::osgParticle::Particle::getColorInterpolator )
, bp::return_internal_reference< >() );
}
{ //::osgParticle::Particle::getColorRange
typedef ::osgParticle::rangev4 const & ( ::osgParticle::Particle::*getColorRange_function_type )( ) const;
Particle_exposer.def(
"getColorRange"
, getColorRange_function_type( &::osgParticle::Particle::getColorRange )
, bp::return_internal_reference< >() );
}
{ //::osgParticle::Particle::getCurrentAlpha
typedef float ( ::osgParticle::Particle::*getCurrentAlpha_function_type )( ) const;
Particle_exposer.def(
"getCurrentAlpha"
, getCurrentAlpha_function_type( &::osgParticle::Particle::getCurrentAlpha )
, "\n Get the current alpha\n" );
}
{ //::osgParticle::Particle::getCurrentColor
typedef ::osg::Vec4 const & ( ::osgParticle::Particle::*getCurrentColor_function_type )( ) const;
Particle_exposer.def(
"getCurrentColor"
, getCurrentColor_function_type( &::osgParticle::Particle::getCurrentColor )
, bp::return_internal_reference< >()
, "\n Get the current color\n" );
}
{ //::osgParticle::Particle::getCurrentSize
typedef float ( ::osgParticle::Particle::*getCurrentSize_function_type )( ) const;
Particle_exposer.def(
"getCurrentSize"
, getCurrentSize_function_type( &::osgParticle::Particle::getCurrentSize ) );
}
{ //::osgParticle::Particle::getDepth
typedef double ( ::osgParticle::Particle::*getDepth_function_type )( ) const;
Particle_exposer.def(
"getDepth"
, getDepth_function_type( &::osgParticle::Particle::getDepth )
, "\n Get the depth of the particle\n" );
}
{ //::osgParticle::Particle::getDrawable
typedef ::osg::Drawable * ( ::osgParticle::Particle::*getDrawable_function_type )( ) const;
Particle_exposer.def(
"getDrawable"
, getDrawable_function_type( &::osgParticle::Particle::getDrawable )
, bp::return_internal_reference< >()
, "\n Get the user-defined particle drawable\n" );
}
{ //::osgParticle::Particle::getEndTile
typedef int ( ::osgParticle::Particle::*getEndTile_function_type )( ) const;
Particle_exposer.def(
"getEndTile"
, getEndTile_function_type( &::osgParticle::Particle::getEndTile ) );
}
{ //::osgParticle::Particle::getLifeTime
typedef double ( ::osgParticle::Particle::*getLifeTime_function_type )( ) const;
Particle_exposer.def(
"getLifeTime"
, getLifeTime_function_type( &::osgParticle::Particle::getLifeTime ) );
}
{ //::osgParticle::Particle::getMass
typedef float ( ::osgParticle::Particle::*getMass_function_type )( ) const;
Particle_exposer.def(
"getMass"
, getMass_function_type( &::osgParticle::Particle::getMass ) );
}
{ //::osgParticle::Particle::getMassInv
typedef float ( ::osgParticle::Particle::*getMassInv_function_type )( ) const;
Particle_exposer.def(
"getMassInv"
, getMassInv_function_type( &::osgParticle::Particle::getMassInv ) );
}
{ //::osgParticle::Particle::getNextParticle
typedef int ( ::osgParticle::Particle::*getNextParticle_function_type )( ) const;
Particle_exposer.def(
"getNextParticle"
, getNextParticle_function_type( &::osgParticle::Particle::getNextParticle )
, "\n Get the const next particle\n" );
}
{ //::osgParticle::Particle::getNumTiles
typedef int ( ::osgParticle::Particle::*getNumTiles_function_type )( ) const;
Particle_exposer.def(
"getNumTiles"
, getNumTiles_function_type( &::osgParticle::Particle::getNumTiles )
, "\n Get number of texture tiles\n" );
}
{ //::osgParticle::Particle::getPosition
typedef ::osg::Vec3 const & ( ::osgParticle::Particle::*getPosition_function_type )( ) const;
Particle_exposer.def(
"getPosition"
, getPosition_function_type( &::osgParticle::Particle::getPosition )
, bp::return_internal_reference< >() );
}
{ //::osgParticle::Particle::getPreviousAngle
typedef ::osg::Vec3 const & ( ::osgParticle::Particle::*getPreviousAngle_function_type )( ) const;
Particle_exposer.def(
"getPreviousAngle"
, getPreviousAngle_function_type( &::osgParticle::Particle::getPreviousAngle )
, bp::return_internal_reference< >() );
}
{ //::osgParticle::Particle::getPreviousParticle
typedef int ( ::osgParticle::Particle::*getPreviousParticle_function_type )( ) const;
Particle_exposer.def(
"getPreviousParticle"
, getPreviousParticle_function_type( &::osgParticle::Particle::getPreviousParticle )
, "\n Get the previous particle\n" );
}
{ //::osgParticle::Particle::getPreviousPosition
typedef ::osg::Vec3 const & ( ::osgParticle::Particle::*getPreviousPosition_function_type )( ) const;
Particle_exposer.def(
"getPreviousPosition"
, getPreviousPosition_function_type( &::osgParticle::Particle::getPreviousPosition )
, bp::return_internal_reference< >() );
}
{ //::osgParticle::Particle::getRadius
typedef float ( ::osgParticle::Particle::*getRadius_function_type )( ) const;
Particle_exposer.def(
"getRadius"
, getRadius_function_type( &::osgParticle::Particle::getRadius ) );
}
{ //::osgParticle::Particle::getSTexCoord
typedef float ( ::osgParticle::Particle::*getSTexCoord_function_type )( ) const;
Particle_exposer.def(
"getSTexCoord"
, getSTexCoord_function_type( &::osgParticle::Particle::getSTexCoord )
, "\n Get the s texture coordinate of the bottom left of the particle\n" );
}
{ //::osgParticle::Particle::getShape
typedef ::osgParticle::Particle::Shape ( ::osgParticle::Particle::*getShape_function_type )( ) const;
Particle_exposer.def(
"getShape"
, getShape_function_type( &::osgParticle::Particle::getShape ) );
}
{ //::osgParticle::Particle::getSizeInterpolator
typedef ::osgParticle::Interpolator const * ( ::osgParticle::Particle::*getSizeInterpolator_function_type )( ) const;
Particle_exposer.def(
"getSizeInterpolator"
, getSizeInterpolator_function_type( &::osgParticle::Particle::getSizeInterpolator )
, bp::return_internal_reference< >() );
}
{ //::osgParticle::Particle::getSizeRange
typedef ::osgParticle::rangef const & ( ::osgParticle::Particle::*getSizeRange_function_type )( ) const;
Particle_exposer.def(
"getSizeRange"
, getSizeRange_function_type( &::osgParticle::Particle::getSizeRange )
, bp::return_internal_reference< >() );
}
{ //::osgParticle::Particle::getStartTile
typedef int ( ::osgParticle::Particle::*getStartTile_function_type )( ) const;
Particle_exposer.def(
"getStartTile"
, getStartTile_function_type( &::osgParticle::Particle::getStartTile ) );
}
{ //::osgParticle::Particle::getTTexCoord
typedef float ( ::osgParticle::Particle::*getTTexCoord_function_type )( ) const;
Particle_exposer.def(
"getTTexCoord"
, getTTexCoord_function_type( &::osgParticle::Particle::getTTexCoord )
, "\n Get the t texture coordinate of the bottom left of the particle\n" );
}
{ //::osgParticle::Particle::getTileS
typedef int ( ::osgParticle::Particle::*getTileS_function_type )( ) const;
Particle_exposer.def(
"getTileS"
, getTileS_function_type( &::osgParticle::Particle::getTileS ) );
}
{ //::osgParticle::Particle::getTileT
typedef int ( ::osgParticle::Particle::*getTileT_function_type )( ) const;
Particle_exposer.def(
"getTileT"
, getTileT_function_type( &::osgParticle::Particle::getTileT ) );
}
{ //::osgParticle::Particle::getVelocity
typedef ::osg::Vec3 const & ( ::osgParticle::Particle::*getVelocity_function_type )( ) const;
Particle_exposer.def(
"getVelocity"
, getVelocity_function_type( &::osgParticle::Particle::getVelocity )
, bp::return_internal_reference< >() );
}
{ //::osgParticle::Particle::isAlive
typedef bool ( ::osgParticle::Particle::*isAlive_function_type )( ) const;
Particle_exposer.def(
"isAlive"
, isAlive_function_type( &::osgParticle::Particle::isAlive ) );
}
{ //::osgParticle::Particle::kill
typedef void ( ::osgParticle::Particle::*kill_function_type )( ) ;
Particle_exposer.def(
"kill"
, kill_function_type( &::osgParticle::Particle::kill ) );
}
Particle_exposer.def( bp::self < bp::self );
{ //::osgParticle::Particle::render
typedef void ( ::osgParticle::Particle::*render_function_type )( ::osg::GLBeginEndAdapter *,::osg::Vec3 const &,::osg::Vec3 const &,::osg::Vec3 const &,float ) const;
Particle_exposer.def(
"render"
, render_function_type( &::osgParticle::Particle::render )
, ( bp::arg("gl"), bp::arg("xpos"), bp::arg("px"), bp::arg("py"), bp::arg("scale")=1.0e+0f )
, "\n Render the particle. Called automatically by particle systems.\n" );
}
{ //::osgParticle::Particle::render
typedef void ( ::osgParticle::Particle::*render_function_type )( ::osg::RenderInfo &,::osg::Vec3 const &,::osg::Vec3 const & ) const;
Particle_exposer.def(
"render"
, render_function_type( &::osgParticle::Particle::render )
, ( bp::arg("renderInfo"), bp::arg("xpos"), bp::arg("xrot") )
, "\n Render the particle with user-defined drawable\n" );
}
{ //::osgParticle::Particle::setAlphaInterpolator
typedef void ( ::osgParticle::Particle::*setAlphaInterpolator_function_type )( ::osgParticle::Interpolator * ) ;
Particle_exposer.def(
"setAlphaInterpolator"
, setAlphaInterpolator_function_type( &::osgParticle::Particle::setAlphaInterpolator )
, ( bp::arg("ai") ) );
}
{ //::osgParticle::Particle::setAlphaRange
typedef void ( ::osgParticle::Particle::*setAlphaRange_function_type )( ::osgParticle::rangef const & ) ;
Particle_exposer.def(
"setAlphaRange"
, setAlphaRange_function_type( &::osgParticle::Particle::setAlphaRange )
, ( bp::arg("r") ) );
}
{ //::osgParticle::Particle::setAngle
typedef void ( ::osgParticle::Particle::*setAngle_function_type )( ::osg::Vec3 const & ) ;
Particle_exposer.def(
"setAngle"
, setAngle_function_type( &::osgParticle::Particle::setAngle )
, ( bp::arg("a") ) );
}
{ //::osgParticle::Particle::setAngularVelocity
typedef void ( ::osgParticle::Particle::*setAngularVelocity_function_type )( ::osg::Vec3 const & ) ;
Particle_exposer.def(
"setAngularVelocity"
, setAngularVelocity_function_type( &::osgParticle::Particle::setAngularVelocity )
, ( bp::arg("v") ) );
}
{ //::osgParticle::Particle::setColorInterpolator
typedef void ( ::osgParticle::Particle::*setColorInterpolator_function_type )( ::osgParticle::Interpolator * ) ;
Particle_exposer.def(
"setColorInterpolator"
, setColorInterpolator_function_type( &::osgParticle::Particle::setColorInterpolator )
, ( bp::arg("ci") ) );
}
{ //::osgParticle::Particle::setColorRange
typedef void ( ::osgParticle::Particle::*setColorRange_function_type )( ::osgParticle::rangev4 const & ) ;
Particle_exposer.def(
"setColorRange"
, setColorRange_function_type( &::osgParticle::Particle::setColorRange )
, ( bp::arg("r") ) );
}
{ //::osgParticle::Particle::setDepth
typedef void ( ::osgParticle::Particle::*setDepth_function_type )( double ) ;
Particle_exposer.def(
"setDepth"
, setDepth_function_type( &::osgParticle::Particle::setDepth )
, ( bp::arg("d") )
, "\n Set the depth of the particle\n" );
}
{ //::osgParticle::Particle::setDrawable
typedef void ( ::osgParticle::Particle::*setDrawable_function_type )( ::osg::Drawable * ) ;
Particle_exposer.def(
"setDrawable"
, setDrawable_function_type( &::osgParticle::Particle::setDrawable )
, ( bp::arg("d") )
, "\n Set the user-defined particle drawable\n" );
}
{ //::osgParticle::Particle::setLifeTime
typedef void ( ::osgParticle::Particle::*setLifeTime_function_type )( double ) ;
Particle_exposer.def(
"setLifeTime"
, setLifeTime_function_type( &::osgParticle::Particle::setLifeTime )
, ( bp::arg("t") ) );
}
{ //::osgParticle::Particle::setMass
typedef void ( ::osgParticle::Particle::*setMass_function_type )( float ) ;
Particle_exposer.def(
"setMass"
, setMass_function_type( &::osgParticle::Particle::setMass )
, ( bp::arg("m") ) );
}
{ //::osgParticle::Particle::setNextParticle
typedef void ( ::osgParticle::Particle::*setNextParticle_function_type )( int ) ;
Particle_exposer.def(
"setNextParticle"
, setNextParticle_function_type( &::osgParticle::Particle::setNextParticle )
, ( bp::arg("next") )
, "\n Set the next particle\n" );
}
{ //::osgParticle::Particle::setPosition
typedef void ( ::osgParticle::Particle::*setPosition_function_type )( ::osg::Vec3 const & ) ;
Particle_exposer.def(
"setPosition"
, setPosition_function_type( &::osgParticle::Particle::setPosition )
, ( bp::arg("p") ) );
}
{ //::osgParticle::Particle::setPreviousParticle
typedef void ( ::osgParticle::Particle::*setPreviousParticle_function_type )( int ) ;
Particle_exposer.def(
"setPreviousParticle"
, setPreviousParticle_function_type( &::osgParticle::Particle::setPreviousParticle )
, ( bp::arg("previous") )
, "\n Set the previous particle\n" );
}
{ //::osgParticle::Particle::setRadius
typedef void ( ::osgParticle::Particle::*setRadius_function_type )( float ) ;
Particle_exposer.def(
"setRadius"
, setRadius_function_type( &::osgParticle::Particle::setRadius )
, ( bp::arg("r") ) );
}
{ //::osgParticle::Particle::setShape
typedef void ( ::osgParticle::Particle::*setShape_function_type )( ::osgParticle::Particle::Shape ) ;
Particle_exposer.def(
"setShape"
, setShape_function_type( &::osgParticle::Particle::setShape )
, ( bp::arg("s") ) );
}
{ //::osgParticle::Particle::setSizeInterpolator
typedef void ( ::osgParticle::Particle::*setSizeInterpolator_function_type )( ::osgParticle::Interpolator * ) ;
Particle_exposer.def(
"setSizeInterpolator"
, setSizeInterpolator_function_type( &::osgParticle::Particle::setSizeInterpolator )
, ( bp::arg("ri") ) );
}
{ //::osgParticle::Particle::setSizeRange
typedef void ( ::osgParticle::Particle::*setSizeRange_function_type )( ::osgParticle::rangef const & ) ;
Particle_exposer.def(
"setSizeRange"
, setSizeRange_function_type( &::osgParticle::Particle::setSizeRange )
, ( bp::arg("r") ) );
}
{ //::osgParticle::Particle::setTextureTile
typedef void ( ::osgParticle::Particle::*setTextureTile_function_type )( int,int,int ) ;
Particle_exposer.def(
"setTextureTile"
, setTextureTile_function_type( &::osgParticle::Particle::setTextureTile )
, ( bp::arg("sTile"), bp::arg("tTile"), bp::arg("end")=(int)(-0x00000000000000001) ) );
}
{ //::osgParticle::Particle::setTextureTileRange
typedef void ( ::osgParticle::Particle::*setTextureTileRange_function_type )( int,int,int,int ) ;
Particle_exposer.def(
"setTextureTileRange"
, setTextureTileRange_function_type( &::osgParticle::Particle::setTextureTileRange )
, ( bp::arg("sTile"), bp::arg("tTile"), bp::arg("startTile"), bp::arg("endTile") ) );
}
{ //::osgParticle::Particle::setUpTexCoordsAsPartOfConnectedParticleSystem
typedef void ( ::osgParticle::Particle::*setUpTexCoordsAsPartOfConnectedParticleSystem_function_type )( ::osgParticle::ParticleSystem * ) ;
Particle_exposer.def(
"setUpTexCoordsAsPartOfConnectedParticleSystem"
, setUpTexCoordsAsPartOfConnectedParticleSystem_function_type( &::osgParticle::Particle::setUpTexCoordsAsPartOfConnectedParticleSystem )
, ( bp::arg("ps") )
, "\n Method for initializing a particles texture coords as part of a connected particle system.\n" );
}
{ //::osgParticle::Particle::setVelocity
typedef void ( ::osgParticle::Particle::*setVelocity_function_type )( ::osg::Vec3 const & ) ;
Particle_exposer.def(
"setVelocity"
, setVelocity_function_type( &::osgParticle::Particle::setVelocity )
, ( bp::arg("v") ) );
}
{ //::osgParticle::Particle::transformAngleVelocity
typedef void ( ::osgParticle::Particle::*transformAngleVelocity_function_type )( ::osg::Matrix const & ) ;
Particle_exposer.def(
"transformAngleVelocity"
, transformAngleVelocity_function_type( &::osgParticle::Particle::transformAngleVelocity )
, ( bp::arg("xform") ) );
}
{ //::osgParticle::Particle::transformPositionVelocity
typedef void ( ::osgParticle::Particle::*transformPositionVelocity_function_type )( ::osg::Matrix const & ) ;
Particle_exposer.def(
"transformPositionVelocity"
, transformPositionVelocity_function_type( &::osgParticle::Particle::transformPositionVelocity )
, ( bp::arg("xform") ) );
}
{ //::osgParticle::Particle::transformPositionVelocity
typedef void ( ::osgParticle::Particle::*transformPositionVelocity_function_type )( ::osg::Matrix const &,::osg::Matrix const &,float ) ;
Particle_exposer.def(
"transformPositionVelocity"
, transformPositionVelocity_function_type( &::osgParticle::Particle::transformPositionVelocity )
, ( bp::arg("xform1"), bp::arg("xform2"), bp::arg("r") ) );
}
{ //::osgParticle::Particle::update
typedef bool ( ::osgParticle::Particle::*update_function_type )( double,bool ) ;
Particle_exposer.def(
"update"
, update_function_type( &::osgParticle::Particle::update )
, ( bp::arg("dt"), bp::arg("onlyTimeStamp") )
, "\n Update the particle (dont call this method manually).\n This method is called automatically by <CODE>ParticleSystem::update()</CODE>; it\n updates the graphical properties of the particle for the current time,\n checks whether the particle is still alive, and then updates its position\n by computing <I>P = P + V * dt</I> (where <I>P</I> is the position and <I>V</I> is the velocity).\n" );
}
}
}
| 43.119822 | 1,098 | 0.539229 | [
"render",
"shape"
] |
25e0dbe7da29a9b73734fcc0c40a7a8a8e769f36 | 194 | cpp | C++ | training-olinfo/galattici/main.cpp | GabrieleRolleri/competitive_programming | 8459e5045a16e01aa28248614ef9b88c7bae2ac0 | [
"MIT"
] | null | null | null | training-olinfo/galattici/main.cpp | GabrieleRolleri/competitive_programming | 8459e5045a16e01aa28248614ef9b88c7bae2ac0 | [
"MIT"
] | null | null | null | training-olinfo/galattici/main.cpp | GabrieleRolleri/competitive_programming | 8459e5045a16e01aa28248614ef9b88c7bae2ac0 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
int main(){
int M, N, K;
cin>>M>>N>>K;
string S;
vector<char> S(K);
for(int i=0; i<K; ++i){
}
return 0;
} | 7.461538 | 27 | 0.458763 | [
"vector"
] |
25e10f3a1025350d66d13913aa9e5d728e60f740 | 2,252 | cpp | C++ | Barracks.cpp | dianabacon/stalag-escape | 445085f1d95bec4190f29d72843bf4878d8f45ac | [
"MIT"
] | null | null | null | Barracks.cpp | dianabacon/stalag-escape | 445085f1d95bec4190f29d72843bf4878d8f45ac | [
"MIT"
] | null | null | null | Barracks.cpp | dianabacon/stalag-escape | 445085f1d95bec4190f29d72843bf4878d8f45ac | [
"MIT"
] | null | null | null | /*********************************************************************
** Program Filename: Barracks.cpp
** Author: Diana Bacon
** Date: 2015-11-28
** Description: Implementation of the Barracks class. Functions
** related to the derived class for Barracks spaces.
*********************************************************************/
#include "Barracks.hpp"
/*********************************************************************
** Function: Barracks
** Description: Default constructor for the Barracks class.
** Parameters: None.
** Pre-Conditions: None.
** Post-Conditions: A Barracks object will be created. The items
** container is given a name and some items are added.
*********************************************************************/
Barracks::Barracks()
{
items->setName("Monopoly Game");
items->add("silk map", false);
items->add("monopoly money", false);
items->add("race car", false);
items->add("plastic houses", false);
lightOn = false;
}
/*********************************************************************
** Function: enter
** Description: Controls entry into a Barracks space.
** Parameters: A pointer to an Airman object.
** Pre-Conditions: A Barracks object must exist.
** Post-Conditions: The light will be turned on (true) or off (false).
*********************************************************************/
bool Barracks::enter(Airman *myAirman)
{
std::cout << std::endl << "You are in " << getName() << std::endl;
char choice = ' ';
if (lightOn) {
std::cout << "The light is on." << std::endl;
std::cout << "Do you want to turn it off (y or n)?";
std::cin >> choice;
std::cin.clear();
std::cin.ignore(256, '\n');
if (choice == 'y') {
lightOn = false;
return false;
} else {
return true;
}
} else {
std::cout << "The light is off." << std::endl;
std::cout << "Do you want to turn it on (y or n)? ";
std::cin >> choice;
std::cin.clear();
std::cin.ignore(256, '\n');
if (choice == 'y') {
lightOn = true;
return true;
} else {
return false;
}
}
} | 34.121212 | 72 | 0.463588 | [
"object"
] |
25e65851eaf068bb1fbca9742ea47fe6308b680e | 1,690 | cc | C++ | dadt/internal/executor/nccl_coo_all_reduce_executor.cc | amazingyyc/DADT | da6cf2c15923d2be6a10d2c5ece95ff6a6f98ebc | [
"MIT"
] | 5 | 2019-08-30T11:13:33.000Z | 2022-03-26T03:11:10.000Z | dadt/internal/executor/nccl_coo_all_reduce_executor.cc | amazingyyc/DADT | da6cf2c15923d2be6a10d2c5ece95ff6a6f98ebc | [
"MIT"
] | null | null | null | dadt/internal/executor/nccl_coo_all_reduce_executor.cc | amazingyyc/DADT | da6cf2c15923d2be6a10d2c5ece95ff6a6f98ebc | [
"MIT"
] | null | null | null | #include "executor/nccl_coo_all_reduce_executor.h"
#include "common/exception.h"
namespace dadt {
NCCLCooAllReduceExecutor::NCCLCooAllReduceExecutor() {
CUDA_CALL(cudaEventCreate(&finish_event_));
}
NCCLCooAllReduceExecutor::~NCCLCooAllReduceExecutor() {
cudaEventDestroy(finish_event_);
}
Tensor NCCLCooAllReduceExecutor::DoImpl(const Context& context,
const Tensor& coo_t) {
Shape shape = coo_t.shape();
// indices shape:(nnz, sparse_dim)
// values shape: (nnz,) + coo_t.shape[M : M + K]
// Concate with other rank shape: (new_nnz, M)
Tensor new_indices = NcclAllGatherAndCatTensor(context, coo_t.indices());
// Concate values, shape: (new_nnz, coo_t.shape[M : M + K])
Tensor new_values = NcclAllGatherAndCatTensor(context, coo_t.values());
// Create a new Coo tensor.
return Tensor::CooTensor(new_indices, new_values, shape, false);
}
void NCCLCooAllReduceExecutor::Do(const Context& context,
const std::vector<Task>& tasks) {
if (tasks.empty()) {
return;
}
for (const auto& task : tasks) {
if (task.before) {
task.before();
}
const Tensor& coo_t = task.l_tensor->tensor();
ARGUMENT_CHECK(
coo_t.IsCoo() && coo_t.IsCuda() && coo_t.is_coalesced(),
"MPICooAllReduce need tensor is Coo, GPU and must be coalesced");
Tensor new_coo_t = DoImpl(context, coo_t);
task.l_tensor->ResetTensor(new_coo_t);
// Wait all reduce finish
CUDA_CALL(cudaEventRecord(finish_event_, context.cuda_stream));
CUDA_CALL(cudaEventSynchronize(finish_event_));
if (task.done) {
task.done();
}
}
}
} // namespace dadt
| 26.825397 | 75 | 0.668047 | [
"shape",
"vector"
] |
25e8d8da5c5b1f31cdc035b439da16997e564275 | 1,295 | cpp | C++ | codeBase/HackerRank/Algorithms/Dynamic Programming/Bricks Game/Solution.cpp | suren3141/codeBase | 10ed9a56aca33631dc8c419cd83859c19dd6ff09 | [
"Apache-2.0"
] | 3 | 2020-03-16T14:59:08.000Z | 2021-07-28T20:51:53.000Z | codeBase/HackerRank/Algorithms/Dynamic Programming/Bricks Game/Solution.cpp | suren3141/codeBase | 10ed9a56aca33631dc8c419cd83859c19dd6ff09 | [
"Apache-2.0"
] | 1 | 2020-03-15T10:57:02.000Z | 2020-03-15T10:57:02.000Z | codeBase/HackerRank/Algorithms/Dynamic Programming/Bricks Game/Solution.cpp | killerilaksha/codeBase | 91cbd950fc90066903e58311000784aeba4ffc02 | [
"Apache-2.0"
] | 18 | 2020-02-17T23:17:37.000Z | 2021-07-28T20:52:13.000Z | /*
Copyright (C) 2020, Sathira Silva.
Problem Statement: You and your friend decide to play a game using a stack consisting of N bricks. In this game, you can
alternatively remove 1, 2 or 3 bricks from the top, and the numbers etched on the removed bricks are
added to your score. You have to play so that you obtain the maximum possible score. It is given that your
friend will also play optimally and you make the first move.
*/
#include <bits/stdc++.h>
#include <numeric>
using namespace std;
vector<string> split_string(string);
long long bricksGame(vector<int> arr) {
int n = arr.size();
long long score[n];
if (arr.size() <= 3)
return accumulate(arr.begin(), arr.end(), 0);
// Base Cases:
score[n - 1] = arr[n - 1];
score[n - 2] = score[n - 1] + arr[n - 2];
score[n - 3] = score[n - 2] + arr[n - 3];
long long sum = score[n - 3];
// Build the optimal solution using the optimal solutions of it's subproblems.
// Traverse the array backwards and get the cumulative sum at each state.
for (int i = n - 4; i >= 0; i--) {
sum += arr[i];
score[i] = sum - min({score[i + 1], score[i + 2], score[i + 3]});
}
return score[0];
}
| 37 | 131 | 0.593822 | [
"vector"
] |
25efd61f7a23fe685167b8e9073e39a9dd397e78 | 4,352 | cpp | C++ | core/animated_vector.cpp | ppearson/ImaginePartial | 9871b052f2edeb023e2845578ad69c25c5baf7d2 | [
"Apache-2.0"
] | 1 | 2018-07-10T13:36:38.000Z | 2018-07-10T13:36:38.000Z | core/animated_vector.cpp | ppearson/ImaginePartial | 9871b052f2edeb023e2845578ad69c25c5baf7d2 | [
"Apache-2.0"
] | null | null | null | core/animated_vector.cpp | ppearson/ImaginePartial | 9871b052f2edeb023e2845578ad69c25c5baf7d2 | [
"Apache-2.0"
] | null | null | null | /*
Imagine
Copyright 2011-2012 Peter Pearson.
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 "animated_vector.h"
#include "output_context.h"
namespace Imagine
{
AnimatedVector::AnimatedVector()
{
}
Vector AnimatedVector::getVector() const
{
float time = OutputContext::instance().getFrame();
float xVal = x.getValue(time);
float yVal = y.getValue(time);
float zVal = z.getValue(time);
Vector newVector(xVal, yVal, zVal);
return newVector;
}
Vector AnimatedVector::getVectorAt(float time) const
{
float xVal = x.getValue(time);
float yVal = y.getValue(time);
float zVal = z.getValue(time);
Vector newVector(xVal, yVal, zVal);
return newVector;
}
void AnimatedVector::setFromVector(const Vector& vector)
{
float time = OutputContext::instance().getFrame();
x.setValue(vector.x, time);
y.setValue(vector.y, time);
z.setValue(vector.z, time);
}
void AnimatedVector::setFromVectorAt(const Vector& vector, float time)
{
x.setValue(vector.x, time);
y.setValue(vector.y, time);
z.setValue(vector.z, time);
}
void AnimatedVector::add(const Vector& vector)
{
float time = OutputContext::instance().getFrame();
float curX = x.getValue(time);
float curY = y.getValue(time);
float curZ = z.getValue(time);
x.setValue(curX + vector.x, time);
y.setValue(curY + vector.y, time);
z.setValue(curZ + vector.z, time);
}
void AnimatedVector::addValues(float xVal, float yVal, float zVal)
{
float time = OutputContext::instance().getFrame();
float curX = x.getValue(time);
float curY = y.getValue(time);
float curZ = z.getValue(time);
x.setValue(curX + xVal, time);
y.setValue(curY + yVal, time);
z.setValue(curZ + zVal, time);
}
bool AnimatedVector::isAnimated() const
{
// for the moment, all curves have to be animated together
return x.isAnimated();
}
void AnimatedVector::setAllAnimated(bool animated)
{
x.setAnimated(animated);
y.setAnimated(animated);
z.setAnimated(animated);
}
bool AnimatedVector::isKeyed() const
{
// for the moment, all curves have to be keyed together
return x.isKey();
}
void AnimatedVector::setKey()
{
float time = OutputContext::instance().getFrame();
x.setKey(time);
y.setKey(time);
z.setKey(time);
}
void AnimatedVector::setKey(float time)
{
x.setKey(time);
y.setKey(time);
z.setKey(time);
}
void AnimatedVector::deleteKey()
{
float time = OutputContext::instance().getFrame();
x.deleteKey(time);
y.deleteKey(time);
z.deleteKey(time);
}
AnimationCurve::CurveInterpolationType AnimatedVector::getInterpolationType() const
{
// currently, they're all the same
return x.getInterpolationType();
}
void AnimatedVector::setInterpolationType(AnimationCurve::CurveInterpolationType type)
{
x.setInterpolationType(type);
y.setInterpolationType(type);
z.setInterpolationType(type);
}
void AnimatedVector::load(Stream* stream, unsigned int version)
{
x.load(stream, version);
y.load(stream, version);
z.load(stream, version);
}
void AnimatedVector::store(Stream* stream) const
{
x.store(stream);
y.store(stream);
z.store(stream);
}
void AnimatedVector::loadNonAnimated(Stream* stream, unsigned int version)
{
float xVal;
float yVal;
float zVal;
stream->loadFloat(xVal);
stream->loadFloat(yVal);
stream->loadFloat(zVal);
x.setValue(xVal);
y.setValue(yVal);
z.setValue(zVal);
}
void AnimatedVector::storeNonAnimated(Stream* stream) const
{
float xVal = x.getValue();
float yVal = y.getValue();
float zVal = z.getValue();
stream->storeFloat(xVal);
stream->storeFloat(yVal);
stream->storeFloat(zVal);
}
bool AnimatedVector::isNull() const
{
// if we're animated, we're not zero, as keys have been set
if (isAnimated())
return false;
// get constant values, and check if they're 0.0f
bool constantIsZero = (x.getValue() == 0.0f && y.getValue() == 0.0f && z.getValue() == 0.0f);
return constantIsZero;
}
} // namespace Imagine
| 21.333333 | 94 | 0.725643 | [
"vector"
] |
25f298d46c7367dd24ecd58f8d1131c8ffe2650e | 8,228 | cpp | C++ | docs/template_plugin/tests/functional/op_reference/einsum.cpp | ivkalgin/openvino | 81685c8d212135dd9980da86a18db41fbf6d250a | [
"Apache-2.0"
] | null | null | null | docs/template_plugin/tests/functional/op_reference/einsum.cpp | ivkalgin/openvino | 81685c8d212135dd9980da86a18db41fbf6d250a | [
"Apache-2.0"
] | 18 | 2022-01-21T08:42:58.000Z | 2022-03-28T13:21:31.000Z | docs/template_plugin/tests/functional/op_reference/einsum.cpp | ematroso/openvino | 403339f8f470c90dee6f6d94ed58644b2787f66b | [
"Apache-2.0"
] | null | null | null | // Copyright (C) 2018-2022 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include <gtest/gtest.h>
#include "openvino/opsets/opset7.hpp"
#include "openvino/opsets/opset1.hpp"
#include "base_reference_test.hpp"
using namespace reference_tests;
using namespace ov;
namespace {
struct EinsumParams {
std::vector<Tensor> inputs;
std::string equation;
Tensor expectedResult;
std::string testcaseName;
};
struct Builder : ParamsBuilder<EinsumParams> {
REFERENCE_TESTS_ADD_SET_PARAM(Builder, inputs);
REFERENCE_TESTS_ADD_SET_PARAM(Builder, equation);
REFERENCE_TESTS_ADD_SET_PARAM(Builder, expectedResult);
REFERENCE_TESTS_ADD_SET_PARAM(Builder, testcaseName);
};
class ReferenceEinsumTest : public testing::TestWithParam<EinsumParams>, public CommonReferenceTest {
public:
void SetUp() override {
auto params = GetParam();
function = CreateModel(params);
for (const auto& input_tensor : params.inputs) {
inputData.push_back(input_tensor.data);
}
refOutData = {params.expectedResult.data};
}
static std::string getTestCaseName(const testing::TestParamInfo<EinsumParams>& obj) {
auto param = obj.param;
std::ostringstream result;
result << "iType=" << param.inputs[0].type;
result << "_iShape=" << param.inputs[0].shape;
result << "_equation=" << param.equation;
result << "_eType=" << param.expectedResult.type;
result << "_eShape=" << param.expectedResult.shape;
if (param.testcaseName != "") {
result << "_=" << param.testcaseName;
}
return result.str();
}
private:
static std::shared_ptr<Model> CreateModel(const EinsumParams& params) {
OutputVector output_vector;
ParameterVector param_vector;
for (const auto& input_tensor : params.inputs) {
auto param = std::make_shared<opset1::Parameter>(input_tensor.type, input_tensor.shape);
output_vector.push_back(param);
param_vector.push_back(param);
}
const auto einsum = std::make_shared<opset7::Einsum>(output_vector, params.equation);
const auto f = std::make_shared<Model>(OutputVector{einsum}, param_vector);
return f;
}
};
TEST_P(ReferenceEinsumTest, CompareWithRefs) {
Exec();
}
template <element::Type_t ET>
std::vector<EinsumParams> generateParams() {
using T = typename element_type_traits<ET>::value_type;
std::vector<EinsumParams> params {
Builder {}
.inputs({{ET, {1, 2}, std::vector<T>{1, 2}},
{ET, {3, 4}, std::vector<T>{3, 4, 5, 6,
7, 8, 9, 10,
11, 12, 13, 14}}})
.equation("ab,cd->abcd")
.expectedResult({ET, {1, 2, 3, 4}, std::vector<T>{3, 4, 5, 6, 7, 8, 9, 10,
11, 12, 13, 14, 6, 8, 10, 12,
14, 16, 18, 20, 22, 24, 26, 28}})
.testcaseName("einsum_no_reduction"),
Builder {}
.inputs({{ET, {1, 2, 3}, std::vector<T>{1, 2, 3, 4, 5, 6}}})
.equation("ijk->kij")
.expectedResult({ET, {3, 1, 2}, std::vector<T>{1, 4, 2, 5, 3, 6}})
.testcaseName("einsum_transpose"),
Builder {}
.inputs({{ET, {2, 3}, std::vector<T>{1, 2, 3, 4, 5, 6}}})
.equation("ab->a")
.expectedResult({ET, {2}, std::vector<T>{6, 15}})
.testcaseName("einsum_reduce"),
Builder {}
.inputs({{ET, {2, 3}, std::vector<T>{1, 2, 3, 4, 5, 6}},
{ET, {3, 2}, std::vector<T>{1, 2, 3, 4, 5, 6}}})
.equation("ab,bc->ac")
.expectedResult({ET, {2, 2}, std::vector<T>{22, 28, 49, 64}})
.testcaseName("einsum_matrix_multiplication"),
Builder {}
.inputs({{ET, {2, 4}, std::vector<T>{1, 3, 2, 7, 5, 6, 0, 1}},
{ET, {4, 3, 1}, std::vector<T>{1, 2, 3, 4, 5, 6, 5, 7, 3, 7, 9, 1}},
{ET, {4, 3}, std::vector<T>{4, 3, 1, 6, 4, 2, 2, 5, 3, 1, 9, 4}}})
.equation("ab,bcd,bc->ca")
.expectedResult({ET, {3, 2}, std::vector<T>{145, 171, 703, 231, 85, 91}})
.testcaseName("einsum_multiple_multiplication"),
Builder {}
.inputs({{ET, {2, 2, 3}, std::vector<T>{1, 3, 2, 7, 5, 6, 3, 5, 2, 1, 0, 7}}})
.equation("a...->...")
.expectedResult({ET, {2, 3}, std::vector<T>{4, 8, 4, 8, 5, 13}})
.testcaseName("einsum_ellipsis_one_input_reduction"),
Builder {}
.inputs({{ET, {2, 2, 3}, std::vector<T>{1, 3, 2, 7, 5, 6, 3, 5, 2, 1, 0, 7}}})
.equation("a...->...a")
.expectedResult({ET, {2, 3, 2}, std::vector<T>{1, 3, 3, 5, 2, 2, 7, 1, 5, 0, 6, 7}})
.testcaseName("einsum_ellipsis_one_input_transpose"),
Builder {}
.inputs({{ET, {2, 2, 3}, std::vector<T>{1, 3, 2, 7, 5, 6, 3, 5, 2, 1, 0, 7}},
{ET, {1}, std::vector<T>{2}}})
.equation("ab...,...->ab...")
.expectedResult({ET, {2, 2, 3}, std::vector<T>{2, 6, 4, 14, 10, 12, 6, 10, 4, 2, 0, 14}})
.testcaseName("einsum_ellipsis_mul_by_1dscalar"),
Builder {}
.inputs({{ET, {1, 1, 4, 3}, std::vector<T>{1, 3, 2, 7, 5, 6, 3, 5, 2, 1, 0, 7}},
{ET, {3, 4, 2, 1}, std::vector<T>{3, 1, 6, 2, 3, 10, 9, 8, 2, 9, 3, 2,
4, 2, 3, 1, 9, 1, 11, 4, 7, 2, 3, 1}}})
.equation("a...j,j...->a...")
.expectedResult({ET, {1, 4, 2, 4}, std::vector<T>{27, 85, 37, 66, 30, 58, 50, 8,
37, 123, 55, 83, 16, 48, 24, 30,
29, 83, 43, 52, 20, 92, 44, 24,
24, 96, 48, 30, 13, 67, 31, 15}})
.testcaseName("einsum_ellipsis_complex_mul"),
Builder {}
.inputs({{ET, {1, 3, 3}, std::vector<T>{1, 2, 3, 4, 5, 6, 7, 8, 9}}})
.equation("kii->ki")
.expectedResult({ET, {1, 3}, std::vector<T>{1, 5, 9}})
.testcaseName("einsum_diagonal"),
Builder {}
.inputs({{ET, {2, 3, 3, 2, 4}, std::vector<T>{4, 2, 5, 4, 5, 5, 1, 1, 3, 3, 1, 1, 2, 2, 4, 1, 3, 4,
4, 5, 1, 3, 1, 3, 1, 4, 3, 5, 4, 4, 5, 4, 4, 5, 4, 2,
2, 2, 3, 3, 1, 1, 4, 3, 4, 2, 2, 1, 1, 2, 3, 1, 1, 4,
2, 3, 1, 3, 4, 2, 5, 5, 3, 4, 3, 4, 5, 4, 4, 5, 1, 3,
4, 4, 5, 3, 1, 3, 2, 5, 3, 2, 5, 4, 4, 2, 4, 4, 1, 4,
4, 5, 4, 4, 4, 2, 3, 3, 4, 2, 4, 2, 5, 1, 3, 2, 4, 3,
5, 1, 2, 3, 1, 1, 2, 5, 1, 1, 2, 1, 4, 5, 3, 4, 1, 3,
3, 1, 3, 2, 4, 5, 1, 1, 5, 4, 5, 2, 2, 3, 3, 1, 2, 4}},
{ET, {3, 2, 1}, std::vector<T>{1, 4, 4, 5, 3, 3}}})
.equation("abbac,bad->ad")
.expectedResult({ET, {2, 1}, std::vector<T>{123, 129}})
.testcaseName("einsum_diagonal_with_matmul"),
};
return params;
}
std::vector<EinsumParams> generateCombinedParams() {
const std::vector<std::vector<EinsumParams>> generatedParams {
generateParams<element::Type_t::i32>(),
generateParams<element::Type_t::f32>(),
};
std::vector<EinsumParams> combinedParams;
for (const auto& params : generatedParams) {
combinedParams.insert(combinedParams.end(), params.begin(), params.end());
}
return combinedParams;
}
INSTANTIATE_TEST_SUITE_P(smoke_Einsum_With_Hardcoded_Refs, ReferenceEinsumTest,
testing::ValuesIn(generateCombinedParams()), ReferenceEinsumTest::getTestCaseName);
} // namespace
| 44.961749 | 113 | 0.478853 | [
"shape",
"vector",
"model"
] |
25f647d73e1dee31c9eab2d23bc39cc34f0458a3 | 16,598 | cpp | C++ | src/slib/network/network_async.cpp | inogroup/SLib | 6c053c8f47f04240b8444eac5f316effdee2eb01 | [
"MIT"
] | null | null | null | src/slib/network/network_async.cpp | inogroup/SLib | 6c053c8f47f04240b8444eac5f316effdee2eb01 | [
"MIT"
] | null | null | null | src/slib/network/network_async.cpp | inogroup/SLib | 6c053c8f47f04240b8444eac5f316effdee2eb01 | [
"MIT"
] | null | null | null | /*
* Copyright (c) 2008-2021 SLIBIO <https://github.com/SLIBIO>
*
* 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 "slib/network/async.h"
#include "network_async.h"
#include "slib/core/handle_ptr.h"
namespace slib
{
SLIB_DEFINE_OBJECT(AsyncTcpSocketInstance, AsyncStreamInstance)
AsyncTcpSocketInstance::AsyncTcpSocketInstance()
{
m_flagRequestConnect = sl_false;
m_flagSupportingConnect = sl_true;
}
AsyncTcpSocketInstance::~AsyncTcpSocketInstance()
{
_free();
}
sl_socket AsyncTcpSocketInstance::getSocket()
{
return (sl_socket)(getHandle());
}
sl_bool AsyncTcpSocketInstance::isSupportedConnect()
{
return m_flagSupportingConnect;
}
sl_bool AsyncTcpSocketInstance::connect(const SocketAddress& address)
{
m_flagRequestConnect = sl_true;
m_addressRequestConnect = address;
return sl_true;
}
void AsyncTcpSocketInstance::onClose()
{
_free();
AsyncStreamInstance::onClose();
}
void AsyncTcpSocketInstance::_free()
{
if (m_requestReading.isNotNull()) {
processStreamResult(m_requestReading.get(), 0, AsyncStreamResultCode::Closed);
m_requestReading.setNull();
}
if (m_requestWriting.isNotNull()) {
processStreamResult(m_requestWriting.get(), 0, AsyncStreamResultCode::Closed);
m_requestWriting.setNull();
}
sl_socket socket = getSocket();
if (socket != SLIB_SOCKET_INVALID_HANDLE) {
Socket::close(socket);
setHandle(SLIB_ASYNC_INVALID_HANDLE);
}
}
void AsyncTcpSocketInstance::_onConnect(sl_bool flagError)
{
Ref<AsyncTcpSocket> object = Ref<AsyncTcpSocket>::from(getObject());
if (object.isNotNull()) {
object->_onConnect(flagError);
}
}
SLIB_DEFINE_MOVEONLY_CLASS_DEFAULT_MEMBERS(AsyncTcpSocketParam)
AsyncTcpSocketParam::AsyncTcpSocketParam()
{
flagIPv6 = sl_false;
flagLogError = sl_true;
}
SLIB_DEFINE_OBJECT(AsyncTcpSocket, AsyncStreamBase)
AsyncTcpSocket::AsyncTcpSocket()
{
}
AsyncTcpSocket::~AsyncTcpSocket()
{
if (m_onConnect.isNotNull()) {
m_onConnect(sl_null, sl_false);
}
}
Ref<AsyncTcpSocket> AsyncTcpSocket::create(AsyncTcpSocketParam& param)
{
sl_bool flagIPv6 = param.flagIPv6;
Socket& socket = param.socket;
if (socket.isNone()) {
if (param.bindAddress.ip.isIPv6()) {
flagIPv6 = sl_true;
}
if (flagIPv6) {
socket = Socket::openTcp_IPv6();
} else {
socket = Socket::openTcp();
}
if (socket.isNone()) {
return sl_null;
}
if (param.bindAddress.ip.isNotNone() || param.bindAddress.port != 0) {
if (!(socket.bind(param.bindAddress))) {
if (param.flagLogError) {
LogError(TAG, "AsyncTcpSocket bind error: %s, %s", param.bindAddress.toString(), Socket::getLastErrorMessage());
}
return sl_null;
}
}
}
Ref<AsyncTcpSocketInstance> instance = _createInstance(Move(socket), flagIPv6);
if (instance.isNotNull()) {
Ref<AsyncIoLoop> loop = param.ioLoop;
if (loop.isNull()) {
loop = AsyncIoLoop::getDefault();
if (loop.isNull()) {
return sl_null;
}
}
Ref<AsyncTcpSocket> ret = new AsyncTcpSocket;
if (ret.isNotNull()) {
if (ret->_initialize(instance.get(), AsyncIoMode::InOut, loop)) {
return ret;
}
}
}
return sl_null;
}
sl_socket AsyncTcpSocket::getSocket()
{
Ref<AsyncTcpSocketInstance> instance = _getIoInstance();
if (instance.isNotNull()) {
return instance->getSocket();
}
return SLIB_SOCKET_INVALID_HANDLE;
}
sl_bool AsyncTcpSocket::connect(const SocketAddress& address, const Function<void(AsyncTcpSocket*, sl_bool flagError)>& callback)
{
Ref<AsyncIoLoop> loop = getIoLoop();
if (loop.isNull()) {
return sl_false;
}
if (address.isInvalid()) {
return sl_false;
}
Ref<AsyncTcpSocketInstance> instance = _getIoInstance();
if (instance.isNotNull()) {
HandlePtr<Socket> socket(instance->getSocket());
if (socket->isOpened()) {
if (m_onConnect.isNotNull()) {
m_onConnect(this, sl_false);
}
m_onConnect = callback;
if (instance->isSupportedConnect()) {
if (instance->connect(address)) {
loop->requestOrder(instance.get());
return sl_true;
}
} else {
if (socket->connectAndWait(address)) {
_onConnect(sl_true);
return sl_true;
} else {
_onConnect(sl_false);
}
}
}
}
return sl_false;
}
sl_bool AsyncTcpSocket::receive(void* data, sl_size size, const Function<void(AsyncStreamResult&)>& callback, Referable* userObject)
{
return AsyncStreamBase::read(data, size, callback, userObject);
}
sl_bool AsyncTcpSocket::receive(const Memory& mem, const Function<void(AsyncStreamResult&)>& callback)
{
return AsyncStreamBase::read(mem.getData(), mem.getSize(), callback, mem.ref.get());
}
sl_bool AsyncTcpSocket::send(void* data, sl_size size, const Function<void(AsyncStreamResult&)>& callback, Referable* userObject)
{
return AsyncStreamBase::write(data, size, callback, userObject);
}
sl_bool AsyncTcpSocket::send(const Memory& mem, const Function<void(AsyncStreamResult&)>& callback)
{
return AsyncStreamBase::write(mem.getData(), mem.getSize(), callback, mem.ref.get());
}
Ref<AsyncTcpSocketInstance> AsyncTcpSocket::_getIoInstance()
{
return Ref<AsyncTcpSocketInstance>::from(AsyncStreamBase::getIoInstance());
}
void AsyncTcpSocket::_onConnect(sl_bool flagError)
{
if (m_onConnect.isNotNull()) {
m_onConnect(this, flagError);
m_onConnect.setNull();
}
}
SLIB_DEFINE_OBJECT(AsyncTcpServerInstance, AsyncIoInstance)
AsyncTcpServerInstance::AsyncTcpServerInstance()
{
m_flagRunning = sl_false;
}
AsyncTcpServerInstance::~AsyncTcpServerInstance()
{
_closeHandle();
}
void AsyncTcpServerInstance::start()
{
ObjectLocker lock(this);
if (m_flagRunning) {
return;
}
m_flagRunning = sl_true;
requestOrder();
}
sl_bool AsyncTcpServerInstance::isRunning()
{
return m_flagRunning;
}
sl_socket AsyncTcpServerInstance::getSocket()
{
return (sl_socket)(getHandle());
}
void AsyncTcpServerInstance::onClose()
{
m_flagRunning = sl_false;
_closeHandle();
}
void AsyncTcpServerInstance::_closeHandle()
{
sl_socket socket = getSocket();
if (socket != SLIB_SOCKET_INVALID_HANDLE) {
Socket::close(socket);
setHandle(SLIB_ASYNC_INVALID_HANDLE);
}
}
void AsyncTcpServerInstance::_onAccept(Socket& socketAccept, SocketAddress& address)
{
Ref<AsyncTcpServer> server = Ref<AsyncTcpServer>::from(getObject());
if (server.isNotNull()) {
server->_onAccept(socketAccept, address);
}
}
void AsyncTcpServerInstance::_onError()
{
Ref<AsyncTcpServer> server = Ref<AsyncTcpServer>::from(getObject());
if (server.isNotNull()) {
server->_onError();
}
}
SLIB_DEFINE_MOVEONLY_CLASS_DEFAULT_MEMBERS(AsyncTcpServerParam)
AsyncTcpServerParam::AsyncTcpServerParam()
{
flagIPv6 = sl_false;
flagAutoStart = sl_true;
flagLogError = sl_true;
}
SLIB_DEFINE_OBJECT(AsyncTcpServer, AsyncIoObject)
AsyncTcpServer::AsyncTcpServer()
{
}
AsyncTcpServer::~AsyncTcpServer()
{
}
Ref<AsyncTcpServer> AsyncTcpServer::create(AsyncTcpServerParam& param)
{
sl_bool flagIPv6 = param.flagIPv6;
Socket& socket = param.socket;
if (socket.isNone()) {
if (!(param.bindAddress.port)) {
return sl_null;
}
if (param.bindAddress.ip.isIPv6()) {
flagIPv6 = sl_true;
}
if (flagIPv6) {
socket = Socket::openTcp_IPv6();
} else {
socket = Socket::openTcp();
}
if (socket.isNone()) {
return sl_null;
}
#if defined(SLIB_PLATFORM_IS_UNIX)
/*
* SO_REUSEADDR option allows the server applications to listen on the port that is still
* bound by some TIME_WAIT sockets.
*
* http://stackoverflow.com/questions/14388706/socket-options-so-reuseaddr-and-so-reuseport-how-do-they-differ-do-they-mean-t
*/
socket.setOption_ReuseAddress(sl_true);
#endif
if (!(socket.bind(param.bindAddress))) {
if (param.flagLogError) {
LogError(TAG, "AsyncTcpServer bind error: %s, %s", param.bindAddress.toString(), Socket::getLastErrorMessage());
}
return sl_null;
}
}
if (socket.listen()) {
Ref<AsyncTcpServerInstance> instance = _createInstance(Move(socket), flagIPv6);
if (instance.isNotNull()) {
Ref<AsyncIoLoop> loop = param.ioLoop;
if (loop.isNull()) {
loop = AsyncIoLoop::getDefault();
if (loop.isNull()) {
return sl_null;
}
}
Ref<AsyncTcpServer> ret = new AsyncTcpServer;
if (ret.isNotNull()) {
ret->m_onAccept = param.onAccept;
ret->m_onError = param.onError;
instance->setObject(ret.get());
ret->setIoInstance(instance.get());
ret->setIoLoop(loop);
if (loop->attachInstance(instance.get(), AsyncIoMode::In)) {
if (param.flagAutoStart) {
instance->start();
}
return ret;
}
}
}
} else {
if (param.flagLogError) {
LogError(TAG, "AsyncTcpServer listen error: %s, %s", param.bindAddress.toString(), Socket::getLastErrorMessage());
}
}
return sl_null;
}
void AsyncTcpServer::close()
{
closeIoInstance();
}
sl_bool AsyncTcpServer::isOpened()
{
return getIoInstance().isNotNull();
}
void AsyncTcpServer::start()
{
Ref<AsyncTcpServerInstance> instance = _getIoInstance();
if (instance.isNotNull()) {
instance->start();
}
}
sl_bool AsyncTcpServer::isRunning()
{
Ref<AsyncTcpServerInstance> instance = _getIoInstance();
if (instance.isNotNull()) {
return instance->isRunning();
}
return sl_false;
}
sl_socket AsyncTcpServer::getSocket()
{
Ref<AsyncTcpServerInstance> instance = _getIoInstance();
if (instance.isNotNull()) {
return instance->getSocket();
}
return SLIB_SOCKET_INVALID_HANDLE;
}
Ref<AsyncTcpServerInstance> AsyncTcpServer::_getIoInstance()
{
return Ref<AsyncTcpServerInstance>::from(AsyncIoObject::getIoInstance());
}
void AsyncTcpServer::_onAccept(Socket& socketAccept, SocketAddress& address)
{
m_onAccept(this, socketAccept, address);
}
void AsyncTcpServer::_onError()
{
m_onError(this);
}
SLIB_DEFINE_OBJECT(AsyncUdpSocketInstance, AsyncIoInstance)
AsyncUdpSocketInstance::AsyncUdpSocketInstance()
{
m_flagRunning = sl_false;
}
AsyncUdpSocketInstance::~AsyncUdpSocketInstance()
{
_closeHandle();
}
void AsyncUdpSocketInstance::start()
{
ObjectLocker lock(this);
if (m_flagRunning) {
return;
}
m_flagRunning = sl_true;
requestOrder();
}
sl_bool AsyncUdpSocketInstance::isRunning()
{
return m_flagRunning;
}
sl_socket AsyncUdpSocketInstance::getSocket()
{
return (sl_socket)(getHandle());
}
void AsyncUdpSocketInstance::onClose()
{
m_flagRunning = sl_false;
_closeHandle();
}
void AsyncUdpSocketInstance::_closeHandle()
{
sl_socket socket = getSocket();
if (socket != SLIB_SOCKET_INVALID_HANDLE) {
Socket::close(socket);
setHandle(SLIB_ASYNC_INVALID_HANDLE);
}
}
void AsyncUdpSocketInstance::_onReceive(SocketAddress& address, sl_uint32 size)
{
Ref<AsyncUdpSocket> object = Ref<AsyncUdpSocket>::from(getObject());
if (object.isNotNull()) {
object->_onReceive(address, m_buffer.getData(), size);
}
}
void AsyncUdpSocketInstance::_onError()
{
Ref<AsyncUdpSocket> object = Ref<AsyncUdpSocket>::from(getObject());
if (object.isNotNull()) {
object->_onError();
}
}
SLIB_DEFINE_MOVEONLY_CLASS_DEFAULT_MEMBERS(AsyncUdpSocketParam)
AsyncUdpSocketParam::AsyncUdpSocketParam()
{
flagIPv6 = sl_false;
flagBroadcast = sl_false;
flagAutoStart = sl_true;
flagLogError = sl_false;
packetSize = 65536;
}
SLIB_DEFINE_OBJECT(AsyncUdpSocket, AsyncIoObject)
AsyncUdpSocket::AsyncUdpSocket()
{
}
AsyncUdpSocket::~AsyncUdpSocket()
{
}
Ref<AsyncUdpSocket> AsyncUdpSocket::create(AsyncUdpSocketParam& param)
{
if (param.packetSize < 1) {
return sl_null;
}
Socket& socket = param.socket;
if (socket.isNone()) {
sl_bool flagIPv6 = param.flagIPv6;
if (param.bindAddress.ip.isIPv6()) {
flagIPv6 = sl_true;
}
if (flagIPv6) {
socket = Socket::openUdp_IPv6();
} else {
socket = Socket::openUdp();
}
if (socket.isNone()) {
return sl_null;
}
#if defined(SLIB_PLATFORM_IS_UNIX)
/*
* SO_REUSEADDR option allows the server applications to listen on the port that is still
* bound by some TIME_WAIT sockets.
*
* http://stackoverflow.com/questions/14388706/socket-options-so-reuseaddr-and-so-reuseport-how-do-they-differ-do-they-mean-t
*/
socket.setOption_ReuseAddress(sl_true);
#endif
if (param.bindAddress.ip.isNotNone() || param.bindAddress.port != 0) {
if (!(socket.bind(param.bindAddress))) {
if (param.flagLogError) {
LogError(TAG, "AsyncTcpSocket bind error: %s, %s", param.bindAddress.toString(), Socket::getLastErrorMessage());
}
return sl_null;
}
}
}
if (param.flagBroadcast) {
socket.setOption_Broadcast(sl_true);
}
Ref<AsyncUdpSocketInstance> instance = _createInstance(Move(socket), param.packetSize);
if (instance.isNotNull()) {
Ref<AsyncIoLoop> loop = param.ioLoop;
if (loop.isNull()) {
loop = AsyncIoLoop::getDefault();
if (loop.isNull()) {
return sl_null;
}
}
Ref<AsyncUdpSocket> ret = new AsyncUdpSocket;
if (ret.isNotNull()) {
ret->m_onReceiveFrom = param.onReceiveFrom;
instance->setObject(ret.get());
ret->setIoInstance(instance.get());
ret->setIoLoop(loop);
if (loop->attachInstance(instance.get(), AsyncIoMode::In)) {
if (param.flagAutoStart) {
ret->start();
}
return ret;
}
}
}
return sl_null;
}
void AsyncUdpSocket::close()
{
closeIoInstance();
}
sl_bool AsyncUdpSocket::isOpened()
{
return getIoInstance().isNotNull();
}
void AsyncUdpSocket::start()
{
Ref<AsyncUdpSocketInstance> instance = _getIoInstance();
if (instance.isNotNull()) {
instance->start();
}
}
sl_bool AsyncUdpSocket::isRunning()
{
Ref<AsyncUdpSocketInstance> instance = _getIoInstance();
if (instance.isNotNull()) {
return instance->isRunning();
}
return sl_false;
}
sl_socket AsyncUdpSocket::getSocket()
{
Ref<AsyncUdpSocketInstance> instance = _getIoInstance();
if (instance.isNotNull()) {
return instance->getSocket();
}
return SLIB_SOCKET_INVALID_HANDLE;
}
void AsyncUdpSocket::setBroadcast(sl_bool flag)
{
HandlePtr<Socket> socket(getSocket());
if (socket->isNotNone()) {
socket->setOption_Broadcast(flag);
}
}
void AsyncUdpSocket::setSendBufferSize(sl_uint32 size)
{
HandlePtr<Socket> socket(getSocket());
if (socket->isNotNone()) {
socket->setOption_SendBufferSize(size);
}
}
void AsyncUdpSocket::setReceiveBufferSize(sl_uint32 size)
{
HandlePtr<Socket> socket(getSocket());
if (socket->isNotNone()) {
socket->setOption_ReceiveBufferSize(size);
}
}
sl_bool AsyncUdpSocket::sendTo(const SocketAddress& addressTo, const void* data, sl_size size)
{
HandlePtr<Socket> socket(getSocket());
if (socket->isNotNone()) {
return socket->sendTo(addressTo, data, size) == size;
}
return sl_false;
}
sl_bool AsyncUdpSocket::sendTo(const SocketAddress& addressTo, const Memory& mem)
{
return sendTo(addressTo, mem.getData(), (sl_uint32)(mem.getSize()));
}
Ref<AsyncUdpSocketInstance> AsyncUdpSocket::_getIoInstance()
{
return Ref<AsyncUdpSocketInstance>::from(AsyncIoObject::getIoInstance());
}
void AsyncUdpSocket::_onReceive(SocketAddress& address, void* data, sl_uint32 sizeReceived)
{
m_onReceiveFrom(this, address, data, sizeReceived);
}
void AsyncUdpSocket::_onError()
{
m_onError(this);
}
}
| 23.985549 | 133 | 0.700627 | [
"object"
] |
25f6bc3adaff13baedad106c0b34c6124d839afe | 13,622 | cpp | C++ | libcaf_core/test/composable_behavior.cpp | dosuperuser/actor-framework | bee96d84bbc95414df5084b2d65f4886ba731558 | [
"BSL-1.0",
"BSD-3-Clause"
] | null | null | null | libcaf_core/test/composable_behavior.cpp | dosuperuser/actor-framework | bee96d84bbc95414df5084b2d65f4886ba731558 | [
"BSL-1.0",
"BSD-3-Clause"
] | null | null | null | libcaf_core/test/composable_behavior.cpp | dosuperuser/actor-framework | bee96d84bbc95414df5084b2d65f4886ba731558 | [
"BSL-1.0",
"BSD-3-Clause"
] | null | null | null | /******************************************************************************
* ____ _ _____ *
* / ___| / \ | ___| C++ *
* | | / _ \ | |_ Actor *
* | |___ / ___ \| _| Framework *
* \____/_/ \_|_| *
* *
* Copyright 2011-2018 Dominik Charousset *
* *
* Distributed under the terms and conditions of the BSD 3-Clause License or *
* (at your option) under the terms and conditions of the Boost Software *
* License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *
* *
* If you did not receive a copy of the license files, see *
* http://opensource.org/licenses/BSD-3-Clause and *
* http://www.boost.org/LICENSE_1_0.txt. *
******************************************************************************/
#define CAF_SUITE composable_behavior
#include "caf/composable_behavior.hpp"
#include "caf/test/dsl.hpp"
#include "caf/attach_stream_sink.hpp"
#include "caf/attach_stream_source.hpp"
#include "caf/attach_stream_stage.hpp"
#include "caf/typed_actor.hpp"
#define ERROR_HANDLER [&](error& err) { CAF_FAIL(system.render(err)); }
using namespace caf;
namespace {
// -- composable behaviors using primitive data types and streams --------------
using i3_actor = typed_actor<replies_to<int, int, int>::with<int>>;
using d_actor = typed_actor<replies_to<double>::with<double, double>>;
using source_actor = typed_actor<replies_to<open_atom>::with<stream<int>>>;
using stage_actor = typed_actor<replies_to<stream<int>>::with<stream<int>>>;
using sink_actor = typed_actor<reacts_to<stream<int>>>;
using foo_actor = i3_actor::extend_with<d_actor>;
class foo_actor_state : public composable_behavior<foo_actor> {
public:
result<int> operator()(int x, int y, int z) override {
return x + y + z;
}
result<double, double> operator()(double x) override {
return {x, x};
}
};
class i3_actor_state : public composable_behavior<i3_actor> {
public:
result<int> operator()(int x, int y, int z) override {
return x + y + z;
}
};
class d_actor_state : public composable_behavior<d_actor> {
public:
result<double, double> operator()(double x) override {
return {x, x};
}
};
class i3_actor_state2 : public composable_behavior<i3_actor> {
public:
result<int> operator()(int x, int y, int z) override {
return x * (y * z);
}
};
// checks whether CAF resolves "diamonds" properly by inheriting
// from two behaviors that both implement i3_actor
struct foo_actor_state2
: composed_behavior<i3_actor_state2, i3_actor_state, d_actor_state> {
result<int> operator()(int x, int y, int z) override {
return x - y - z;
}
};
class source_actor_state : public composable_behavior<source_actor> {
public:
result<stream<int>> operator()(open_atom) override {
return attach_stream_source(
self, [](size_t& counter) { counter = 0; },
[](size_t& counter, downstream<int>& out, size_t hint) {
auto n = std::min(static_cast<size_t>(100 - counter), hint);
for (size_t i = 0; i < n; ++i)
out.push(counter++);
},
[](const size_t& counter) { return counter < 100; });
}
};
class stage_actor_state : public composable_behavior<stage_actor> {
public:
result<stream<int>> operator()(stream<int> in) override {
return attach_stream_stage(
self, in,
[](unit_t&) {
// nop
},
[](unit_t&, downstream<int>& out, int x) {
if (x % 2 == 0)
out.push(x);
});
}
};
class sink_actor_state : public composable_behavior<sink_actor> {
public:
std::vector<int> buf;
result<void> operator()(stream<int> in) override {
attach_stream_sink(
self, in,
[](unit_t&) {
// nop
},
[=](unit_t&, int x) { buf.emplace_back(x); });
return unit;
}
};
// -- composable behaviors using param<T> arguments ----------------------------
std::atomic<long> counting_strings_created;
std::atomic<long> counting_strings_moved;
std::atomic<long> counting_strings_destroyed;
// counts how many instances where created
struct counting_string {
public:
counting_string() {
++counting_strings_created;
}
counting_string(const char* cstr) : str_(cstr) {
++counting_strings_created;
}
counting_string(const counting_string& x) : str_(x.str_) {
++counting_strings_created;
}
counting_string(counting_string&& x) : str_(std::move(x.str_)) {
++counting_strings_created;
++counting_strings_moved;
}
~counting_string() {
++counting_strings_destroyed;
}
counting_string& operator=(const char* cstr) {
str_ = cstr;
return *this;
}
const std::string& str() const {
return str_;
}
template <class Inspector>
friend typename Inspector::result_type inspect(Inspector& f,
counting_string& x) {
return f(x.str_);
}
private:
std::string str_;
};
bool operator==(const counting_string& x, const counting_string& y) {
return x.str() == y.str();
}
bool operator==(const counting_string& x, const char* y) {
return x.str() == y;
}
std::string to_string(const counting_string& ref) {
return ref.str();
}
} // namespace
namespace std {
template <>
struct hash<counting_string> {
size_t operator()(const counting_string& ref) const {
hash<string> f;
return f(ref.str());
}
};
} // namespace std
namespace {
// a simple dictionary
using dict = typed_actor<
replies_to<get_atom, counting_string>::with<counting_string>,
replies_to<put_atom, counting_string, counting_string>::with<void>>;
class dict_state : public composable_behavior<dict> {
public:
result<counting_string> operator()(get_atom,
param<counting_string> key) override {
auto i = values_.find(key.get());
if (i == values_.end())
return "";
return i->second;
}
result<void> operator()(put_atom, param<counting_string> key,
param<counting_string> value) override {
if (values_.count(key.get()) != 0)
return unit;
values_.emplace(key.move(), value.move());
return unit;
}
protected:
std::unordered_map<counting_string, counting_string> values_;
};
using delayed_testee_actor = typed_actor<
reacts_to<int>, replies_to<bool>::with<int>, reacts_to<std::string>>;
class delayed_testee : public composable_behavior<delayed_testee_actor> {
public:
result<void> operator()(int x) override {
CAF_CHECK_EQUAL(x, 42);
delayed_anon_send(self, std::chrono::milliseconds(10), true);
return unit;
}
result<int> operator()(bool x) override {
CAF_CHECK_EQUAL(x, true);
self->delayed_send(self, std::chrono::milliseconds(10), "hello");
return 0;
}
result<void> operator()(param<std::string> x) override {
CAF_CHECK_EQUAL(x.get(), "hello");
return unit;
}
};
struct config : actor_system_config {
config() {
using foo_actor_impl = composable_behavior_based_actor<foo_actor_state>;
add_actor_type<foo_actor_impl>("foo_actor");
}
};
struct fixture : test_coordinator_fixture<config> {
// nop
};
} // namespace
CAF_TEST_FIXTURE_SCOPE(composable_behaviors_tests, fixture)
CAF_TEST(composition) {
CAF_MESSAGE("test foo_actor_state");
auto f1 = sys.spawn<foo_actor_state>();
inject((int, int, int), from(self).to(f1).with(1, 2, 4));
expect((int), from(f1).to(self).with(7));
inject((double), from(self).to(f1).with(42.0));
expect((double, double), from(f1).to(self).with(42.0, 42.0));
CAF_MESSAGE("test composed_behavior<i3_actor_state, d_actor_state>");
f1 = sys.spawn<composed_behavior<i3_actor_state, d_actor_state>>();
inject((int, int, int), from(self).to(f1).with(1, 2, 4));
expect((int), from(f1).to(self).with(7));
inject((double), from(self).to(f1).with(42.0));
expect((double, double), from(f1).to(self).with(42.0, 42.0));
CAF_MESSAGE("test composed_behavior<i3_actor_state2, d_actor_state>");
f1 = sys.spawn<composed_behavior<i3_actor_state2, d_actor_state>>();
inject((int, int, int), from(self).to(f1).with(1, 2, 4));
expect((int), from(f1).to(self).with(8));
inject((double), from(self).to(f1).with(42.0));
expect((double, double), from(f1).to(self).with(42.0, 42.0));
CAF_MESSAGE("test foo_actor_state2");
f1 = sys.spawn<foo_actor_state2>();
inject((int, int, int), from(self).to(f1).with(1, 2, 4));
expect((int), from(f1).to(self).with(-5));
inject((double), from(self).to(f1).with(42.0));
expect((double, double), from(f1).to(self).with(42.0, 42.0));
}
CAF_TEST(param_detaching) {
auto dict = actor_cast<actor>(sys.spawn<dict_state>());
// Using CAF is the key to success!
counting_string key = "CAF";
counting_string value = "success";
CAF_CHECK_EQUAL(counting_strings_created.load(), 2);
CAF_CHECK_EQUAL(counting_strings_moved.load(), 0);
CAF_CHECK_EQUAL(counting_strings_destroyed.load(), 0);
// Wrap two strings into messages.
auto put_msg = make_message(put_atom_v, key, value);
auto get_msg = make_message(get_atom_v, key);
CAF_CHECK_EQUAL(counting_strings_created.load(), 5);
CAF_CHECK_EQUAL(counting_strings_moved.load(), 0);
CAF_CHECK_EQUAL(counting_strings_destroyed.load(), 0);
// Send put message to dictionary.
self->send(dict, put_msg);
sched.run();
// The handler of put_atom calls .move() on key and value, both causing to
// detach + move into the map.
CAF_CHECK_EQUAL(counting_strings_created.load(), 9);
CAF_CHECK_EQUAL(counting_strings_moved.load(), 2);
CAF_CHECK_EQUAL(counting_strings_destroyed.load(), 2);
// Send put message to dictionary again.
self->send(dict, put_msg);
sched.run();
// The handler checks whether key already exists -> no copies.
CAF_CHECK_EQUAL(counting_strings_created.load(), 9);
CAF_CHECK_EQUAL(counting_strings_moved.load(), 2);
CAF_CHECK_EQUAL(counting_strings_destroyed.load(), 2);
// Alter our initial put, this time moving it to the dictionary.
put_msg.get_mutable_as<counting_string>(1) = "neverlord";
put_msg.get_mutable_as<counting_string>(2) = "CAF";
// Send new put message to dictionary.
self->send(dict, std::move(put_msg));
sched.run();
// The handler of put_atom calls .move() on key and value, but no detaching
// occurs this time (unique access) -> move into the map.
CAF_CHECK_EQUAL(counting_strings_created.load(), 11);
CAF_CHECK_EQUAL(counting_strings_moved.load(), 4);
CAF_CHECK_EQUAL(counting_strings_destroyed.load(), 4);
// Finally, check for original key.
self->send(dict, std::move(get_msg));
sched.run();
self->receive([&](const counting_string& str) {
// We receive a copy of the value, which is copied out of the map and then
// moved into the result message; the string from our get_msg is destroyed.
CAF_CHECK_EQUAL(counting_strings_created.load(), 13);
CAF_CHECK_EQUAL(counting_strings_moved.load(), 5);
CAF_CHECK_EQUAL(counting_strings_destroyed.load(), 6);
CAF_CHECK_EQUAL(str, "success");
});
// Temporary of our handler is destroyed.
CAF_CHECK_EQUAL(counting_strings_destroyed.load(), 7);
self->send_exit(dict, exit_reason::user_shutdown);
sched.run();
dict = nullptr;
// Only `key` and `value` from this scope remain.
CAF_CHECK_EQUAL(counting_strings_destroyed.load(), 11);
}
CAF_TEST(delayed_sends) {
auto testee = self->spawn<delayed_testee>();
inject((int), from(self).to(testee).with(42));
disallow((bool), from(_).to(testee));
sched.trigger_timeouts();
expect((bool), from(_).to(testee));
disallow((std::string), from(testee).to(testee).with("hello"));
sched.trigger_timeouts();
expect((std::string), from(testee).to(testee).with("hello"));
}
CAF_TEST(dynamic_spawning) {
auto testee = unbox(sys.spawn<foo_actor>("foo_actor", make_message()));
inject((int, int, int), from(self).to(testee).with(1, 2, 4));
expect((int), from(testee).to(self).with(7));
inject((double), from(self).to(testee).with(42.0));
expect((double, double), from(testee).to(self).with(42.0, 42.0));
}
CAF_TEST(streaming) {
auto src = sys.spawn<source_actor_state>();
auto stg = sys.spawn<stage_actor_state>();
auto snk = sys.spawn<sink_actor_state>();
using src_to_stg = typed_actor<replies_to<open_atom>::with<stream<int>>>;
using stg_to_snk = typed_actor<reacts_to<stream<int>>>;
static_assert(std::is_same<decltype(stg * src), src_to_stg>::value,
"stg * src produces the wrong type");
static_assert(std::is_same<decltype(snk * stg), stg_to_snk>::value,
"stg * src produces the wrong type");
auto pipeline = snk * stg * src;
self->send(pipeline, open_atom_v);
run();
using sink_actor = composable_behavior_based_actor<sink_actor_state>;
auto& st = deref<sink_actor>(snk).state;
CAF_CHECK_EQUAL(st.buf.size(), 50u);
auto is_even = [](int x) { return x % 2 == 0; };
CAF_CHECK(std::all_of(st.buf.begin(), st.buf.end(), is_even));
anon_send_exit(src, exit_reason::user_shutdown);
anon_send_exit(stg, exit_reason::user_shutdown);
anon_send_exit(snk, exit_reason::user_shutdown);
}
CAF_TEST_FIXTURE_SCOPE_END()
| 33.469287 | 80 | 0.643518 | [
"render",
"vector"
] |
d3078b52209dc0050531a2b4381e6441c6a4a3a7 | 17,263 | cpp | C++ | model/mosesdecoder/moses/FF/LexicalReordering/LexicalReorderingTable.cpp | saeedesm/UNMT_AH | cc171bf66933b5c0ad8a0ab87e57f7364312a7df | [
"Apache-2.0"
] | 3 | 2019-12-02T14:53:29.000Z | 2020-08-12T18:01:49.000Z | tools/mosesdecoder-master/moses/FF/LexicalReordering/LexicalReorderingTable.cpp | Pangeamt/nectm | 6b84f048698f2530b9fdbb30695f2e2217c3fbfe | [
"Apache-2.0"
] | 2 | 2020-11-06T14:40:10.000Z | 2020-12-29T19:03:11.000Z | tools/mosesdecoder-master/moses/FF/LexicalReordering/LexicalReorderingTable.cpp | Pangeamt/nectm | 6b84f048698f2530b9fdbb30695f2e2217c3fbfe | [
"Apache-2.0"
] | 2 | 2020-03-26T16:05:11.000Z | 2020-08-06T16:35:39.000Z | // -*- c++ -*-
#include "LexicalReorderingTable.h"
#include "moses/InputFileStream.h"
#include "moses/StaticData.h"
#include "moses/TranslationModel/PhraseDictionary.h"
#include "moses/GenerationDictionary.h"
#include "moses/TargetPhrase.h"
#include "moses/TargetPhraseCollection.h"
#include "moses/TranslationTask.h"
#if !defined WIN32 || defined __MINGW32__ || defined HAVE_CMPH
#include "moses/TranslationModel/CompactPT/LexicalReorderingTableCompact.h"
#endif
namespace Moses
{
//cleans str of leading and tailing spaces
std::string auxClearString(const std::string& str)
{
int i = 0, j = str.size()-1;
while(i <= j) {
if(' ' != str[i]) {
break;
} else {
++i;
}
}
while(j >= i) {
if(' ' != str[j]) {
break;
} else {
--j;
}
}
return str.substr(i,j-i+1);
}
void auxAppend(IPhrase& head, const IPhrase& tail)
{
head.reserve(head.size()+tail.size());
for(size_t i = 0; i < tail.size(); ++i) {
head.push_back(tail[i]);
}
}
LexicalReorderingTable*
LexicalReorderingTable::
LoadAvailable(const std::string& filePath,
const FactorList& f_factors,
const FactorList& e_factors,
const FactorList& c_factors)
{
//decide use Compact or Tree or Memory table
#ifdef HAVE_CMPH
LexicalReorderingTable *compactLexr = NULL;
compactLexr = LexicalReorderingTableCompact::CheckAndLoad(filePath + ".minlexr", f_factors, e_factors, c_factors);
if(compactLexr)
return compactLexr;
#endif
LexicalReorderingTable* ret;
if (FileExists(filePath+".binlexr.idx") )
ret = new LexicalReorderingTableTree(filePath, f_factors,
e_factors, c_factors);
else
ret = new LexicalReorderingTableMemory(filePath, f_factors,
e_factors, c_factors);
return ret;
}
LexicalReorderingTableMemory::
LexicalReorderingTableMemory(const std::string& filePath,
const std::vector<FactorType>& f_factors,
const std::vector<FactorType>& e_factors,
const std::vector<FactorType>& c_factors)
: LexicalReorderingTable(f_factors, e_factors, c_factors)
{
LoadFromFile(filePath);
}
LexicalReorderingTableMemory::
~LexicalReorderingTableMemory() { }
std::vector<float>
LexicalReorderingTableMemory::GetScore(const Phrase& f,
const Phrase& e,
const Phrase& c)
{
//rather complicated because of const can't use []... as [] might enter new things into std::map
//also can't have to be careful with words range if c is empty can't use c.GetSize()-1 will underflow and be large
TableType::const_iterator r;
std::string key;
if(0 == c.GetSize()) {
key = MakeKey(f,e,c);
r = m_Table.find(key);
if(m_Table.end() != r) {
return r->second;
}
} else {
//right try from large to smaller context
for(size_t i = 0; i <= c.GetSize(); ++i) {
Phrase sub_c(c.GetSubString(Range(i,c.GetSize()-1)));
key = MakeKey(f,e,sub_c);
r = m_Table.find(key);
if(m_Table.end() != r) {
return r->second;
}
}
}
return Scores();
}
void
LexicalReorderingTableMemory::
DbgDump(std::ostream* out) const
{
TableType::const_iterator i;
for(i = m_Table.begin(); i != m_Table.end(); ++i) {
*out << " key: '" << i->first << "' score: ";
*out << "(num scores: " << (i->second).size() << ")";
for(size_t j = 0; j < (i->second).size(); ++j)
*out << (i->second)[j] << " ";
*out << "\n";
}
};
std::string
LexicalReorderingTableMemory::MakeKey(const Phrase& f,
const Phrase& e,
const Phrase& c) const
{
return MakeKey(auxClearString(f.GetStringRep(m_FactorsF)),
auxClearString(e.GetStringRep(m_FactorsE)),
auxClearString(c.GetStringRep(m_FactorsC)));
}
std::string
LexicalReorderingTableMemory::MakeKey(const std::string& f,
const std::string& e,
const std::string& c) const
{
std::string key;
if(!f.empty()) key += f;
if(!m_FactorsE.empty()) {
if(!key.empty()) {
key += "|||";
}
key += e;
}
if(!m_FactorsC.empty()) {
if(!key.empty()) {
key += "|||";
}
key += c;
}
return key;
}
void
LexicalReorderingTableMemory::
LoadFromFile(const std::string& filePath)
{
std::string fileName = filePath;
if(!FileExists(fileName) && FileExists(fileName+".gz"))
fileName += ".gz";
InputFileStream file(fileName);
std::string line(""), key("");
int numScores = -1;
std::cerr << "Loading table into memory...";
while(!getline(file, line).eof()) {
std::vector<std::string> tokens = TokenizeMultiCharSeparator(line, "|||");
int t = 0 ;
std::string f(""),e(""),c("");
if(!m_FactorsF.empty()) {
//there should be something for f
f = auxClearString(tokens.at(t));
++t;
}
if(!m_FactorsE.empty()) {
//there should be something for e
e = auxClearString(tokens.at(t));
++t;
}
if(!m_FactorsC.empty()) {
//there should be something for c
c = auxClearString(tokens.at(t));
++t;
}
//last token are the probs
std::vector<float> p = Scan<float>(Tokenize(tokens.at(t)));
//sanity check: all lines must have equall number of probs
if(-1 == numScores) {
numScores = (int)p.size(); //set in first line
}
if((int)p.size() != numScores) {
TRACE_ERR( "found inconsistent number of probabilities... found "
<< p.size() << " expected " << numScores << std::endl);
exit(0);
}
std::transform(p.begin(),p.end(),p.begin(),TransformScore);
std::transform(p.begin(),p.end(),p.begin(),FloorScore);
//save it all into our map
m_Table[MakeKey(f,e,c)] = p;
}
std::cerr << "done.\n";
}
LexicalReorderingTableTree::
LexicalReorderingTableTree(const std::string& filePath,
const std::vector<FactorType>& f_factors,
const std::vector<FactorType>& e_factors,
const std::vector<FactorType>& c_factors)
: LexicalReorderingTable(f_factors, e_factors, c_factors)
, m_UseCache(false)
, m_FilePath(filePath)
{
m_Table.reset(new PrefixTreeMap());
m_Table->Read(m_FilePath+".binlexr");
}
LexicalReorderingTableTree::
~LexicalReorderingTableTree()
{ }
Scores
LexicalReorderingTableTree::
GetScore(const Phrase& f, const Phrase& e, const Phrase& c)
{
if((!m_FactorsF.empty() && 0 == f.GetSize())
|| (!m_FactorsE.empty() && 0 == e.GetSize())) {
//NOTE: no check for c as c might be empty, e.g. start of sentence
//not a proper key
// phi: commented out, since e may be empty (drop-unknown)
//std::cerr << "Not a proper key!\n";
return Scores();
}
CacheType::iterator i;
if(m_UseCache) {
std::pair<CacheType::iterator, bool> r;
r = m_Cache.insert(std::make_pair(MakeCacheKey(f,e),Candidates()));
if(!r.second) return auxFindScoreForContext((r.first)->second, c);
i = r.first;
} else if((i = m_Cache.find(MakeCacheKey(f,e))) != m_Cache.end())
// although we might not be caching now, cache might be none empty!
return auxFindScoreForContext(i->second, c);
// not in cache => go to file...
Candidates cands;
m_Table->GetCandidates(MakeTableKey(f,e), &cands);
if(cands.empty()) return Scores();
if(m_UseCache) i->second = cands;
if(m_FactorsC.empty()) {
UTIL_THROW_IF2(1 != cands.size(), "Error");
return cands[0].GetScore(0);
} else return auxFindScoreForContext(cands, c);
};
Scores
LexicalReorderingTableTree::
auxFindScoreForContext(const Candidates& cands, const Phrase& context)
{
if(m_FactorsC.empty()) {
UTIL_THROW_IF2(cands.size() > 1, "Error");
return (cands.size() == 1) ? cands[0].GetScore(0) : Scores();
} else {
std::vector<std::string> cvec;
for(size_t i = 0; i < context.GetSize(); ++i)
cvec.push_back(context.GetWord(i).GetString(m_FactorsC, false));
IPhrase c = m_Table->ConvertPhrase(cvec,TargetVocId);
IPhrase sub_c;
IPhrase::iterator start = c.begin();
for(size_t j = 0; j <= context.GetSize(); ++j, ++start) {
sub_c.assign(start, c.end());
for(size_t cand = 0; cand < cands.size(); ++cand) {
IPhrase p = cands[cand].GetPhrase(0);
if(cands[cand].GetPhrase(0) == sub_c)
return cands[cand].GetScore(0);
}
}
return Scores();
}
}
void
LexicalReorderingTableTree::
InitializeForInput(ttasksptr const& ttask)
{
const InputType& input = *ttask->GetSource();
ClearCache();
if(ConfusionNet const* cn = dynamic_cast<ConfusionNet const*>(&input)) {
Cache(*cn);
} else if (dynamic_cast<Sentence const*>(&input)) {
// Cache(*s); ... this just takes up too much memory, we cache elsewhere
DisableCache();
}
if (!m_Table.get()) {
//load thread specific table.
m_Table.reset(new PrefixTreeMap());
m_Table->Read(m_FilePath+".binlexr");
}
};
bool
LexicalReorderingTableTree::
Create(std::istream& inFile, const std::string& outFileName)
{
typedef PrefixTreeSA<LabelId,OFF_T> PSA;
std::string
line,
ofn(outFileName+".binlexr.srctree"),
oft(outFileName+".binlexr.tgtdata"),
ofi(outFileName+".binlexr.idx"),
ofsv(outFileName+".binlexr.voc0"),
oftv(outFileName+".binlexr.voc1");
FILE *os = fOpen(ofn.c_str(),"wb");
FILE *ot = fOpen(oft.c_str(),"wb");
PSA *psa = new PSA;
PSA::setDefault(InvalidOffT);
WordVoc* voc[3];
LabelId currFirstWord = InvalidLabelId;
IPhrase currKey;
Candidates cands;
std::vector<OFF_T> vo;
size_t lnc = 0;
size_t numTokens = 0;
size_t numKeyTokens = 0;
while(getline(inFile, line)) {
++lnc;
if(0 == lnc % 10000) TRACE_ERR(".");
IPhrase key;
Scores score;
std::vector<std::string> tokens = TokenizeMultiCharSeparator(line, "|||");
std::string w;
if(1 == lnc) {
//do some init stuff in the first line
numTokens = tokens.size();
if(tokens.size() == 2) {
// f ||| score
numKeyTokens = 1;
voc[0] = new WordVoc();
voc[1] = 0;
} else if(3 == tokens.size() || 4 == tokens.size()) {
//either f ||| e ||| score or f ||| e ||| c ||| score
numKeyTokens = 2;
voc[0] = new WordVoc(); //f voc
voc[1] = new WordVoc(); //e voc
voc[2] = voc[1]; //c & e share voc
}
} else {
//sanity check ALL lines must have same number of tokens
UTIL_THROW_IF2(numTokens != tokens.size(),
"Lines do not have the same number of tokens");
}
size_t phrase = 0;
for(; phrase < numKeyTokens; ++phrase) {
//conditioned on more than just f... need |||
if(phrase >=1) key.push_back(PrefixTreeMap::MagicWord);
std::istringstream is(tokens[phrase]);
while(is >> w) key.push_back(voc[phrase]->add(w));
}
//collect all non key phrases, i.e. c
std::vector<IPhrase> tgt_phrases;
tgt_phrases.resize(numTokens - numKeyTokens - 1);
for(size_t j = 0; j < tgt_phrases.size(); ++j, ++phrase) {
std::istringstream is(tokens[numKeyTokens + j]);
while(is >> w) tgt_phrases[j].push_back(voc[phrase]->add(w));
}
//last token is score
std::istringstream is(tokens[numTokens-1]);
while(is >> w) score.push_back(atof(w.c_str()));
//transform score now...
std::transform(score.begin(),score.end(),score.begin(),TransformScore);
std::transform(score.begin(),score.end(),score.begin(),FloorScore);
std::vector<Scores> scores;
scores.push_back(score);
if(key.empty()) {
TRACE_ERR("WARNING: empty source phrase in line '"<<line<<"'\n");
continue;
}
//first time inits
if(currFirstWord == InvalidLabelId) currFirstWord = key[0];
if(currKey.empty()) {
currKey = key;
//insert key into tree
UTIL_THROW_IF2(psa == NULL, "Object not yet created");
PSA::Data& d = psa->insert(key);
if(d == InvalidOffT) d = fTell(ot);
else {
TRACE_ERR("ERROR: source phrase already inserted (A)!\nline("
<< lnc << "): '" << line << "\n");
return false;
}
}
if(currKey != key) {
//ok new key
currKey = key;
//a) write cands for old key
cands.writeBin(ot);
cands.clear();
//b) check if we need to move on to new tree root
if(key[0] != currFirstWord) {
// write key prefix tree to file and clear
PTF pf;
if(currFirstWord >= vo.size())
vo.resize(currFirstWord+1,InvalidOffT);
vo[currFirstWord] = fTell(os);
pf.create(*psa, os);
delete psa;
psa = new PSA;
currFirstWord = key[0];
}
// c) insert key into tree
UTIL_THROW_IF2(psa == NULL, "Object not yet created");
PSA::Data& d = psa->insert(key);
if(d == InvalidOffT) d = fTell(ot);
else {
TRACE_ERR("ERROR: source phrase already inserted (A)!\nline("
<< lnc << "): '" << line << "\n");
return false;
}
}
cands.push_back(GenericCandidate(tgt_phrases, scores));
}
if (lnc == 0) {
TRACE_ERR("ERROR: empty lexicalised reordering file\n" << std::endl);
return false;
}
cands.writeBin(ot);
cands.clear();
PTF pf;
if(currFirstWord >= vo.size())
vo.resize(currFirstWord+1,InvalidOffT);
vo[currFirstWord] = fTell(os);
pf.create(*psa,os);
delete psa;
psa=0;
fClose(os);
fClose(ot);
FILE *oi = fOpen(ofi.c_str(),"wb");
fWriteVector(oi,vo);
fClose(oi);
if(voc[0]) {
voc[0]->Write(ofsv);
delete voc[0];
}
if(voc[1]) {
voc[1]->Write(oftv);
delete voc[1];
}
return true;
}
std::string
LexicalReorderingTableTree::
MakeCacheKey(const Phrase& f, const Phrase& e) const
{
std::string key;
if(!m_FactorsF.empty())
key += auxClearString(f.GetStringRep(m_FactorsF));
if(!m_FactorsE.empty()) {
if(!key.empty()) {
key += "|||";
}
key += auxClearString(e.GetStringRep(m_FactorsE));
}
return key;
};
IPhrase
LexicalReorderingTableTree::
MakeTableKey(const Phrase& f, const Phrase& e) const
{
IPhrase key;
std::vector<std::string> keyPart;
if(!m_FactorsF.empty()) {
for(size_t i = 0; i < f.GetSize(); ++i)
keyPart.push_back(f.GetWord(i).GetString(m_FactorsF, false));
auxAppend(key, m_Table->ConvertPhrase(keyPart, SourceVocId));
keyPart.clear();
}
if(!m_FactorsE.empty()) {
if(!key.empty()) key.push_back(PrefixTreeMap::MagicWord);
for(size_t i = 0; i < e.GetSize(); ++i)
keyPart.push_back(e.GetWord(i).GetString(m_FactorsE, false));
auxAppend(key, m_Table->ConvertPhrase(keyPart,TargetVocId));
}
return key;
};
struct State {
State(PPimp* t, const std::string& p)
: pos(t), path(p) { }
PPimp* pos;
std::string path;
};
void
LexicalReorderingTableTree::
auxCacheForSrcPhrase(const Phrase& f)
{
if(m_FactorsE.empty()) {
//f is all of key...
Candidates cands;
m_Table->GetCandidates(MakeTableKey(f,Phrase(ARRAY_SIZE_INCR)),&cands);
m_Cache[MakeCacheKey(f,Phrase(ARRAY_SIZE_INCR))] = cands;
} else {
ObjectPool<PPimp> pool;
PPimp* pPos = m_Table->GetRoot();
// 1) goto subtree for f
for(size_t i = 0; i < f.GetSize() && 0 != pPos && pPos->isValid(); ++i)
pPos = m_Table->Extend(pPos, f.GetWord(i).GetString(m_FactorsF, false), SourceVocId);
if(pPos && pPos->isValid())
pPos = m_Table->Extend(pPos, PrefixTreeMap::MagicWord);
if(!pPos || !pPos->isValid())
return;
//2) explore whole subtree depth first & cache
std::string cache_key = auxClearString(f.GetStringRep(m_FactorsF)) + "|||";
std::vector<State> stack;
stack.push_back(State(pool.get(PPimp(pPos->ptr()->getPtr(pPos->idx),0,0)),""));
Candidates cands;
while(!stack.empty()) {
if(stack.back().pos->isValid()) {
LabelId w = stack.back().pos->ptr()->getKey(stack.back().pos->idx);
std::string next_path = stack.back().path + " " + m_Table->ConvertWord(w,TargetVocId);
//cache this
m_Table->GetCandidates(*stack.back().pos,&cands);
if(!cands.empty()) m_Cache[cache_key + auxClearString(next_path)] = cands;
cands.clear();
PPimp* next_pos = pool.get(PPimp(stack.back().pos->ptr()->getPtr(stack.back().pos->idx),0,0));
++stack.back().pos->idx;
stack.push_back(State(next_pos,next_path));
} else stack.pop_back();
}
}
}
void
LexicalReorderingTableTree::
Cache(const ConfusionNet& /*input*/)
{
return;
}
void
LexicalReorderingTableTree::
Cache(const Sentence& input)
{
//only works with sentences...
size_t prev_cache_size = m_Cache.size();
size_t max_phrase_length = input.GetSize();
for(size_t len = 0; len <= max_phrase_length; ++len) {
for(size_t start = 0; start+len <= input.GetSize(); ++start) {
Phrase f = input.GetSubString(Range(start, start+len));
auxCacheForSrcPhrase(f);
}
}
std::cerr << "Cached " << m_Cache.size() - prev_cache_size
<< " new primary reordering table keys\n";
}
}
| 29.06229 | 116 | 0.605109 | [
"object",
"vector",
"transform"
] |
d307d2070af3930341784c12ee76be872a33cb09 | 2,769 | cpp | C++ | common/src/module_linux.cpp | tyoma/micro-profiler | 32f6981c643b93997752d414f631fd6684772b28 | [
"MIT"
] | 194 | 2015-07-27T09:54:24.000Z | 2022-03-21T20:50:22.000Z | common/src/module_linux.cpp | tyoma/micro-profiler | 32f6981c643b93997752d414f631fd6684772b28 | [
"MIT"
] | 63 | 2015-08-19T16:42:33.000Z | 2022-02-22T20:30:49.000Z | common/src/module_linux.cpp | tyoma/micro-profiler | 32f6981c643b93997752d414f631fd6684772b28 | [
"MIT"
] | 33 | 2015-08-21T17:48:03.000Z | 2022-02-23T03:54:17.000Z | // Copyright (c) 2011-2021 by Artem A. Gevorkyan (gevorkyan.org)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#include <common/module.h>
#include <dlfcn.h>
#include <link.h>
#include <stdexcept>
#include <unistd.h>
using namespace std;
namespace micro_profiler
{
shared_ptr<void> load_library(const string &path)
{
return shared_ptr<void>(::dlopen(path.c_str(), RTLD_NOW), [] (void *h) {
if (h)
::dlclose(h);
});
}
string get_current_executable()
{
char path[1000];
int result = ::readlink("/proc/self/exe", path, sizeof(path) - 1);
return path[result >= 0 ? result : 0] = 0, path;
}
mapped_module get_module_info(const void *address)
{
Dl_info di = { };
::dladdr(address, &di);
mapped_module info = {
di.dli_fname && *di.dli_fname ? di.dli_fname : get_current_executable(),
static_cast<byte *>(di.dli_fbase),
std::vector<byte_range>()
};
return info;
}
void enumerate_process_modules(const module_callback_t &callback)
{
struct local
{
static int on_phdr(dl_phdr_info *phdr, size_t, void *cb)
{
int n = phdr->dlpi_phnum;
const module_callback_t &callback = *static_cast<const module_callback_t *>(cb);
mapped_module m = {
phdr->dlpi_name && *phdr->dlpi_name ? phdr->dlpi_name : get_current_executable(),
reinterpret_cast<byte *>(phdr->dlpi_addr),
std::vector<byte_range>()
};
for (const ElfW(Phdr) *segment = phdr->dlpi_phdr; n; --n, ++segment)
if (segment->p_type == PT_LOAD)
m.addresses.push_back(byte_range(m.base + segment->p_vaddr, segment->p_memsz));
if (!access(m.path.c_str(), 0))
callback(m);
return 0;
}
};
::dl_iterate_phdr(&local::on_phdr, const_cast<module_callback_t *>(&callback));
}
}
| 31.11236 | 86 | 0.70242 | [
"vector"
] |
d31220617356ee986b31040c88c186424a8d0c2b | 1,156 | hpp | C++ | src/chunk.hpp | DylanSp/cpplox | 97186dba4a22402c626a2de588fadd5bfbc69ae3 | [
"MIT"
] | null | null | null | src/chunk.hpp | DylanSp/cpplox | 97186dba4a22402c626a2de588fadd5bfbc69ae3 | [
"MIT"
] | 4 | 2021-08-29T05:49:12.000Z | 2021-09-02T01:35:24.000Z | src/chunk.hpp | DylanSp/cpplox | 97186dba4a22402c626a2de588fadd5bfbc69ae3 | [
"MIT"
] | null | null | null | #pragma once
#include "value.hpp"
#include <cstdint>
#include <string>
#include <vector>
namespace lox {
class OpCode {
public:
static constexpr uint8_t OP_CONSTANT = 0;
static constexpr uint8_t OP_RETURN = 1;
static constexpr uint8_t OP_NEGATE = 2;
static constexpr uint8_t OP_ADD = 3;
static constexpr uint8_t OP_SUBTRACT = 4;
static constexpr uint8_t OP_MULTIPLY = 5;
static constexpr uint8_t OP_DIVIDE = 6;
};
class Chunk {
private:
std::vector<int>
lineNumbers; // nth entry of this is the line number for nth byte of
// this.code; stored as a separate array to avoid messing
// with CPU cache of bytecode data
public:
std::vector<uint8_t> code; // stores opcodes AND operands
std::vector<Value> constantPool;
void write(uint8_t byte, int lineNumber);
int addConstant(Value constant);
// debugging functionality
void disassemble(const std::string &chunkName);
int disassembleInstruction(int offset);
int disassembleSimpleInstruction(const std::string &name, int offset);
int disassembleConstantInstruction(const std::string &name, int offset);
};
} // namespace lox | 27.52381 | 76 | 0.719723 | [
"vector"
] |
d319f9e9a7ff37e1ba2a6458ab50e7a1a5570a64 | 4,427 | cpp | C++ | DT3Core/Types/FileBuffer/FileHandleCompressedFD.cpp | nemerle/DT3 | 801615d507eda9764662f3a34339aa676170e93a | [
"MIT"
] | 3 | 2016-01-27T13:17:18.000Z | 2019-03-19T09:18:25.000Z | DT3Core/Types/FileBuffer/FileHandleCompressedFD.cpp | nemerle/DT3 | 801615d507eda9764662f3a34339aa676170e93a | [
"MIT"
] | 1 | 2016-01-28T14:39:49.000Z | 2016-01-28T22:12:07.000Z | DT3Core/Types/FileBuffer/FileHandleCompressedFD.cpp | adderly/DT3 | e2605be091ec903d3582e182313837cbaf790857 | [
"MIT"
] | 3 | 2016-01-25T16:44:51.000Z | 2021-01-29T19:59:45.000Z | //==============================================================================
///
/// File: FileHandleCompressedFD.cpp
///
/// Copyright (C) 2000-2014 by Smells Like Donkey Software Inc. All rights reserved.
///
/// This file is subject to the terms and conditions defined in
/// file 'LICENSE.txt', which is part of this source code package.
///
//==============================================================================
#include "DT3Core/Types/FileBuffer/FileHandleCompressedFD.hpp"
#include "DT3Core/Types/FileBuffer/FilePath.hpp"
#include "DT3Core/Types/Math/MoreMath.hpp"
#include "DT3Core/Types/Utility/Assert.hpp"
#include "DT3Core/Types/Utility/Error.hpp"
#include <fcntl.h>
#include <unistd.h>
#include <cstring>
extern "C" {
#include "zlib.h"
}
//==============================================================================
//==============================================================================
namespace DT3 {
//==============================================================================
/// Standard class constructors/destructors
//==============================================================================
FileHandleCompressedFD::FileHandleCompressedFD (void)
{
}
FileHandleCompressedFD::~FileHandleCompressedFD (void)
{
}
//==============================================================================
//==============================================================================
DTsize FileHandleCompressedFD::read (DTubyte *buffer, DTsize size)
{
if (_file_g >= static_cast<DTsize>(_data.size()))
_eof = true;
DTsize gcount = MoreMath::min( (DTsize) size, (DTsize) (_data.size() - _file_g) );
// We aren't actually reading from a file, we're reading from the decompressed buffer
::memcpy(buffer, &_data[_file_g], (size_t) gcount);
_file_g += size;
return gcount;
}
void FileHandleCompressedFD::write (const DTubyte *buffer, DTsize size)
{
ERRORMSG("This function is unsupported");
}
//==============================================================================
//==============================================================================
DTerr FileHandleCompressedFD::open_file (const FilePath &pathname, DTsize start, DTsize length, DTsize uncompressed_length)
{
DTint fd;
fd = ::open(pathname.full_path().c_str(), O_RDONLY);
if (fd < 0) {
return DT3_ERR_FILE_OPEN_FAILED;
}
_eof = false;
_file_g = 0;
set_fd(fd,start,length,uncompressed_length);
return DT3_ERR_NONE;
}
DTerr FileHandleCompressedFD::set_fd (DTint fd, DTsize start, DTsize length, DTsize uncompressed_length)
{
std::vector<DTubyte> compressed_buffer;
// Read the compressed file
compressed_buffer.resize(length);
// Read the compressed data from wherever it is in the file
::lseek(fd, start, SEEK_SET);
::read( fd, (char*) &compressed_buffer[0], (size_t) compressed_buffer.size());
// Uncompress the data
_data.resize(uncompressed_length);
// Use zlib to compress the buffer
z_stream strm;
strm.zalloc = 0;
strm.zfree = 0;
strm.next_in = reinterpret_cast<DTubyte *>(&compressed_buffer[0]);
strm.avail_in = (uInt) compressed_buffer.size();
strm.next_out = reinterpret_cast<DTubyte *>(&_data[0]);
strm.avail_out = (uInt) _data.size();
inflateInit(&strm);
DTint err;
while (strm.total_out < _data.size() && strm.total_in < compressed_buffer.size()) {
err = inflate(&strm, Z_NO_FLUSH);
ASSERT(err >= 0);
if (err == Z_STREAM_END)
break;
}
inflateEnd(&strm);
::close(fd);
return DT3_ERR_NONE;
}
void FileHandleCompressedFD::close (void)
{
// Should already be closed
}
void FileHandleCompressedFD::seek_p (DToffset p, Relative r)
{
ASSERT(0); // unsupported
}
void FileHandleCompressedFD::seek_g (DToffset g, Relative r)
{
switch (r) {
case FROM_CURRENT: _file_g += g; break;
case FROM_BEGINNING: _file_g = g; break;
case FROM_END: _file_g = _data.size() - g; break;
};
// // update Progress
// if (cache->_progress) {
// cache->_progress->update(_file_g, _data.size());
// cache->_last_update = 0;
// }
}
//==============================================================================
//==============================================================================
} // DT3
| 28.018987 | 123 | 0.52225 | [
"vector"
] |
d323795a1884ba5eab823f645226245e92cf7c54 | 4,877 | cc | C++ | src/tools/reconstruct_video.cc | h33p/libmv | fc7f41a484c3cb8df94e71b591076ab3c9e84827 | [
"MIT"
] | 1 | 2016-04-17T12:53:00.000Z | 2016-04-17T12:53:00.000Z | src/tools/reconstruct_video.cc | rgkoo/libmv-blender | cdf65edbb80d8904e2df9a20116d02546df93a81 | [
"MIT"
] | null | null | null | src/tools/reconstruct_video.cc | rgkoo/libmv-blender | cdf65edbb80d8904e2df9a20116d02546df93a81 | [
"MIT"
] | null | null | null | // Copyright (c) 2011 libmv authors.
//
// 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 <list>
#include <string>
#include "libmv/correspondence/import_matches_txt.h"
#include "libmv/correspondence/tracker.h"
#include "libmv/logging/logging.h"
#include "libmv/reconstruction/euclidean_reconstruction.h"
#include "libmv/reconstruction/export_blender.h"
#include "libmv/reconstruction/export_ply.h"
using namespace libmv;
DEFINE_string(i, "matches.txt", "Matches input file");
DEFINE_string(o, "reconstruction.py", "Reconstruction output file");
DEFINE_int32(w, 0, "Image width (px)");
DEFINE_int32(h, 0, "Image height (px)");
DEFINE_double(f, 50,
"Focale length for all the cameras (px)");
DEFINE_double(u0, 0,
"Principal point u coordinate (px)");
DEFINE_double(v0, 0,
"Principal point v coordinate (px)");
void GetFilePathExtention(const std::string &file,
std::string *path_name,
std::string *ext) {
size_t dot_pos = file.rfind (".");
if (dot_pos != std::string::npos) {
*path_name = file.substr(0, dot_pos);
*ext = file.substr(dot_pos + 1, file.length() - dot_pos - 1);
} else {
*path_name = file;
*ext = "";
}
}
int main (int argc, char *argv[]) {
std::string usage ="Estimate the camera trajectory using matches.\n";
usage += "Usage: " + std::string(argv[0]) + " -i INFILE.txt -o OUTFILE.ply.";
//usage += argv[0] + "<detector>";
gflags::SetUsageMessage(usage);
gflags::ParseCommandLineFlags(&argc, &argv, true);
// Imports matches
tracker::FeaturesGraph fg;
FeatureSet *fs = fg.CreateNewFeatureSet();
VLOG(0) << "Loading Matches file..." << std::endl;
ImportMatchesFromTxt(FLAGS_i, &fg.matches_, fs);
VLOG(0) << "Loading Matches file...[DONE]." << std::endl;
// Estimates the camera trajectory and 3D structure of the scene
int w = FLAGS_w, h = FLAGS_h;
// HACK to have the good principal point
if (FLAGS_u0 > 0)
w = 2 * (FLAGS_u0 + 0.5);
if (FLAGS_v0 > 0)
h = 2 * (FLAGS_v0 + 0.5);
// TODO(julien) put u and v as arguments of EuclideanReconstructionFromVideo
VLOG(0) << "Euclidean Reconstruction From Video..." << std::endl;
std::list<Reconstruction *> reconstructions;
EuclideanReconstructionFromVideo(fg.matches_,
w, h,
FLAGS_f,
&reconstructions);
VLOG(0) << "Euclidean Reconstruction From Video...[DONE]" << std::endl;
// Exports the reconstructions
VLOG(0) << "Exporting Reconstructions..." << std::endl;
std::string file_path_name, file_ext;
GetFilePathExtention(FLAGS_o, &file_path_name, &file_ext);
std::transform(file_ext.begin(), file_ext.end(), file_ext.begin(), ::tolower);
int i = 0;
std::list<Reconstruction *>::iterator iter = reconstructions.begin();
if (file_ext == "ply") {
for (; iter != reconstructions.end(); ++iter) {
std::stringstream s;
if (reconstructions.size() > 1)
s << file_path_name << "-" << i << ".ply";
else
s << FLAGS_o;
ExportToPLY(**iter, s.str());
}
} else if (file_ext == "py") {
for (; iter != reconstructions.end(); ++iter) {
std::stringstream s;
if (reconstructions.size() > 1)
s << file_path_name << "-" << i << ".py";
else
s << FLAGS_o;
ExportToBlenderScript(**iter, s.str());
}
}
VLOG(0) << "Exporting Reconstructions...[DONE]" << std::endl;
// Cleaning
VLOG(0) << "Cleaning." << std::endl;
iter = reconstructions.begin();
for (; iter != reconstructions.end(); ++iter) {
(*iter)->ClearCamerasMap();
(*iter)->ClearStructuresMap();
delete *iter;
}
reconstructions.clear();
// Delete the features graph
fg.DeleteAndClear();
return 0;
}
| 36.395522 | 80 | 0.647119 | [
"transform",
"3d"
] |
d327c7bc5a758c3192d31b0cd90e1622e5043235 | 27,217 | cpp | C++ | fem/tmop_amr.cpp | pghysels/mfem | 3c1859e1d7d9d7bb35ed3a5261f15dcc24343d9a | [
"BSD-3-Clause"
] | null | null | null | fem/tmop_amr.cpp | pghysels/mfem | 3c1859e1d7d9d7bb35ed3a5261f15dcc24343d9a | [
"BSD-3-Clause"
] | null | null | null | fem/tmop_amr.cpp | pghysels/mfem | 3c1859e1d7d9d7bb35ed3a5261f15dcc24343d9a | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2010-2022, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.
#include "tmop_amr.hpp"
namespace mfem
{
using namespace mfem;
void TMOPRefinerEstimator::ComputeEstimates()
{
bool iso = false;
bool aniso = false;
if (amrmetric == 1 || amrmetric == 2 || amrmetric == 58)
{
aniso = true;
}
if (amrmetric == 55 || amrmetric == 56 || amrmetric == 77 ||
amrmetric == 315 || amrmetric == 316 || amrmetric == 321)
{
iso = true;
}
if (amrmetric == 7 || amrmetric == 9)
{
iso = true; aniso = true;
}
MFEM_VERIFY(iso || aniso, "Metric type not supported in hr-adaptivity.");
const int dim = mesh->Dimension();
const int num_ref_types = 3 + 4*(dim-2);
const int NEorig = mesh->GetNE();
aniso_flags.SetSize(NEorig);
error_estimates.SetSize(NEorig);
Vector amr_base_energy(NEorig), amr_temp_energy(NEorig);
error_estimates = 1.*std::numeric_limits<float>::max();
aniso_flags = -1;
GetTMOPRefinementEnergy(0, amr_base_energy);
for (int i = 1; i < num_ref_types+1; i++)
{
if ( dim == 2 && i < 3 && aniso != true ) { continue; }
if ( dim == 2 && i == 3 && iso != true ) { continue; }
if ( dim == 3 && i < 7 && aniso != true ) { continue; }
if ( dim == 3 && i == 7 && iso != true ) { continue; }
GetTMOPRefinementEnergy(i, amr_temp_energy);
for (int e = 0; e < NEorig; e++)
{
if ( amr_temp_energy(e) < error_estimates(e) )
{
error_estimates(e) = amr_temp_energy(e);
aniso_flags[e] = i;
}
}
}
error_estimates *= energy_scaling_factor;
if (spat_gf)
{
L2_FECollection avg_fec(0, mesh->Dimension());
FiniteElementSpace avg_fes(spat_gf->FESpace()->GetMesh(), &avg_fec);
GridFunction elem_avg(&avg_fes);
spat_gf->GetElementAverages(elem_avg);
for (int i = 0; i < amr_base_energy.Size(); i++)
{
if (elem_avg(i) < spat_gf_critical) { amr_base_energy(i) = 0.; }
}
}
error_estimates -= amr_base_energy;
error_estimates *= -1; // error = E(parent) - scaling_factor*mean(E(children))
current_sequence = mesh->GetSequence();
}
void TMOPRefinerEstimator::GetTMOPRefinementEnergy(int reftype,
Vector &el_energy_vec)
{
const FiniteElementSpace *fes = mesh->GetNodalFESpace();
const int NE = fes->GetNE();
GridFunction *xdof = mesh->GetNodes();
xdof->SetTrueVector();
xdof->SetFromTrueVector();
el_energy_vec.SetSize(NE);
el_energy_vec = std::numeric_limits<float>::max();
for (int e = 0; e < NE; e++)
{
Geometry::Type gtype = fes->GetFE(e)->GetGeomType();
DenseMatrix tr, xsplit;
IntegrationRule *irule = NULL;
if ( (gtype == Geometry::TRIANGLE && reftype > 0 && reftype < 3) ||
(gtype == Geometry::CUBE && reftype > 0 && reftype < 7) ||
(gtype == Geometry::TETRAHEDRON && reftype > 0 && reftype < 7) )
{
continue;
}
switch (gtype)
{
case Geometry::TRIANGLE:
{
int ref_access = reftype == 0 ? 0 : 1;
xdof->GetVectorValues(e, *TriIntRule[ref_access], xsplit, tr);
irule = TriIntRule[ref_access];
break;
}
case Geometry::TETRAHEDRON:
{
int ref_access = reftype == 0 ? 0 : 1;
xdof->GetVectorValues(e, *TetIntRule[ref_access], xsplit, tr);
irule = TetIntRule[ref_access];
break;
}
case Geometry::SQUARE:
{
MFEM_VERIFY(QuadIntRule[reftype], " Integration rule does not exist.");
xdof->GetVectorValues(e, *QuadIntRule[reftype], xsplit, tr);
irule = QuadIntRule[reftype];
break;
}
case Geometry::CUBE:
{
int ref_access = reftype == 0 ? 0 : 1;
xdof->GetVectorValues(e, *HexIntRule[ref_access], xsplit, tr);
irule = HexIntRule[ref_access];
break;
}
default:
MFEM_ABORT("Incompatible geometry type!");
}
xsplit.Transpose();
el_energy_vec(e) = 0.; // Re-set to 0
// The data format is xe1,xe2,..xen,ye1,ye2..yen.
// We will reformat it inside GetRefinementElementEnergy
Vector elfun(xsplit.GetData(), xsplit.NumCols()*xsplit.NumRows());
Array<NonlinearFormIntegrator*> &integs = *(nlf->GetDNFI());
TMOP_Integrator *ti = NULL;
TMOPComboIntegrator *co = NULL;
for (int i = 0; i < integs.Size(); i++)
{
ti = dynamic_cast<TMOP_Integrator *>(integs[i]);
if (ti)
{
el_energy_vec(e) = ti->GetRefinementElementEnergy(*fes->GetFE(e),
*mesh->GetElementTransformation(e),
elfun,
*irule);
}
co = dynamic_cast<TMOPComboIntegrator *>(integs[i]);
if (co)
{
Array<TMOP_Integrator *> ati = co->GetTMOPIntegrators();
for (int j = 0; j < ati.Size(); j++)
{
el_energy_vec(e) += ati[j]->GetRefinementElementEnergy(*fes->GetFE(e),
*mesh->GetElementTransformation(e),
elfun,
*irule);
}
}
}
}
}
void TMOPRefinerEstimator::SetHexIntRules()
{
HexIntRule.SetSize(1+1);
// Reftype = 0 -> original element
Mesh meshsplit = Mesh::MakeCartesian3D(1, 1, 1, Element::HEXAHEDRON);
Mesh base_mesh_copy(meshsplit);
HexIntRule[0] = SetIntRulesFromMesh(meshsplit);
meshsplit.Clear();
// Reftype = 7
for (int i = 7; i < 8; i++)
{
Array<Refinement> marked_elements;
Mesh mesh_ref(base_mesh_copy);
for (int e = 0; e < mesh_ref.GetNE(); e++)
{
marked_elements.Append(Refinement(e, i));
}
mesh_ref.GeneralRefinement(marked_elements, 1, 0);
HexIntRule[1] = SetIntRulesFromMesh(mesh_ref);
mesh_ref.Clear();
}
}
void TMOPRefinerEstimator::SetQuadIntRules()
{
QuadIntRule.SetSize(3+1);
// Reftype = 0 -> original element
Mesh meshsplit = Mesh::MakeCartesian2D(1, 1, Element::QUADRILATERAL);
Mesh base_mesh_copy(meshsplit);
QuadIntRule[0] = SetIntRulesFromMesh(meshsplit);
meshsplit.Clear();
// Reftype = 1-3
for (int i = 1; i < 4; i++)
{
Array<Refinement> marked_elements;
Mesh mesh_ref(base_mesh_copy);
for (int e = 0; e < mesh_ref.GetNE(); e++)
{
marked_elements.Append(Refinement(e, i));
}
mesh_ref.GeneralRefinement(marked_elements, 1, 0);
QuadIntRule[i] = SetIntRulesFromMesh(mesh_ref);
mesh_ref.Clear();
}
}
void TMOPRefinerEstimator::SetTriIntRules()
{
TriIntRule.SetSize(1+1);
// Reftype = 0 // original element
const int Nvert = 3, NEsplit = 1;
Mesh meshsplit(2, Nvert, NEsplit, 0, 2);
const double tri_v[3][2] =
{
{0, 0}, {1, 0}, {0, 1}
};
const int tri_e[1][3] =
{
{0, 1, 2}
};
for (int j = 0; j < Nvert; j++)
{
meshsplit.AddVertex(tri_v[j]);
}
meshsplit.AddTriangle(tri_e[0], 1);
meshsplit.FinalizeTriMesh(1, 1, true);
Mesh base_mesh_copy(meshsplit);
TriIntRule[0] = SetIntRulesFromMesh(meshsplit);
meshsplit.Clear();
// no anisotropic refinements for triangle
// Reftype = 3
for (int i = 1; i < 2; i++)
{
Array<Refinement> marked_elements;
Mesh mesh_ref(base_mesh_copy);
for (int e = 0; e < mesh_ref.GetNE(); e++)
{
marked_elements.Append(Refinement(e, i));
}
mesh_ref.GeneralRefinement(marked_elements, 1, 0);
TriIntRule[i] = SetIntRulesFromMesh(mesh_ref);
mesh_ref.Clear();
}
}
void TMOPRefinerEstimator::SetTetIntRules()
{
TetIntRule.SetSize(1+1);
// Reftype = 0 // original element
const int Nvert = 4, NEsplit = 1;
Mesh meshsplit(3, Nvert, NEsplit, 0, 3);
const double tet_v[4][3] =
{
{0, 0, 0}, {1, 0, 0}, {0, 1, 0}, {0, 0, 1}
};
const int tet_e[1][4] =
{
{0, 1, 2, 3}
};
for (int j = 0; j < Nvert; j++)
{
meshsplit.AddVertex(tet_v[j]);
}
meshsplit.AddTet(tet_e[0], 1);
meshsplit.FinalizeTetMesh(1, 1, true);
Mesh base_mesh_copy(meshsplit);
TetIntRule[0] = SetIntRulesFromMesh(meshsplit);
meshsplit.Clear();
// no anisotropic refinements for triangle
// Reftype = 7
for (int i = 1; i < 2; i++)
{
Array<Refinement> marked_elements;
Mesh mesh_ref(base_mesh_copy);
for (int e = 0; e < mesh_ref.GetNE(); e++)
{
marked_elements.Append(Refinement(e, i)); // ref_type will default to 7
}
mesh_ref.GeneralRefinement(marked_elements, 1, 0);
TetIntRule[i] = SetIntRulesFromMesh(mesh_ref);
mesh_ref.Clear();
}
}
IntegrationRule* TMOPRefinerEstimator::SetIntRulesFromMesh(Mesh &meshsplit)
{
const int dim = meshsplit.Dimension();
H1_FECollection fec(order, dim);
FiniteElementSpace nodal_fes(&meshsplit, &fec, dim);
meshsplit.SetNodalFESpace(&nodal_fes);
const int NEsplit = meshsplit.GetNE();
const int dof_cnt = nodal_fes.GetFE(0)->GetDof(),
pts_cnt = NEsplit * dof_cnt;
DenseMatrix pos(dof_cnt, dim);
Vector posV(pos.Data(), dof_cnt * dim);
Array<int> xdofs(dof_cnt * dim);
// Create an IntegrationRule on the nodes of the reference submesh.
IntegrationRule *irule = new IntegrationRule(pts_cnt);
GridFunction *nodesplit = meshsplit.GetNodes();
int pt_id = 0;
for (int i = 0; i < NEsplit; i++)
{
nodal_fes.GetElementVDofs(i, xdofs);
nodesplit->GetSubVector(xdofs, posV);
for (int j = 0; j < dof_cnt; j++)
{
if (dim == 2)
{
irule->IntPoint(pt_id).Set2(pos(j, 0), pos(j, 1));
}
else if (dim == 3)
{
irule->IntPoint(pt_id).Set3(pos(j, 0), pos(j, 1), pos(j, 2));
}
pt_id++;
}
}
return irule;
}
bool TMOPDeRefinerEstimator::GetDerefineEnergyForIntegrator(
TMOP_Integrator &tmopi,
Vector &fine_energy)
{
DiscreteAdaptTC *tcd = tmopi.GetDiscreteAdaptTC();
fine_energy.SetSize(mesh->GetNE());
if (serial)
{
Mesh meshcopy(*mesh);
FiniteElementSpace *tcdfes = NULL;
if (tcd)
{
tcdfes = new FiniteElementSpace(*tcd->GetTSpecFESpace(), &meshcopy);
}
Vector local_err(meshcopy.GetNE());
local_err = 0.;
double threshold = std::numeric_limits<float>::max();
meshcopy.DerefineByError(local_err, threshold, 0, 1);
if (meshcopy.GetGlobalNE() == mesh->GetGlobalNE())
{
delete tcdfes;
return false;
}
if (tcd)
{
tcdfes->Update();
tcd->SetTspecDataForDerefinement(tcdfes);
}
Vector coarse_energy(meshcopy.GetNE());
GetTMOPDerefinementEnergy(meshcopy, tmopi, coarse_energy);
if (tcd) { tcd->ResetDerefinementTspecData(); }
GetTMOPDerefinementEnergy(*mesh, tmopi, fine_energy);
const CoarseFineTransformations &dtrans =
meshcopy.ncmesh->GetDerefinementTransforms();
Table coarse_to_fine;
dtrans.MakeCoarseToFineTable(coarse_to_fine);
Array<int> tabrow;
for (int pe = 0; pe < coarse_to_fine.Size(); pe++)
{
coarse_to_fine.GetRow(pe, tabrow);
int nchild = tabrow.Size();
double parent_energy = coarse_energy(pe);
for (int fe = 0; fe < nchild; fe++)
{
int child = tabrow[fe];
MFEM_VERIFY(child < mesh->GetNE(), " invalid coarse to fine mapping");
fine_energy(child) -= parent_energy;
}
}
delete tcdfes;
}
else
{
#ifdef MFEM_USE_MPI
ParMesh meshcopy(*pmesh);
ParFiniteElementSpace *tcdfes = NULL;
if (tcd)
{
tcdfes = new ParFiniteElementSpace(*tcd->GetTSpecParFESpace(), meshcopy);
}
Vector local_err(meshcopy.GetNE());
local_err = 0.;
double threshold = std::numeric_limits<float>::max();
meshcopy.DerefineByError(local_err, threshold, 0, 1);
if (meshcopy.GetGlobalNE() == pmesh->GetGlobalNE())
{
delete tcdfes;
return false;
}
if (tcd)
{
tcdfes->Update();
tcd->SetTspecDataForDerefinement(tcdfes);
}
Vector coarse_energy(meshcopy.GetNE());
GetTMOPDerefinementEnergy(meshcopy, tmopi, coarse_energy);
if (tcd) { tcd->ResetDerefinementTspecData(); }
GetTMOPDerefinementEnergy(*pmesh, tmopi, fine_energy);
const CoarseFineTransformations &dtrans =
meshcopy.pncmesh->GetDerefinementTransforms();
Table coarse_to_fine;
dtrans.MakeCoarseToFineTable(coarse_to_fine);
Array<int> tabrow;
for (int pe = 0; pe < meshcopy.GetNE(); pe++)
{
coarse_to_fine.GetRow(pe, tabrow);
int nchild = tabrow.Size();
double parent_energy = coarse_energy(pe);
for (int fe = 0; fe < nchild; fe++)
{
int child = tabrow[fe];
MFEM_VERIFY(child < pmesh->GetNE(), " invalid coarse to fine mapping");
fine_energy(child) -= parent_energy;
}
}
delete tcdfes;
#endif
}
// error_estimate(e) = energy(parent_of_e)-energy(e)
// Negative energy means derefinement is desirable.
fine_energy *= -1;
return true;
}
void TMOPDeRefinerEstimator::ComputeEstimates()
{
Array<NonlinearFormIntegrator*> &integs = *(nlf->GetDNFI());
TMOP_Integrator *ti = NULL;
TMOPComboIntegrator *co = NULL;
error_estimates.SetSize(mesh->GetNE());
error_estimates = 0.;
Vector fine_energy(mesh->GetNE());
for (int i = 0; i < integs.Size(); i++)
{
ti = dynamic_cast<TMOP_Integrator *>(integs[i]);
if (ti)
{
bool deref = GetDerefineEnergyForIntegrator(*ti, fine_energy);
if (!deref) { error_estimates = 1; return; }
error_estimates += fine_energy;
}
co = dynamic_cast<TMOPComboIntegrator *>(integs[i]);
if (co)
{
Array<TMOP_Integrator *> ati = co->GetTMOPIntegrators();
for (int j = 0; j < ati.Size(); j++)
{
bool deref = GetDerefineEnergyForIntegrator(*ati[j], fine_energy);
if (!deref) { error_estimates = 1; return; }
error_estimates += fine_energy;
}
}
}
}
void TMOPDeRefinerEstimator::GetTMOPDerefinementEnergy(Mesh &cmesh,
TMOP_Integrator &tmopi,
Vector &el_energy_vec)
{
const int cNE = cmesh.GetNE();
el_energy_vec.SetSize(cNE);
const FiniteElementSpace *fespace = cmesh.GetNodalFESpace();
GridFunction *cxdof = cmesh.GetNodes();
Array<int> vdofs;
Vector el_x;
const FiniteElement *fe;
ElementTransformation *T;
for (int j = 0; j < cNE; j++)
{
fe = fespace->GetFE(j);
fespace->GetElementVDofs(j, vdofs);
T = cmesh.GetElementTransformation(j);
cxdof->GetSubVector(vdofs, el_x);
el_energy_vec(j) = tmopi.GetDerefinementElementEnergy(*fe, *T, el_x);
}
}
TMOPHRSolver::TMOPHRSolver(Mesh &mesh_, NonlinearForm &nlf_,
TMOPNewtonSolver &tmopns_, GridFunction &x_,
bool move_bnd_, bool hradaptivity_,
int mesh_poly_deg_, int amr_metric_id_,
int hr_iter_, int h_per_r_iter_) :
mesh(&mesh_), nlf(&nlf_), tmopns(&tmopns_), x(&x_),
gridfuncarr(), fespacearr(),
move_bnd(move_bnd_), hradaptivity(hradaptivity_),
mesh_poly_deg(mesh_poly_deg_), amr_metric_id(amr_metric_id_),
serial(true), hr_iter(hr_iter_), h_per_r_iter(h_per_r_iter_)
{
if (!hradaptivity) { return; }
tmop_r_est = new TMOPRefinerEstimator(*mesh, *nlf, mesh_poly_deg,
amr_metric_id);
tmop_r = new ThresholdRefiner(*tmop_r_est);
tmop_r->SetTotalErrorFraction(0.0);
tmop_r_est->SetEnergyScalingFactor(1.);
tmop_dr_est= new TMOPDeRefinerEstimator(*mesh, *nlf);
tmop_dr = new ThresholdDerefiner(*tmop_dr_est);
AddGridFunctionForUpdate(x);
}
#ifdef MFEM_USE_MPI
TMOPHRSolver::TMOPHRSolver(ParMesh &pmesh_, ParNonlinearForm &pnlf_,
TMOPNewtonSolver &tmopns_, ParGridFunction &px_,
bool move_bnd_, bool hradaptivity_,
int mesh_poly_deg_, int amr_metric_id_,
int hr_iter_, int h_per_r_iter_) :
mesh(&pmesh_), nlf(&pnlf_), tmopns(&tmopns_), x(&px_),
gridfuncarr(), fespacearr(),
move_bnd(move_bnd_), hradaptivity(hradaptivity_),
mesh_poly_deg(mesh_poly_deg_), amr_metric_id(amr_metric_id_),
pmesh(&pmesh_), pnlf(&pnlf_), pgridfuncarr(), pfespacearr(),
serial(false), hr_iter(hr_iter_), h_per_r_iter(h_per_r_iter_)
{
if (!hradaptivity) { return; }
tmop_r_est = new TMOPRefinerEstimator(*pmesh, *pnlf, mesh_poly_deg,
amr_metric_id);
tmop_r = new ThresholdRefiner(*tmop_r_est);
tmop_r->SetTotalErrorFraction(0.0);
tmop_r_est->SetEnergyScalingFactor(1.);
tmop_dr_est= new TMOPDeRefinerEstimator(*pmesh, *pnlf);
tmop_dr = new ThresholdDerefiner(*tmop_dr_est);
AddGridFunctionForUpdate(&px_);
}
#endif
void TMOPHRSolver::Mult()
{
Vector b(0);
int myid = 0;
if (serial)
{
tmopns->SetOperator(*nlf);
}
else
{
#ifdef MFEM_USE_MPI
myid = pnlf->ParFESpace()->GetMyRank();
tmopns->SetOperator(*pnlf);
#endif
}
if (!hradaptivity)
{
tmopns->Mult(b, x->GetTrueVector());
if (tmopns->GetConverged() == false)
{
if (myid == 0) { mfem::out << "Nonlinear solver: rtol not achieved.\n"; }
}
x->SetFromTrueVector();
return;
}
bool radaptivity = true;
tmop_dr->Reset();
tmop_r->Reset();
if (serial)
{
for (int i_hr = 0; i_hr < hr_iter; i_hr++)
{
if (!radaptivity)
{
break;
}
mfem::out << i_hr << " r-adaptivity iteration.\n";
tmopns->SetOperator(*nlf);
tmopns->Mult(b, x->GetTrueVector());
x->SetFromTrueVector();
mfem::out << "TMOP energy after r-adaptivity: " <<
nlf->GetGridFunctionEnergy(*x)/mesh->GetNE() <<
", Elements: " << mesh->GetNE() << std::endl;
for (int i_h = 0; i_h < h_per_r_iter; i_h++)
{
// Derefinement step.
if (mesh->ncmesh)
{
tmop_dr->Apply(*mesh);
Update();
}
mfem::out << "TMOP energy after derefinement: " <<
nlf->GetGridFunctionEnergy(*x)/mesh->GetNE() <<
", Elements: " << mesh->GetNE() << std::endl;
// Refinement step.
tmop_r->Apply(*mesh);
Update();
mfem::out << "TMOP energy after refinement: " <<
nlf->GetGridFunctionEnergy(*x)/mesh->GetNE() <<
", Elements: " << mesh->GetNE() << std::endl;
if (!tmop_dr->Derefined() && tmop_r->Stop())
{
radaptivity = false;
mfem::out << "AMR stopping criterion satisfied. Stop.\n";
break;
}
} //n_h
} //n_hr
}
else
{
#ifdef MFEM_USE_MPI
int NEGlob;
double tmopenergy;
for (int i_hr = 0; i_hr < hr_iter; i_hr++)
{
if (!radaptivity)
{
break;
}
if (myid == 0) { mfem::out << i_hr << " r-adaptivity iteration.\n"; }
tmopns->SetOperator(*pnlf);
tmopns->Mult(b, x->GetTrueVector());
x->SetFromTrueVector();
NEGlob = pmesh->GetGlobalNE();
tmopenergy = pnlf->GetParGridFunctionEnergy(*x) / NEGlob;
if (myid == 0)
{
mfem::out << "TMOP energy after r-adaptivity: " << tmopenergy <<
", Elements: " << NEGlob << std::endl;
}
for (int i_h = 0; i_h < h_per_r_iter; i_h++)
{
// Derefinement step.
if (pmesh->pncmesh)
{
RebalanceParNCMesh();
ParUpdate();
tmop_dr->Apply(*pmesh);
ParUpdate();
}
NEGlob = pmesh->GetGlobalNE();
tmopenergy = pnlf->GetParGridFunctionEnergy(*x) / NEGlob;
if (myid == 0)
{
mfem::out << "TMOP energy after derefinement: " << tmopenergy <<
", Elements: " << NEGlob << std::endl;
}
// Refinement step.
tmop_r->Apply(*pmesh);
ParUpdate();
NEGlob = pmesh->GetGlobalNE();
tmopenergy = pnlf->GetParGridFunctionEnergy(*x) / NEGlob;
if (myid == 0)
{
mfem::out << "TMOP energy after refinement: " << tmopenergy <<
", Elements: " << NEGlob << std::endl;
}
if (!tmop_dr->Derefined() && tmop_r->Stop())
{
radaptivity = false;
if (myid == 0)
{
mfem::out << "AMR stopping criterion satisfied. Stop.\n";
}
break;
}
} // n_r limit
} // n_hr
#endif
}
}
#ifdef MFEM_USE_MPI
void TMOPHRSolver::RebalanceParNCMesh()
{
ParNCMesh *pncmesh = pmesh->pncmesh;
if (pncmesh)
{
const Table &dreftable = pncmesh->GetDerefinementTable();
Array<int> drefs, new_ranks;
for (int i = 0; i < dreftable.Size(); i++)
{
drefs.Append(i);
}
pncmesh->GetFineToCoarsePartitioning(drefs, new_ranks);
pmesh->Rebalance(new_ranks);
}
}
#endif
void TMOPHRSolver::Update()
{
// Update FESpace
for (int i = 0; i < fespacearr.Size(); i++)
{
fespacearr[i]->Update();
}
// Update nodal GF
for (int i = 0; i < gridfuncarr.Size(); i++)
{
gridfuncarr[i]->Update();
gridfuncarr[i]->SetTrueVector();
gridfuncarr[i]->SetFromTrueVector();
}
// Update Discrete Indicator for all the TMOP_Integrators in NonLinearForm
Array<NonlinearFormIntegrator*> &integs = *(nlf->GetDNFI());
TMOP_Integrator *ti = NULL;
TMOPComboIntegrator *co = NULL;
DiscreteAdaptTC *dtc = NULL;
for (int i = 0; i < integs.Size(); i++)
{
ti = dynamic_cast<TMOP_Integrator *>(integs[i]);
if (ti)
{
ti->UpdateAfterMeshTopologyChange();
dtc = ti->GetDiscreteAdaptTC();
if (dtc) { dtc->UpdateAfterMeshTopologyChange(); }
}
co = dynamic_cast<TMOPComboIntegrator *>(integs[i]);
if (co)
{
Array<TMOP_Integrator *> ati = co->GetTMOPIntegrators();
for (int j = 0; j < ati.Size(); j++)
{
ati[j]->UpdateAfterMeshTopologyChange();
dtc = ati[j]->GetDiscreteAdaptTC();
if (dtc) { dtc->UpdateAfterMeshTopologyChange(); }
}
}
}
// Update the Nonlinear form and set Essential BC.
UpdateNonlinearFormAndBC(mesh, nlf);
}
#ifdef MFEM_USE_MPI
void TMOPHRSolver::ParUpdate()
{
// Update FESpace
for (int i = 0; i < pfespacearr.Size(); i++)
{
pfespacearr[i]->Update();
}
// Update nodal GF
for (int i = 0; i < pgridfuncarr.Size(); i++)
{
pgridfuncarr[i]->Update();
pgridfuncarr[i]->SetTrueVector();
pgridfuncarr[i]->SetFromTrueVector();
}
// Update Discrete Indicator
Array<NonlinearFormIntegrator*> &integs = *(nlf->GetDNFI());
TMOP_Integrator *ti = NULL;
TMOPComboIntegrator *co = NULL;
DiscreteAdaptTC *dtc = NULL;
for (int i = 0; i < integs.Size(); i++)
{
ti = dynamic_cast<TMOP_Integrator *>(integs[i]);
if (ti)
{
ti->ParUpdateAfterMeshTopologyChange();
dtc = ti->GetDiscreteAdaptTC();
if (dtc) { dtc->ParUpdateAfterMeshTopologyChange(); }
}
co = dynamic_cast<TMOPComboIntegrator *>(integs[i]);
if (co)
{
Array<TMOP_Integrator *> ati = co->GetTMOPIntegrators();
for (int j = 0; j < ati.Size(); j++)
{
ati[j]->ParUpdateAfterMeshTopologyChange();
dtc = ati[j]->GetDiscreteAdaptTC();
if (dtc) { dtc->ParUpdateAfterMeshTopologyChange(); }
}
}
}
// Update the Nonlinear form and set Essential BC.
UpdateNonlinearFormAndBC(pmesh, pnlf);
}
#endif
void TMOPHRSolver::UpdateNonlinearFormAndBC(Mesh *mesh_, NonlinearForm *nlf_)
{
const FiniteElementSpace &fes = *mesh_->GetNodalFESpace();
// Update Nonlinear form and Set Essential BC
nlf_->Update();
const int dim = fes.GetFE(0)->GetDim();
if (move_bnd == false)
{
Array<int> ess_bdr(mesh_->bdr_attributes.Max());
ess_bdr = 1;
nlf_->SetEssentialBC(ess_bdr);
}
else
{
const int nd = fes.GetBE(0)->GetDof();
int n = 0;
for (int i = 0; i < mesh_->GetNBE(); i++)
{
const int attr = mesh_->GetBdrElement(i)->GetAttribute();
MFEM_VERIFY(!(dim == 2 && attr == 3),
"Boundary attribute 3 must be used only for 3D meshes. "
"Adjust the attributes (1/2/3/4 for fixed x/y/z/all "
"components, rest for free nodes), or use -fix-bnd.");
if (attr == 1 || attr == 2 || attr == 3) { n += nd; }
if (attr == 4) { n += nd * dim; }
}
Array<int> ess_vdofs(n), vdofs;
n = 0;
for (int i = 0; i < mesh_->GetNBE(); i++)
{
const int attr = mesh_->GetBdrElement(i)->GetAttribute();
fes.GetBdrElementVDofs(i, vdofs);
if (attr == 1) // Fix x components.
{
for (int j = 0; j < nd; j++)
{ ess_vdofs[n++] = vdofs[j]; }
}
else if (attr == 2) // Fix y components.
{
for (int j = 0; j < nd; j++)
{ ess_vdofs[n++] = vdofs[j+nd]; }
}
else if (attr == 3) // Fix z components.
{
for (int j = 0; j < nd; j++)
{ ess_vdofs[n++] = vdofs[j+2*nd]; }
}
else if (attr == 4) // Fix all components.
{
for (int j = 0; j < vdofs.Size(); j++)
{ ess_vdofs[n++] = vdofs[j]; }
}
}
nlf_->SetEssentialVDofs(ess_vdofs);
}
}
}
| 30.27475 | 105 | 0.557923 | [
"mesh",
"geometry",
"vector",
"3d"
] |
d329a07a07c9cd56f2c6f29a83f1b63f7ceaffa7 | 17,134 | cpp | C++ | src/ramen/core/queue.cpp | helixd2s/Ramen | 5b1ebcfdc796b2276b607e71e09c5842d0c52933 | [
"MIT"
] | 4 | 2021-05-13T21:12:09.000Z | 2022-01-26T18:24:30.000Z | src/ramen/core/queue.cpp | helixd2s/Ramen | 5b1ebcfdc796b2276b607e71e09c5842d0c52933 | [
"MIT"
] | null | null | null | src/ramen/core/queue.cpp | helixd2s/Ramen | 5b1ebcfdc796b2276b607e71e09c5842d0c52933 | [
"MIT"
] | null | null | null | #pragma once
#include <ramen/core/core.hpp>
#include <ramen/core/device.hpp>
#include <ramen/core/queue.hpp>
#include <ramen/core/memory.hpp>
#include <ramen/core/consumer.hpp>
#include <ramen/core/keyed.hpp>
#include <ramen/core/commandBuffer.hpp>
//
namespace rmc {
//
vk::Buffer QueueObject::createUniform( uintptr_t const& allocatorId) {
const uint32_t size = 65536u;
auto info = std::dynamic_pointer_cast<vkh::QueueCreateHelper>(this->info);
auto& device = (vk::Device&)(this->base);
auto deviceObj = InstanceObject::context->get<DeviceObject>(this->base);
auto& queueFamilyIndex = this->base.family;
auto queueFamilyObj = InstanceObject::context->getRaw<QueueFamilyObject>(queueFamilyIndex, HandleType::eQueueFamily);
//
this->uniformBuffer = BufferRegion{ deviceObj->getRaw<MemoryAllocatorObject>(allocatorId, HandleType::eMemoryAllocator)->allocateAndCreateBuffer(std::make_shared<vkh::BufferCreateHelper>(vk::BufferCreateInfo{
.size = size,
.usage = vk::BufferUsageFlagBits::eTransferDst | vk::BufferUsageFlagBits::eUniformBuffer
}, MemoryAllocationInfo{.memoryUsage = MemoryUsage::eGPUOnly })), 0ull, size };
//
std::vector<uint32_t> counts = { 1u };
vk::DescriptorSetVariableDescriptorCountAllocateInfo variable = {};
variable.setDescriptorCounts(counts);
//
std::vector<vk::DescriptorSetLayout> layouts = { deviceObj->defaultLayouts->uniforms };
this->descriptorSet = device.allocateDescriptorSets(vk::DescriptorSetAllocateInfo{ .pNext = &variable, .descriptorPool = deviceObj->descriptorPool }.setSetLayouts(layouts))[0u];
//
device.updateDescriptorSets(std::vector<vk::WriteDescriptorSet>{
vk::WriteDescriptorSet{.dstSet = this->descriptorSet, .dstBinding = 0u, .descriptorCount = 1u, .descriptorType = vk::DescriptorType::eUniformBuffer}.setBufferInfo(reinterpret_cast<vk::DescriptorBufferInfo&>(this->uniformBuffer))
}, nullptr);
//
return this->uniformBuffer.buffer;
};
//
vk::Fence QueueObject::submitCmds( std::vector<vk::CommandBuffer> const& commandBuffers, vk::SubmitInfo2KHR submitInfo) const {
if (commandBuffers.size() <= 0) return vk::Fence{};
//
auto info = std::dynamic_pointer_cast<vkh::QueueCreateHelper>(this->info);
auto& device = (vk::Device&)(this->base);
auto deviceObj = InstanceObject::context->get<DeviceObject>(this->base);
auto fence = device.createFence(vk::FenceCreateInfo{});
auto& queueFamilyIndex = this->base.family;
auto queueFamilyObj = InstanceObject::context->getRaw<QueueFamilyObject>(queueFamilyIndex, HandleType::eQueueFamily);
auto& queue = (vk::Queue&)(this->handle);
//
std::vector<vk::CommandBufferSubmitInfoKHR> commandInfos = {};
for (auto& commandBuffer : commandBuffers) {
commandInfos.push_back(vk::CommandBufferSubmitInfoKHR{
.commandBuffer = commandBuffer,
.deviceMask = 0x0u
});
};
//
submitInfo.commandBufferInfoCount = commandInfos.size();
submitInfo.pCommandBufferInfos = commandInfos.data();
//
queue.submit2KHR(submitInfo, fence, deviceObj->dispatch);
const_cast<LimitedList<vk::Fence,16u>&>(this->fences).push_back(fence);
// resolved: submission is confirmation!
for (auto& cmd : commandBuffers) {
auto commandBufferObj = InstanceObject::context->getRaw<OnceCommandBufferObject>(cmd);
if (commandBufferObj) { commandBufferObj->confirmSubmission(); };
};
//
return fence;
};
//
vk::Fence QueueObject::submitCmds( vk::SubmitInfo2KHR const& submitInfo) {
auto data = this;
auto fence = this->submitCmds(data->commandBuffers, submitInfo);
for (auto& commandBuffer : data->commandBuffers) {
};
data->commandBuffers = {};
return fence;
};
//
Fence QueueObject::copyDeviceBuffers( BufferRegion const& srcInfo, BufferRegion const& dstInfo, vk::SubmitInfo2KHR const& submitInfo, Callback onresult) const {
auto info = std::dynamic_pointer_cast<vkh::QueueCreateHelper>(this->info);
auto& device = (vk::Device&)(this->base);
auto deviceObj = InstanceObject::context->get<DeviceObject>(this->base);
auto& queueFamilyIndex = this->base.family;
auto queueFamilyObj = InstanceObject::context->getRaw<QueueFamilyObject>(queueFamilyIndex, HandleType::eQueueFamily);
return this->submitOnce([srcInfo, dstInfo, dispatch = deviceObj->dispatch]( vk::CommandBuffer const& cmd) {
auto cmdObj = InstanceObject::context->getRaw<OnceCommandBufferObject>(cmd);
vk::BufferCopy2KHR bufferCopy = {
.srcOffset = srcInfo.offset,
.dstOffset = dstInfo.offset,
.size = std::min(srcInfo.range, dstInfo.range)
};
cmd.copyBuffer2KHR(vk::CopyBufferInfo2KHR{
.srcBuffer = srcInfo.buffer,
.dstBuffer = dstInfo.buffer,
.regionCount = 1,
.pRegions = &bufferCopy
}, dispatch);
auto dstMask = rmc::BarrierInfo{
.accessMask = vk::AccessFlagBits2KHR::eMemoryWrite | vk::AccessFlagBits2KHR::eTransferWrite | vk::AccessFlagBits2KHR::eShaderWrite | vk::AccessFlagBits2KHR::eMemoryRead | vk::AccessFlagBits2KHR::eShaderRead | vk::AccessFlagBits2KHR::eTransferRead | vk::AccessFlagBits2KHR::eNone,
.stageMask = vk::PipelineStageFlagBits2KHR::eAllCommands
};
auto srcMemoryBarrier = rmc::MemoryBarrierInfo{
.src = rmc::BarrierInfo{
.accessMask = vk::AccessFlagBits2KHR::eMemoryRead | vk::AccessFlagBits2KHR::eTransferRead,
.stageMask = vk::PipelineStageFlagBits2KHR::eTransfer | vk::PipelineStageFlagBits2KHR::eCopy
},
.dst = dstMask
};
auto dstMemoryBarrier = rmc::MemoryBarrierInfo{
.src = rmc::BarrierInfo{
.accessMask = vk::AccessFlagBits2KHR::eMemoryWrite | vk::AccessFlagBits2KHR::eTransferWrite,
.stageMask = vk::PipelineStageFlagBits2KHR::eTransfer | vk::PipelineStageFlagBits2KHR::eCopy
},
.dst = dstMask
};
cmdObj->memoryBarrierVector(srcInfo, rmc::BufferMemoryBarrierInfo{ .memoryBarrier = &srcMemoryBarrier });
cmdObj->memoryBarrierVector(dstInfo, rmc::BufferMemoryBarrierInfo{ .memoryBarrier = &dstMemoryBarrier });
cmdObj->applyBarrier();
}, submitInfo, onresult);
};
//
Fence QueueObject::copyDeviceBufferToImage( BufferRegion const& srcInfo, ImageMipLayers const& dstInfo, ImageRegion const& dstRegion, vk::SubmitInfo2KHR const& submitInfo, Callback onresult) const {
auto info = std::dynamic_pointer_cast<vkh::QueueCreateHelper>(this->info);
auto& device = (vk::Device&)(this->base);
auto deviceObj = InstanceObject::context->get<DeviceObject>(this->base);
auto& queueFamilyIndex = this->base.family;
auto queueFamilyObj = InstanceObject::context->getRaw<QueueFamilyObject>(queueFamilyIndex, HandleType::eQueueFamily);
return this->submitOnce([deviceObj, srcInfo, dstInfo, dstRegion, dispatch = deviceObj->dispatch](const vk::CommandBuffer& cmd) {
auto cmdObj = InstanceObject::context->getRaw<OnceCommandBufferObject>(cmd);
auto image = deviceObj->getRaw<ImageObject>(dstInfo.image);
//auto data = std::dynamic_pointer_cast<ImageData>(image->data);//mipLayers
auto mipLayers = image->mipLayers[dstInfo.subresourceLayers.mipLevel].find(dstInfo.subresourceLayers.baseArrayLayer);
auto imageLayout = (dstInfo.imageLayout != vk::ImageLayout::eUndefined ? dstInfo.imageLayout : (image->info ? std::dynamic_pointer_cast<vkh::ImageCreateHelper > (image->info)->value().initialLayout : vk::ImageLayout::eUndefined));
//
if (mipLayers) {
auto imageLayoutRef = mipLayers.value().memoryBarrierHistory.size() > 0 ? mipLayers.value().memoryBarrierHistory.back().imageLayout : imageLayout;
imageLayout = dstInfo.imageLayout != vk::ImageLayout::eUndefined ? dstInfo.imageLayout : (imageLayoutRef ? imageLayoutRef.value() : imageLayout);
};
//
vk::BufferImageCopy2KHR bufferImageCopy = {
.bufferOffset = srcInfo.offset,
.imageSubresource = dstInfo.subresourceLayers,
.imageOffset = (vk::Offset3D&)dstRegion.offset,
.imageExtent = (vk::Extent3D&)dstRegion.extent
};
cmd.copyBufferToImage2KHR(vk::CopyBufferToImageInfo2KHR{
.srcBuffer = srcInfo.buffer,
.dstImage = dstInfo.image,
.dstImageLayout = imageLayout, // TODO: optional image layout
.regionCount = 1,
.pRegions = &bufferImageCopy
}, dispatch);
auto dstMask = rmc::BarrierInfo{
.accessMask = vk::AccessFlagBits2KHR::eMemoryWrite | vk::AccessFlagBits2KHR::eTransferWrite | vk::AccessFlagBits2KHR::eShaderWrite | vk::AccessFlagBits2KHR::eMemoryRead | vk::AccessFlagBits2KHR::eShaderRead | vk::AccessFlagBits2KHR::eTransferRead | vk::AccessFlagBits2KHR::eNone,
.stageMask = vk::PipelineStageFlagBits2KHR::eAllCommands
};
auto srcMemoryBarrier = rmc::MemoryBarrierInfo{
.src = rmc::BarrierInfo{
.accessMask = vk::AccessFlagBits2KHR::eMemoryRead | vk::AccessFlagBits2KHR::eTransferRead,
.stageMask = vk::PipelineStageFlagBits2KHR::eTransfer | vk::PipelineStageFlagBits2KHR::eCopy
},
.dst = dstMask
};
auto dstMemoryBarrier = rmc::MemoryBarrierInfo{
.src = rmc::BarrierInfo{
.accessMask = vk::AccessFlagBits2KHR::eMemoryWrite | vk::AccessFlagBits2KHR::eTransferWrite,
.stageMask = vk::PipelineStageFlagBits2KHR::eTransfer | vk::PipelineStageFlagBits2KHR::eCopy
},
.dst = dstMask
};
cmdObj->memoryBarrierVector(srcInfo, rmc::BufferMemoryBarrierInfo{ .memoryBarrier = &srcMemoryBarrier });
cmdObj->memoryBarrierMipLayers(dstInfo, rmc::ImageMemoryBarrierInfo{ .memoryBarrier = &dstMemoryBarrier });
cmdObj->applyBarrier();
}, submitInfo, onresult);
};
//
Fence QueueObject::copyDeviceImageToBuffer( ImageMipLayers const& srcInfo, ImageRegion const& srcRegion, BufferRegion const& dstInfo, vk::SubmitInfo2KHR const& submitInfo, Callback onresult) const {
auto info = std::dynamic_pointer_cast<vkh::QueueCreateHelper>(this->info);
auto& device = (vk::Device&)(this->base);
auto deviceObj = InstanceObject::context->get<DeviceObject>(this->base);
auto& queueFamilyIndex = this->base.family;
auto queueFamilyObj = InstanceObject::context->getRaw<QueueFamilyObject>(queueFamilyIndex, HandleType::eQueueFamily);
return this->submitOnce([deviceObj, srcInfo, dstInfo, srcRegion, dispatch = deviceObj->dispatch](const vk::CommandBuffer& cmd) {
auto cmdObj = InstanceObject::context->getRaw<OnceCommandBufferObject>(cmd);
auto image = deviceObj->getRaw<ImageObject>(srcInfo.image);
//auto data = std::dynamic_pointer_cast<ImageData>(image->data);//mipLayers
auto mipLayers = image->mipLayers[srcInfo.subresourceLayers.mipLevel].find(srcInfo.subresourceLayers.baseArrayLayer);
auto imageLayout = (srcInfo.imageLayout != vk::ImageLayout::eUndefined ? srcInfo.imageLayout: (image->info ? std::dynamic_pointer_cast<vkh::ImageCreateHelper>(image->info)->value().initialLayout : vk::ImageLayout::eUndefined));
//
if (mipLayers) {
auto imageLayoutRef = mipLayers.value().memoryBarrierHistory.size() > 0 ? mipLayers.value().memoryBarrierHistory.back().imageLayout : imageLayout;
imageLayout = srcInfo.imageLayout != vk::ImageLayout::eUndefined ? srcInfo.imageLayout : (imageLayoutRef ? imageLayoutRef.value() : imageLayout);
};
//
vk::BufferImageCopy2KHR bufferImageCopy = {
.bufferOffset = dstInfo.offset,
.imageSubresource = srcInfo.subresourceLayers,
.imageOffset = (vk::Offset3D&)srcRegion.offset,
.imageExtent = (vk::Extent3D&)srcRegion.extent
};
cmd.copyImageToBuffer2KHR(vk::CopyImageToBufferInfo2KHR{
.srcImage = srcInfo.image,
.srcImageLayout = imageLayout, // TODO: optional image layout
.dstBuffer = dstInfo.buffer,
.regionCount = 1,
.pRegions = &bufferImageCopy
}, dispatch);
auto dstMask = rmc::BarrierInfo{
.accessMask = vk::AccessFlagBits2KHR::eMemoryWrite | vk::AccessFlagBits2KHR::eTransferWrite | vk::AccessFlagBits2KHR::eShaderWrite | vk::AccessFlagBits2KHR::eMemoryRead | vk::AccessFlagBits2KHR::eShaderRead | vk::AccessFlagBits2KHR::eTransferRead | vk::AccessFlagBits2KHR::eNone,
.stageMask = vk::PipelineStageFlagBits2KHR::eAllCommands
};
auto srcMemoryBarrier = rmc::MemoryBarrierInfo{
.src = rmc::BarrierInfo{
.accessMask = vk::AccessFlagBits2KHR::eMemoryRead | vk::AccessFlagBits2KHR::eTransferRead,
.stageMask = vk::PipelineStageFlagBits2KHR::eTransfer | vk::PipelineStageFlagBits2KHR::eCopy
},
.dst = dstMask
};
auto dstMemoryBarrier = rmc::MemoryBarrierInfo{
.src = rmc::BarrierInfo{
.accessMask = vk::AccessFlagBits2KHR::eMemoryWrite | vk::AccessFlagBits2KHR::eTransferWrite,
.stageMask = vk::PipelineStageFlagBits2KHR::eTransfer | vk::PipelineStageFlagBits2KHR::eCopy
},
.dst = dstMask
};
cmdObj->memoryBarrierMipLayers(srcInfo, rmc::ImageMemoryBarrierInfo{ .memoryBarrier = &srcMemoryBarrier });
cmdObj->memoryBarrierVector(dstInfo, rmc::BufferMemoryBarrierInfo{ .memoryBarrier = &dstMemoryBarrier });
cmdObj->applyBarrier();
}, submitInfo, onresult);
};
//
Fence QueueObject::submitOnce( std::function<void(vk::CommandBuffer const&)> const& cmdFn, vk::SubmitInfo2KHR const& submitInfo, Callback onresult) const {
auto info = std::dynamic_pointer_cast<vkh::QueueCreateHelper>(this->info);
auto& device = (vk::Device&)(this->base);
auto deviceObj = InstanceObject::context->get<DeviceObject>(this->base);
auto& queueFamilyIndex = this->base.family;
auto queueFamilyObj = InstanceObject::context->getRaw<QueueFamilyObject>(queueFamilyIndex, HandleType::eQueueFamily);
//
auto allocateInfo = vk::CommandBufferAllocateInfo{
.commandPool = queueFamilyObj->commandPool,
.level = vk::CommandBufferLevel::ePrimary,
.commandBufferCount = 1
};
auto commandBuffers = device.allocateCommandBuffers(allocateInfo);
//
auto cmds = std::make_shared<OnceCommandBufferObject>(this->base, Handle().assign(commandBuffers[0]), std::dynamic_pointer_cast<vkh::CreateHelperBase>(std::make_shared<vkh::CommandBufferAllocationHelper>(allocateInfo, this->handle)));
// execute command constructor
commandBuffers[0].begin(vk::CommandBufferBeginInfo{ .flags = vk::CommandBufferUsageFlagBits::eOneTimeSubmit });
cmdFn(commandBuffers[0]);
commandBuffers[0].end();
// planned neopoll coroutine library
auto fence = this->submitCmds(commandBuffers, submitInfo);
//auto event = std::make_shared<cppcoro::single_consumer_event>();
// polling? bad idea... needs independent system
auto result = std::make_shared<vk::Result>(vk::Result::eNotReady);
auto event = neopoll::make_event([cmds, fence, device, commandBuffers, commandPool = queueFamilyObj->commandPool, result, onresult, queueFamilyObj]() {
auto result_ = device.getFenceStatus(fence); device.destroyFence(fence);
//queueFamilyObj->commandBuffers.erase(commandBuffers[0]);
// needs atomic operation?
if (onresult) { onresult(*result = result_); } else { *result = result_; };
}, [device, fence]() {
return device.getFenceStatus(fence) != vk::Result::eNotReady;
});
// make task with awaiting event, and remove resources
return std::tie(result, event);
};
};
| 53.711599 | 297 | 0.646084 | [
"vector"
] |
d32c27d64c0226fa9d6433c953e43ca64c50ea01 | 5,187 | cc | C++ | src/zero_inspector_sync.cc | devsnek/ivan | 98fc08ddb8daa9218cf9c803358edb057df2cd78 | [
"MIT"
] | 6 | 2018-05-10T14:27:49.000Z | 2018-05-31T02:44:39.000Z | src/zero_inspector_sync.cc | devsnek/zero-archive | 98fc08ddb8daa9218cf9c803358edb057df2cd78 | [
"MIT"
] | 123 | 2017-11-05T23:34:05.000Z | 2022-03-08T08:42:06.000Z | src/zero_inspector_sync.cc | devsnek/zero | 98fc08ddb8daa9218cf9c803358edb057df2cd78 | [
"MIT"
] | 3 | 2020-09-13T03:15:22.000Z | 2021-12-13T02:54:45.000Z | #include "v8.h"
#include "v8-inspector.h"
#include "zero.h"
using v8::Array;
using v8::Context;
using v8::Global;
using v8::Local;
using v8::Function;
using v8::FunctionCallbackInfo;
using v8::FunctionTemplate;
using v8::Object;
using v8::Isolate;
using v8::String;
using v8::Value;
using v8::Value;
namespace zero {
namespace inspector {
class InspectorFrontend final : public v8_inspector::V8Inspector::Channel {
public:
explicit InspectorFrontend(Local<Context> context, Local<Function> callback) {
isolate_ = context->GetIsolate();
context_.Reset(isolate_, context);
callback_.Reset(isolate_, callback);
}
virtual ~InspectorFrontend() = default;
private:
void sendResponse(int callId, std::unique_ptr<v8_inspector::StringBuffer> message) override {
Send(message->string());
}
void sendNotification(std::unique_ptr<v8_inspector::StringBuffer> message) override {
Send(message->string());
}
void flushProtocolNotifications() override {}
void Send(const v8_inspector::StringView& string) {
v8::Isolate::AllowJavascriptExecutionScope allow_script(isolate_);
int length = static_cast<int>(string.length());
Local<String> message =
(string.is8Bit()
? v8::String::NewFromOneByte(
isolate_,
reinterpret_cast<const uint8_t*>(string.characters8()),
v8::NewStringType::kNormal, length)
: v8::String::NewFromTwoByte(
isolate_,
reinterpret_cast<const uint16_t*>(string.characters16()),
v8::NewStringType::kNormal, length))
.ToLocalChecked();
Local<Context> context = context_.Get(isolate_);
Local<Function> callback = callback_.Get(isolate_);
v8::TryCatch try_catch(isolate_);
Local<Value> args[] = { message };
USE(callback->Call(context, Undefined(isolate_), 1, args));
}
Isolate* isolate_;
Global<Context> context_;
Global<Function> callback_;
};
class InspectorClient : public v8_inspector::V8InspectorClient {
public:
InspectorClient(Local<Context> context, Local<Function> callback) {
isolate_ = context->GetIsolate();
channel_.reset(new InspectorFrontend(context, callback));
inspector_ = v8_inspector::V8Inspector::create(isolate_, this);
session_ = inspector_->connect(kContextGroupId, channel_.get(), v8_inspector::StringView());
inspector_->contextCreated(
v8_inspector::V8ContextInfo(context, kContextGroupId, v8_inspector::StringView()));
context_.Reset(isolate_, context);
}
static void SendInspectorMessage(const v8::FunctionCallbackInfo<v8::Value>& args) {
Isolate* isolate = args.GetIsolate();
v8::HandleScope handle_scope(isolate);
Local<Context> context = isolate->GetCurrentContext();
v8_inspector::V8InspectorSession* session = GetSession(context);
Local<String> message = args[0]->ToString(context).ToLocalChecked();
int length = message->Length();
std::unique_ptr<uint16_t[]> buffer(new uint16_t[length]);
message->Write(buffer.get(), 0, length);
v8_inspector::StringView message_view(buffer.get(), length);
session->dispatchProtocolMessage(message_view);
args.GetReturnValue().Set(v8::True(isolate));
}
static InspectorClient* GetClient(Local<Context> context) {
return static_cast<InspectorClient*>(
context->GetAlignedPointerFromEmbedderData(EmbedderKeys::kInspector));
}
private:
static v8_inspector::V8InspectorSession* GetSession(Local<Context> context) {
InspectorClient* client = GetClient(context);
if (client == nullptr)
return nullptr;
return client->session_.get();
}
static const int kContextGroupId = 1;
std::unique_ptr<v8_inspector::V8Inspector> inspector_;
std::unique_ptr<v8_inspector::V8InspectorSession> session_;
std::unique_ptr<v8_inspector::V8Inspector::Channel> channel_;
Global<Context> context_;
Isolate* isolate_;
};
void Start(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
Local<Context> context = isolate->GetCurrentContext();
auto inspector_client = InspectorClient::GetClient(context);
if (inspector_client != nullptr)
return;
Local<Function> callback = args[0].As<Function>();
context->SetAlignedPointerInEmbedderData(
EmbedderKeys::kInspector, new InspectorClient(context, callback));
args.GetReturnValue().Set(
FunctionTemplate::New(isolate, InspectorClient::SendInspectorMessage)->GetFunction());
}
void Stop(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
Local<Context> context = isolate->GetCurrentContext();
auto inspector_client = InspectorClient::GetClient(context);
if (inspector_client != nullptr) {
delete inspector_client;
args.GetReturnValue().Set(True(isolate));
} else {
args.GetReturnValue().Set(False(isolate));
}
}
void Init(Local<Context> context, Local<Object> target) {
ZERO_SET_PROPERTY(context, target, "start", Start);
ZERO_SET_PROPERTY(context, target, "stop", Stop);
}
} // namespace inspector
} // namespace zero
ZERO_REGISTER_INTERNAL(inspector_sync, zero::inspector::Init);
| 31.628049 | 96 | 0.712358 | [
"object"
] |
d32cd38807fa059d5d67cb0ec27a494cdbd09bc5 | 1,483 | cpp | C++ | Algorithm/arrays/array_sum_and_operations/C++/0001_solution.cpp | BitsCoding/DS-and-Algo | 481cfdf23429c1b9a60898628afbb93dfbbefc12 | [
"MIT"
] | 5 | 2020-10-08T16:53:05.000Z | 2020-11-29T09:35:49.000Z | Algorithm/arrays/array_sum_and_operations/C++/0001_solution.cpp | BitsCoding/DS-and-Algo | 481cfdf23429c1b9a60898628afbb93dfbbefc12 | [
"MIT"
] | 4 | 2020-10-17T14:18:15.000Z | 2020-10-17T18:22:13.000Z | Algorithm/arrays/array_sum_and_operations/C++/0001_solution.cpp | BitsCoding/DS-and-Algo | 481cfdf23429c1b9a60898628afbb93dfbbefc12 | [
"MIT"
] | 3 | 2020-10-17T14:42:47.000Z | 2021-10-01T09:55:12.000Z | /**
* Solution of problem 'array_sum_and_operations'.
* @file 001_solution.cpp
* @author Nischay Sharma
* @version 1.0
* */
#include <iostream>
#include <vector>
#define M 1000000007
#define ll long long
// formula to find sum from one to 'n'.
#define SUM(n) ((n * (n - 1)) / 2)
using namespace std;
/**
* Finds the appropriate value for the 'array_sum_and_operations' problem
* @param N int
* @param op vector of int
* @return vector of int denoting sum of array after each operations.
**/
vector<ll> performOperations(ll N, const vector<ll>& op) {
vector<ll> result(op.size());
ll first{1}, last{N};
ll s{SUM(N) % M - 1};
for (ll i{}; i < (ll)op.size(); i++) {
/* Comparing 'op[i]' whether it is in range of 2' to 'N-1' or equal to
* 'first' or 'last'*/
if ((op[i] < N && op[i] >= 2) || op[i] == first || op[i] == last) {
ll temp = first;
first = last;
last = temp;
} else {
first = op[i];
}
result[i] = (s + last + first) % M;
}
return result;
}
int main() {
int t;
scanf("%d", &t);
while (t--) {
ll n, q;
scanf("%lld %lld", &n, &q);
vector<ll> op(q);
for (ll i{}; i < q; i++) {
scanf("%lld", &op[i]);
}
vector<ll> result = performOperations(n, op);
for (ll i{}; i < q; i++) {
printf("%lld\n", result[i]);
}
}
return 0;
} | 24.716667 | 78 | 0.498989 | [
"vector"
] |
d3301e4e294cc0b44f5276ac74b5f31639b49344 | 2,385 | hpp | C++ | include/Sphere_d.hpp | sdmg15/CDT-plusplus | 13071b61677e0c1db077f252dcab25ea672bbe9d | [
"BSD-3-Clause"
] | 1 | 2019-10-05T10:58:34.000Z | 2019-10-05T10:58:34.000Z | include/Sphere_d.hpp | sdmg15/CDT-plusplus | 13071b61677e0c1db077f252dcab25ea672bbe9d | [
"BSD-3-Clause"
] | null | null | null | include/Sphere_d.hpp | sdmg15/CDT-plusplus | 13071b61677e0c1db077f252dcab25ea672bbe9d | [
"BSD-3-Clause"
] | 1 | 2020-07-13T03:39:34.000Z | 2020-07-13T03:39:34.000Z | /// Causal Dynamical Triangulations in C++ using CGAL
///
/// Copyright © 2014-2017 Adam Getchell
///
/// Inserts a given number of points into a d-dimensional sphere of
/// a given radius
/// \todo Make the vector compatible with the triangulation data structure
/// @file sphere_d.hpp
/// @brief Functions on d-Spheres
/// @author Adam Getchell
#ifndef INCLUDE_SPHERE_D_HPP_
#define INCLUDE_SPHERE_D_HPP_
/// CGAL headers
#include <CGAL/Cartesian_d.h>
#include <CGAL/point_generators_d.h>
/// C++ headers
#include <iostream>
#include <vector>
using Kd = CGAL::Cartesian_d<double>;
// typedef Kd::Point_d Point;
/// @brief Make a d-dimensional sphere
///
/// The radius is used to denote the time value, so we can nest d-spheres
/// such that our time foliation contains leaves of identical topology.
///
/// @param number_of_points Number of vertices at a given radius
/// @param dimension Dimension of sphere
/// @param radius Radius of sphere
/// @param output Prints detailed output
/// @param points The points ready to insert
void make_d_sphere(std::size_t number_of_points, int dimension, double radius,
bool output, std::vector<Kd::Point_d>& points) noexcept
{
points.reserve(number_of_points);
CGAL::Random_points_on_sphere_d<Kd::Point_d> gen(dimension, radius);
for (decltype(number_of_points) i = 0; i < number_of_points; ++i)
{ points.push_back(*gen++); }
// If output = true, print out values of points in sphere
if (output)
{
std::cout << "Generating " << number_of_points << " random points on "
<< "the surface of a sphere in " << dimension << "D\n"
<< "of center 0 and radius " << radius << ".\n";
for (const auto& point : points) { std::cout << " " << point << "\n"; }
}
} // make_d_sphere()
/// @brief Make a d-dimensional sphere without output
///
/// Function overload of make_d_sphere to suppress output
///
/// @param[in] number_of_points Number of vertices at a given radius
/// @param[in] dimension Dimension of sphere
/// @param[in] radius Radius of sphere
/// @param[out] points The points ready to insert
void make_d_sphere(std::size_t number_of_points, int dimension, double radius,
std::vector<Kd::Point_d>& points) noexcept
{
make_d_sphere(number_of_points, dimension, radius, false, points);
} // make_d_sphere
#endif // INCLUDE_SPHERE_D_HPP_
| 32.671233 | 78 | 0.693501 | [
"vector"
] |
d330c1285c06be31312c5af4400ac499b644ddf1 | 10,091 | cc | C++ | test/matrix_bss.cc | upperwal/valhalla | fa1d104c123a8a33ef8e50b36951b9f89fd53480 | [
"MIT"
] | null | null | null | test/matrix_bss.cc | upperwal/valhalla | fa1d104c123a8a33ef8e50b36951b9f89fd53480 | [
"MIT"
] | null | null | null | test/matrix_bss.cc | upperwal/valhalla | fa1d104c123a8a33ef8e50b36951b9f89fd53480 | [
"MIT"
] | 1 | 2021-01-24T16:46:01.000Z | 2021-01-24T16:46:01.000Z | #include "proto/options.pb.h"
#include "sif/costconstants.h"
#include "test.h"
#include <iostream>
#include <string>
#include <valhalla/baldr/rapidjson_utils.h>
#include <vector>
#include "loki/worker.h"
#include "midgard/logging.h"
#include "odin/worker.h"
#include "thor/worker.h"
#include "sif/costfactory.h"
#include "sif/dynamiccost.h"
#include "thor/costmatrix.h"
#include "thor/timedistancebssmatrix.h"
using namespace valhalla;
using namespace valhalla::thor;
using namespace valhalla::sif;
using namespace valhalla::loki;
using namespace valhalla::baldr;
using namespace valhalla::midgard;
using namespace valhalla::tyr;
using namespace valhalla::odin;
namespace rj = rapidjson;
namespace {
valhalla::sif::cost_ptr_t create_costing() {
valhalla::Options options;
for (int i = 0; i < valhalla::Costing_MAX; ++i)
options.add_costing_options();
for (auto costing_str : {"pedestrian", "bicycle"}) {
valhalla::Costing costing;
if (valhalla::Costing_Enum_Parse(costing_str, &costing)) {
options.set_costing(costing);
}
}
return valhalla::sif::CostFactory{}.Create(options);
}
// Note that the "loki/radius" is intentionally left to 10, since the bss_connection is a duplication
// of the existing way on which the bike share sation is projected. It would be advisable to not set
// radius to 0 so that the algorithm will choose the best projection. Otherwise, the location may be
// projected uniquely on the bss_connection.
const auto config = test::json_to_pt(R"({
"mjolnir":{"tile_dir":"test/data/paris_bss_tiles", "concurrency": 1},
"loki":{
"actions":["sources_to_targets"],
"logging":{"long_request": 100},
"service_defaults":{
"minimum_reachability": 2,
"radius": 10,
"search_cutoff": 35000,
"node_snap_tolerance": 5,
"street_side_tolerance": 5,
"heading_tolerance": 60,
"street_side_max_distance": 1000}
},
"thor":{"logging":{"long_request": 100}},
"odin":{"logging":{"long_request": 100}},
"skadi":{"actons":["height"],"logging":{"long_request": 5}},
"meili":{"customizable": ["turn_penalty_factor","max_route_distance_factor","max_route_time_factor","search_radius"],
"mode":"auto","grid":{"cache_size":100240,"size":500},
"default":{"beta":3,"breakage_distance":2000,"geometry":false,"gps_accuracy":5.0,"interpolation_distance":10,
"max_route_distance_factor":5,"max_route_time_factor":5,"max_search_radius":200,"route":true,
"search_radius":15.0,"sigma_z":4.07,"turn_penalty_factor":200}},
"service_limits": {
"auto": {"max_distance": 5000000.0, "max_locations": 20,"max_matrix_distance": 400000.0,"max_matrix_locations": 50},
"auto_shorter": {"max_distance": 5000000.0,"max_locations": 20,"max_matrix_distance": 400000.0,"max_matrix_locations": 50},
"bicycle": {"max_distance": 500000.0,"max_locations": 50,"max_matrix_distance": 200000.0,"max_matrix_locations": 50},
"bus": {"max_distance": 5000000.0,"max_locations": 50,"max_matrix_distance": 400000.0,"max_matrix_locations": 50},
"hov": {"max_distance": 5000000.0,"max_locations": 20,"max_matrix_distance": 400000.0,"max_matrix_locations": 50},
"taxi": {"max_distance": 5000000.0,"max_locations": 20,"max_matrix_distance": 400000.0,"max_matrix_locations": 50},
"isochrone": {"max_contours": 4,"max_distance": 25000.0,"max_locations": 1,"max_time_contour": 240, "max_distance_contour":200},
"max_avoid_locations": 50,"max_radius": 200,"max_reachability": 100,"max_alternates":2,
"multimodal": {"max_distance": 500000.0,"max_locations": 50,"max_matrix_distance": 0.0,"max_matrix_locations": 0},
"pedestrian": {"max_distance": 250000.0,"max_locations": 50,"max_matrix_distance": 200000.0,"max_matrix_locations": 50,"max_transit_walking_distance": 10000,"min_transit_walking_distance": 1},
"skadi": {"max_shape": 750000,"min_resample": 10.0},
"trace": {"max_distance": 200000.0,"max_gps_accuracy": 100.0,"max_search_radius": 100,"max_shape": 16000,"max_best_paths":4,"max_best_paths_shape":100},
"transit": {"max_distance": 500000.0,"max_locations": 50,"max_matrix_distance": 200000.0,"max_matrix_locations": 50},
"truck": {"max_distance": 5000000.0,"max_locations": 20,"max_matrix_distance": 400000.0,"max_matrix_locations": 50},
"bikeshare": {"max_distance": 5000000.0,"max_locations": 20,"max_matrix_distance": 400000.0,"max_matrix_locations": 50}
}
})");
} // namespace
// The distances returned by route and matrix are not always equal to each other
// We set here 4% as the bias tolerance.
const float kDistancePercentThreshold = 0.04;
const uint32_t kTimeThreshold = 2;
class MatrixBssTest : public ::testing::Test {
public:
MatrixBssTest() {
Options options;
options.set_costing(Costing::bikeshare);
rapidjson::Document doc;
sif::ParseCostingOptions(doc, "/costing_options", options);
sif::TravelMode mode;
mode_costing = sif::CostFactory().CreateModeCosting(options, mode);
}
std::string make_matrix_request(const std::vector<std::pair<float, float>>& sources,
const std::vector<std::pair<float, float>>& targets) {
rj::Document req;
auto& alloc = req.GetAllocator();
auto make_req_array = [&alloc](const auto& locations) -> rj::Value {
auto array = rj::Value{rj::kArrayType};
for (const auto& s : locations) {
array.PushBack(rj::Value()
.SetObject()
.AddMember("lat", s.first, alloc)
.AddMember("lon", s.second, alloc),
alloc);
}
return array;
};
req.SetObject()
.AddMember("sources", make_req_array(sources), alloc)
.AddMember("targets", make_req_array(targets), alloc)
.AddMember("costing", "bikeshare", alloc);
std::cout << "matrix request: " << rj::to_string(req) << "\n";
return rj::to_string(req);
}
std::string make_matrix_request(const std::pair<float, float>& source,
const std::pair<float, float>& target) {
rj::Document req;
auto& alloc = req.GetAllocator();
auto locations = rj::Value{rj::kArrayType};
locations
.PushBack(rj::Value()
.SetObject()
.AddMember("lat", source.first, alloc)
.AddMember("lon", source.second, alloc),
alloc)
.PushBack(rj::Value()
.SetObject()
.AddMember("lat", target.first, alloc)
.AddMember("lon", target.second, alloc),
alloc);
req.SetObject().AddMember("locations", locations, alloc).AddMember("costing", "bikeshare", alloc);
std::cout << "route req: " << rj::to_string(req) << "\n";
return rj::to_string(req);
}
void test(const std::vector<std::pair<float, float>>& sources,
const std::vector<std::pair<float, float>>& targets) {
Api matrix_request;
ParseApi(make_matrix_request(sources, targets), Options::sources_to_targets, matrix_request);
loki_worker.matrix(matrix_request);
auto matrix_results =
timedist_matrix_bss.SourceToTarget(matrix_request.options().sources(),
matrix_request.options().targets(), reader, mode_costing,
TravelMode::kPedestrian, 400000.0);
auto s_size = sources.size();
auto t_size = targets.size();
// we compute the real route by iterating over the sources and targets
for (size_t i = 0; i < s_size; ++i) {
for (size_t j = 0; j < t_size; ++j) {
Api route_request;
ParseApi(make_matrix_request(sources[i], targets[j]), valhalla::Options::route,
route_request);
loki_worker.route(route_request);
thor_worker.route(route_request);
odin_worker.narrate(route_request);
const auto& legs = route_request.directions().routes(0).legs();
EXPECT_EQ(legs.size(), 1) << "Should have 1 leg";
int route_time = legs.begin()->summary().time();
int route_length = legs.begin()->summary().length() * 1000;
size_t m_result_idx = i * t_size + j;
int matrix_time = matrix_results[m_result_idx].time;
int matrix_length = matrix_results[m_result_idx].dist;
EXPECT_NEAR(matrix_time, route_time, kTimeThreshold);
EXPECT_NEAR(matrix_length, route_length, route_length * kDistancePercentThreshold);
}
}
}
private:
loki_worker_t loki_worker{config};
thor_worker_t thor_worker{config};
odin_worker_t odin_worker{config};
GraphReader reader{config.get_child("mjolnir")};
mode_costing_t mode_costing;
TimeDistanceBSSMatrix timedist_matrix_bss;
};
TEST_F(MatrixBssTest, OneToMany) {
test(
// sources lat - lon
{
{48.858376, 2.358229},
},
// targets lat - lon
{
{48.865032, 2.362484},
{48.862484, 2.365708},
{48.86911, 2.36019},
{48.865448, 2.363641},
});
}
TEST_F(MatrixBssTest, ManyToOne) {
test(
// sources lat - lon
{
{48.858376, 2.358229},
{48.859636, 2.362984},
{48.857826, 2.366695},
{48.85788, 2.36125},
},
// targets lat - lon
{
{48.865032, 2.362484},
});
}
TEST_F(MatrixBssTest, ManyToMany) {
test(
// sources lat - lon
{
{48.858376, 2.358229},
{48.859636, 2.362984},
{48.857826, 2.366695},
{48.85788, 2.36125},
},
// targets lat - lon
{
{48.865032, 2.362484},
{48.862484, 2.365708},
{48.86911, 2.36019},
{48.865448, 2.363641},
});
}
int main(int argc, char* argv[]) {
logging::Configure({{"type", ""}}); // silence logs
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 37.374074 | 200 | 0.63076 | [
"geometry",
"vector"
] |
d34c254d76870ab510f91d070601cbfd85701f97 | 201,475 | cc | C++ | wrappers/perl5/EST_Track_wrap.cc | zeehio/speech-tools | 0b0fb9387cbee2b1a5cb010b5a5ca04f5fe8f785 | [
"Unlicense"
] | 8 | 2015-06-12T12:13:59.000Z | 2021-03-16T17:56:49.000Z | wrappers/perl5/EST_Track_wrap.cc | zeehio/speech-tools | 0b0fb9387cbee2b1a5cb010b5a5ca04f5fe8f785 | [
"Unlicense"
] | 1 | 2017-01-02T08:02:45.000Z | 2017-01-02T08:02:45.000Z | wrappers/perl5/EST_Track_wrap.cc | zeehio/speech-tools | 0b0fb9387cbee2b1a5cb010b5a5ca04f5fe8f785 | [
"Unlicense"
] | 5 | 2015-10-13T12:54:31.000Z | 2020-01-21T07:46:14.000Z | /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 1.3.27
*
* This file is not intended to be easily readable and contains a number of
* coding conventions designed to improve portability and efficiency. Do not make
* changes to this file unless you know what you are doing--modify the SWIG
* interface file instead.
* ----------------------------------------------------------------------------- */
#ifdef __cplusplus
template<class T> class SwigValueWrapper {
T *tt;
public:
SwigValueWrapper() : tt(0) { }
SwigValueWrapper(const SwigValueWrapper<T>& rhs) : tt(new T(*rhs.tt)) { }
SwigValueWrapper(const T& t) : tt(new T(t)) { }
~SwigValueWrapper() { delete tt; }
SwigValueWrapper& operator=(const T& t) { delete tt; tt = new T(t); return *this; }
operator T&() const { return *tt; }
T *operator&() { return tt; }
private:
SwigValueWrapper& operator=(const SwigValueWrapper<T>& rhs);
};
#endif
/***********************************************************************
*
* This section contains generic SWIG labels for method/variable
* declarations/attributes, and other compiler dependent labels.
*
************************************************************************/
/* template workaround for compilers that cannot correctly implement the C++ standard */
#ifndef SWIGTEMPLATEDISAMBIGUATOR
# if defined(__SUNPRO_CC) && (__SUNPRO_CC <= 0x560)
# define SWIGTEMPLATEDISAMBIGUATOR template
# else
# define SWIGTEMPLATEDISAMBIGUATOR
# endif
#endif
/* inline attribute */
#ifndef SWIGINLINE
# if defined(__cplusplus) || (defined(__GNUC__) && !defined(__STRICT_ANSI__))
# define SWIGINLINE inline
# else
# define SWIGINLINE
# endif
#endif
/* attribute recognised by some compilers to avoid 'unused' warnings */
#ifndef SWIGUNUSED
# if defined(__GNUC__) || defined(__ICC)
# define SWIGUNUSED __attribute__ ((unused))
# else
# define SWIGUNUSED
# endif
#endif
/* internal SWIG method */
#ifndef SWIGINTERN
# define SWIGINTERN static SWIGUNUSED
#endif
/* internal inline SWIG method */
#ifndef SWIGINTERNINLINE
# define SWIGINTERNINLINE SWIGINTERN SWIGINLINE
#endif
/* exporting methods for Windows DLLs */
#ifndef SWIGEXPORT
# if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__)
# if defined(STATIC_LINKED)
# define SWIGEXPORT
# else
# define SWIGEXPORT __declspec(dllexport)
# endif
# else
# define SWIGEXPORT
# endif
#endif
/* calling conventions for Windows */
#ifndef SWIGSTDCALL
# if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__)
# define SWIGSTDCALL __stdcall
# else
# define SWIGSTDCALL
# endif
#endif
/***********************************************************************
* swigrun.swg
*
* This file contains generic CAPI SWIG runtime support for pointer
* type checking.
*
************************************************************************/
/* This should only be incremented when either the layout of swig_type_info changes,
or for whatever reason, the runtime changes incompatibly */
#define SWIG_RUNTIME_VERSION "2"
/* define SWIG_TYPE_TABLE_NAME as "SWIG_TYPE_TABLE" */
#ifdef SWIG_TYPE_TABLE
# define SWIG_QUOTE_STRING(x) #x
# define SWIG_EXPAND_AND_QUOTE_STRING(x) SWIG_QUOTE_STRING(x)
# define SWIG_TYPE_TABLE_NAME SWIG_EXPAND_AND_QUOTE_STRING(SWIG_TYPE_TABLE)
#else
# define SWIG_TYPE_TABLE_NAME
#endif
/*
You can use the SWIGRUNTIME and SWIGRUNTIMEINLINE macros for
creating a static or dynamic library from the swig runtime code.
In 99.9% of the cases, swig just needs to declare them as 'static'.
But only do this if is strictly necessary, ie, if you have problems
with your compiler or so.
*/
#ifndef SWIGRUNTIME
# define SWIGRUNTIME SWIGINTERN
#endif
#ifndef SWIGRUNTIMEINLINE
# define SWIGRUNTIMEINLINE SWIGRUNTIME SWIGINLINE
#endif
#include <string.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef void *(*swig_converter_func)(void *);
typedef struct swig_type_info *(*swig_dycast_func)(void **);
/* Structure to store inforomation on one type */
typedef struct swig_type_info {
const char *name; /* mangled name of this type */
const char *str; /* human readable name of this type */
swig_dycast_func dcast; /* dynamic cast function down a hierarchy */
struct swig_cast_info *cast; /* linked list of types that can cast into this type */
void *clientdata; /* language specific type data */
} swig_type_info;
/* Structure to store a type and conversion function used for casting */
typedef struct swig_cast_info {
swig_type_info *type; /* pointer to type that is equivalent to this type */
swig_converter_func converter; /* function to cast the void pointers */
struct swig_cast_info *next; /* pointer to next cast in linked list */
struct swig_cast_info *prev; /* pointer to the previous cast */
} swig_cast_info;
/* Structure used to store module information
* Each module generates one structure like this, and the runtime collects
* all of these structures and stores them in a circularly linked list.*/
typedef struct swig_module_info {
swig_type_info **types; /* Array of pointers to swig_type_info structures that are in this module */
size_t size; /* Number of types in this module */
struct swig_module_info *next; /* Pointer to next element in circularly linked list */
swig_type_info **type_initial; /* Array of initially generated type structures */
swig_cast_info **cast_initial; /* Array of initially generated casting structures */
void *clientdata; /* Language specific module data */
} swig_module_info;
/*
Compare two type names skipping the space characters, therefore
"char*" == "char *" and "Class<int>" == "Class<int >", etc.
Return 0 when the two name types are equivalent, as in
strncmp, but skipping ' '.
*/
SWIGRUNTIME int
SWIG_TypeNameComp(const char *f1, const char *l1,
const char *f2, const char *l2) {
for (;(f1 != l1) && (f2 != l2); ++f1, ++f2) {
while ((*f1 == ' ') && (f1 != l1)) ++f1;
while ((*f2 == ' ') && (f2 != l2)) ++f2;
if (*f1 != *f2) return (int)(*f1 - *f2);
}
return (l1 - f1) - (l2 - f2);
}
/*
Check type equivalence in a name list like <name1>|<name2>|...
Return 0 if not equal, 1 if equal
*/
SWIGRUNTIME int
SWIG_TypeEquiv(const char *nb, const char *tb) {
int equiv = 0;
const char* te = tb + strlen(tb);
const char* ne = nb;
while (!equiv && *ne) {
for (nb = ne; *ne; ++ne) {
if (*ne == '|') break;
}
equiv = (SWIG_TypeNameComp(nb, ne, tb, te) == 0) ? 1 : 0;
if (*ne) ++ne;
}
return equiv;
}
/*
Check type equivalence in a name list like <name1>|<name2>|...
Return 0 if equal, -1 if nb < tb, 1 if nb > tb
*/
SWIGRUNTIME int
SWIG_TypeCompare(const char *nb, const char *tb) {
int equiv = 0;
const char* te = tb + strlen(tb);
const char* ne = nb;
while (!equiv && *ne) {
for (nb = ne; *ne; ++ne) {
if (*ne == '|') break;
}
equiv = (SWIG_TypeNameComp(nb, ne, tb, te) == 0) ? 1 : 0;
if (*ne) ++ne;
}
return equiv;
}
/* think of this as a c++ template<> or a scheme macro */
#define SWIG_TypeCheck_Template(comparison, ty) \
if (ty) { \
swig_cast_info *iter = ty->cast; \
while (iter) { \
if (comparison) { \
if (iter == ty->cast) return iter; \
/* Move iter to the top of the linked list */ \
iter->prev->next = iter->next; \
if (iter->next) \
iter->next->prev = iter->prev; \
iter->next = ty->cast; \
iter->prev = 0; \
if (ty->cast) ty->cast->prev = iter; \
ty->cast = iter; \
return iter; \
} \
iter = iter->next; \
} \
} \
return 0
/*
Check the typename
*/
SWIGRUNTIME swig_cast_info *
SWIG_TypeCheck(const char *c, swig_type_info *ty) {
SWIG_TypeCheck_Template(strcmp(iter->type->name, c) == 0, ty);
}
/* Same as previous function, except strcmp is replaced with a pointer comparison */
SWIGRUNTIME swig_cast_info *
SWIG_TypeCheckStruct(swig_type_info *from, swig_type_info *into) {
SWIG_TypeCheck_Template(iter->type == from, into);
}
/*
Cast a pointer up an inheritance hierarchy
*/
SWIGRUNTIMEINLINE void *
SWIG_TypeCast(swig_cast_info *ty, void *ptr) {
return ((!ty) || (!ty->converter)) ? ptr : (*ty->converter)(ptr);
}
/*
Dynamic pointer casting. Down an inheritance hierarchy
*/
SWIGRUNTIME swig_type_info *
SWIG_TypeDynamicCast(swig_type_info *ty, void **ptr) {
swig_type_info *lastty = ty;
if (!ty || !ty->dcast) return ty;
while (ty && (ty->dcast)) {
ty = (*ty->dcast)(ptr);
if (ty) lastty = ty;
}
return lastty;
}
/*
Return the name associated with this type
*/
SWIGRUNTIMEINLINE const char *
SWIG_TypeName(const swig_type_info *ty) {
return ty->name;
}
/*
Return the pretty name associated with this type,
that is an unmangled type name in a form presentable to the user.
*/
SWIGRUNTIME const char *
SWIG_TypePrettyName(const swig_type_info *type) {
/* The "str" field contains the equivalent pretty names of the
type, separated by vertical-bar characters. We choose
to print the last name, as it is often (?) the most
specific. */
if (type->str != NULL) {
const char *last_name = type->str;
const char *s;
for (s = type->str; *s; s++)
if (*s == '|') last_name = s+1;
return last_name;
}
else
return type->name;
}
/*
Set the clientdata field for a type
*/
SWIGRUNTIME void
SWIG_TypeClientData(swig_type_info *ti, void *clientdata) {
swig_cast_info *cast = ti->cast;
/* if (ti->clientdata == clientdata) return; */
ti->clientdata = clientdata;
while (cast) {
if (!cast->converter) {
swig_type_info *tc = cast->type;
if (!tc->clientdata) {
SWIG_TypeClientData(tc, clientdata);
}
}
cast = cast->next;
}
}
/*
Search for a swig_type_info structure only by mangled name
Search is a O(log #types)
We start searching at module start, and finish searching when start == end.
Note: if start == end at the beginning of the function, we go all the way around
the circular list.
*/
SWIGRUNTIME swig_type_info *
SWIG_MangledTypeQueryModule(swig_module_info *start,
swig_module_info *end,
const char *name) {
swig_module_info *iter = start;
do {
if (iter->size) {
register size_t l = 0;
register size_t r = iter->size - 1;
do {
/* since l+r >= 0, we can (>> 1) instead (/ 2) */
register size_t i = (l + r) >> 1;
const char *iname = iter->types[i]->name;
if (iname) {
register int compare = strcmp(name, iname);
if (compare == 0) {
return iter->types[i];
} else if (compare < 0) {
if (i) {
r = i - 1;
} else {
break;
}
} else if (compare > 0) {
l = i + 1;
}
} else {
break; /* should never happen */
}
} while (l <= r);
}
iter = iter->next;
} while (iter != end);
return 0;
}
/*
Search for a swig_type_info structure for either a mangled name or a human readable name.
It first searches the mangled names of the types, which is a O(log #types)
If a type is not found it then searches the human readable names, which is O(#types).
We start searching at module start, and finish searching when start == end.
Note: if start == end at the beginning of the function, we go all the way around
the circular list.
*/
SWIGRUNTIME swig_type_info *
SWIG_TypeQueryModule(swig_module_info *start,
swig_module_info *end,
const char *name) {
/* STEP 1: Search the name field using binary search */
swig_type_info *ret = SWIG_MangledTypeQueryModule(start, end, name);
if (ret) {
return ret;
} else {
/* STEP 2: If the type hasn't been found, do a complete search
of the str field (the human readable name) */
swig_module_info *iter = start;
do {
register size_t i = 0;
for (; i < iter->size; ++i) {
if (iter->types[i]->str && (SWIG_TypeEquiv(iter->types[i]->str, name)))
return iter->types[i];
}
iter = iter->next;
} while (iter != end);
}
/* neither found a match */
return 0;
}
/*
Pack binary data into a string
*/
SWIGRUNTIME char *
SWIG_PackData(char *c, void *ptr, size_t sz) {
static const char hex[17] = "0123456789abcdef";
register const unsigned char *u = (unsigned char *) ptr;
register const unsigned char *eu = u + sz;
for (; u != eu; ++u) {
register unsigned char uu = *u;
*(c++) = hex[(uu & 0xf0) >> 4];
*(c++) = hex[uu & 0xf];
}
return c;
}
/*
Unpack binary data from a string
*/
SWIGRUNTIME const char *
SWIG_UnpackData(const char *c, void *ptr, size_t sz) {
register unsigned char *u = (unsigned char *) ptr;
register const unsigned char *eu = u + sz;
for (; u != eu; ++u) {
register char d = *(c++);
register unsigned char uu = 0;
if ((d >= '0') && (d <= '9'))
uu = ((d - '0') << 4);
else if ((d >= 'a') && (d <= 'f'))
uu = ((d - ('a'-10)) << 4);
else
return (char *) 0;
d = *(c++);
if ((d >= '0') && (d <= '9'))
uu |= (d - '0');
else if ((d >= 'a') && (d <= 'f'))
uu |= (d - ('a'-10));
else
return (char *) 0;
*u = uu;
}
return c;
}
/*
Pack 'void *' into a string buffer.
*/
SWIGRUNTIME char *
SWIG_PackVoidPtr(char *buff, void *ptr, const char *name, size_t bsz) {
char *r = buff;
if ((2*sizeof(void *) + 2) > bsz) return 0;
*(r++) = '_';
r = SWIG_PackData(r,&ptr,sizeof(void *));
if (strlen(name) + 1 > (bsz - (r - buff))) return 0;
strcpy(r,name);
return buff;
}
SWIGRUNTIME const char *
SWIG_UnpackVoidPtr(const char *c, void **ptr, const char *name) {
if (*c != '_') {
if (strcmp(c,"NULL") == 0) {
*ptr = (void *) 0;
return name;
} else {
return 0;
}
}
return SWIG_UnpackData(++c,ptr,sizeof(void *));
}
SWIGRUNTIME char *
SWIG_PackDataName(char *buff, void *ptr, size_t sz, const char *name, size_t bsz) {
char *r = buff;
size_t lname = (name ? strlen(name) : 0);
if ((2*sz + 2 + lname) > bsz) return 0;
*(r++) = '_';
r = SWIG_PackData(r,ptr,sz);
if (lname) {
strncpy(r,name,lname+1);
} else {
*r = 0;
}
return buff;
}
SWIGRUNTIME const char *
SWIG_UnpackDataName(const char *c, void *ptr, size_t sz, const char *name) {
if (*c != '_') {
if (strcmp(c,"NULL") == 0) {
memset(ptr,0,sz);
return name;
} else {
return 0;
}
}
return SWIG_UnpackData(++c,ptr,sz);
}
#ifdef __cplusplus
}
#endif
/* ---------------------------------------------------------------------- -*- c -*-
* perl5.swg
*
* Perl5 runtime library
* $Header: /home/CVS/speech_tools/wrappers/perl5/EST_Track_wrap.cc,v 1.1 2006/01/06 18:13:19 korin Exp $
* ----------------------------------------------------------------------------- */
#define SWIGPERL
#define SWIGPERL5
#ifdef __cplusplus
/* Needed on some windows machines---since MS plays funny games with the header files under C++ */
#include <math.h>
#include <stdlib.h>
extern "C" {
#endif
#include "EXTERN.h"
#include "perl.h"
#include "XSUB.h"
/* Get rid of free and malloc defined by perl */
#undef free
#undef malloc
#ifndef pTHX_
#define pTHX_
#endif
#include <string.h>
#ifdef __cplusplus
}
#endif
/* Macro to call an XS function */
#ifdef PERL_OBJECT
# define SWIG_CALLXS(_name) _name(cv,pPerl)
#else
# ifndef MULTIPLICITY
# define SWIG_CALLXS(_name) _name(cv)
# else
# define SWIG_CALLXS(_name) _name(PERL_GET_THX, cv)
# endif
#endif
/* Contract support */
#define SWIG_contract_assert(expr,msg) if (!(expr)) { SWIG_croak(msg); } else
/* Note: SwigMagicFuncHack is a typedef used to get the C++ compiler to just shut up already */
#ifdef PERL_OBJECT
#define MAGIC_PPERL CPerlObj *pPerl = (CPerlObj *) this;
typedef int (CPerlObj::*SwigMagicFunc)(SV *, MAGIC *);
#ifdef __cplusplus
extern "C" {
#endif
typedef int (CPerlObj::*SwigMagicFuncHack)(SV *, MAGIC *);
#ifdef __cplusplus
}
#endif
#define SWIG_MAGIC(a,b) (SV *a, MAGIC *b)
#define SWIGCLASS_STATIC
#else
#define MAGIC_PPERL
#define SWIGCLASS_STATIC static
#ifndef MULTIPLICITY
#define SWIG_MAGIC(a,b) (SV *a, MAGIC *b)
typedef int (*SwigMagicFunc)(SV *, MAGIC *);
#ifdef __cplusplus
extern "C" {
#endif
typedef int (*SwigMagicFuncHack)(SV *, MAGIC *);
#ifdef __cplusplus
}
#endif
#else
#define SWIG_MAGIC(a,b) (struct interpreter *interp, SV *a, MAGIC *b)
typedef int (*SwigMagicFunc)(struct interpreter *, SV *, MAGIC *);
#ifdef __cplusplus
extern "C" {
#endif
typedef int (*SwigMagicFuncHack)(struct interpreter *, SV *, MAGIC *);
#ifdef __cplusplus
}
#endif
#endif
#endif
#if defined(WIN32) && defined(PERL_OBJECT) && !defined(PerlIO_exportFILE)
#define PerlIO_exportFILE(fh,fl) (FILE*)(fh)
#endif
/* Modifications for newer Perl 5.005 releases */
#if !defined(PERL_REVISION) || ((PERL_REVISION >= 5) && ((PERL_VERSION < 5) || ((PERL_VERSION == 5) && (PERL_SUBVERSION < 50))))
# ifndef PL_sv_yes
# define PL_sv_yes sv_yes
# endif
# ifndef PL_sv_undef
# define PL_sv_undef sv_undef
# endif
# ifndef PL_na
# define PL_na na
# endif
#endif
#include <stdlib.h>
#ifdef __cplusplus
extern "C" {
#endif
#define SWIG_OWNER 1
#define SWIG_SHADOW 2
/* Common SWIG API */
#ifdef PERL_OBJECT
# define SWIG_ConvertPtr(obj, pp, type, flags) \
SWIG_Perl_ConvertPtr(pPerl, obj, pp, type, flags)
# define SWIG_NewPointerObj(p, type, flags) \
SWIG_Perl_NewPointerObj(pPerl, p, type, flags)
# define SWIG_MakePackedObj(sv, p, s, type) \
SWIG_Perl_MakePackedObj(pPerl, sv, p, s, type)
# define SWIG_ConvertPacked(obj, p, s, type, flags) \
SWIG_Perl_ConvertPacked(pPerl, obj, p, s, type, flags)
#else
# define SWIG_ConvertPtr(obj, pp, type, flags) \
SWIG_Perl_ConvertPtr(obj, pp, type, flags)
# define SWIG_NewPointerObj(p, type, flags) \
SWIG_Perl_NewPointerObj(p, type, flags)
# define SWIG_MakePackedObj(sv, p, s, type) \
SWIG_Perl_MakePackedObj(sv, p, s, type )
# define SWIG_ConvertPacked(obj, p, s, type, flags) \
SWIG_Perl_ConvertPacked(obj, p, s, type, flags)
#endif
/* Runtime API */
#define SWIG_GetModule(clientdata) SWIG_Perl_GetModule()
#define SWIG_SetModule(clientdata, pointer) SWIG_Perl_SetModule(pointer)
/* Perl-specific API */
#ifdef PERL_OBJECT
# define SWIG_MakePtr(sv, ptr, type, flags) \
SWIG_Perl_MakePtr(pPerl, sv, ptr, type, flags)
# define SWIG_SetError(str) \
SWIG_Perl_SetError(pPerl, str)
#else
# define SWIG_MakePtr(sv, ptr, type, flags) \
SWIG_Perl_MakePtr(sv, ptr, type, flags)
# define SWIG_SetError(str) \
SWIG_Perl_SetError(str)
# define SWIG_SetErrorSV(str) \
SWIG_Perl_SetErrorSV(str)
#endif
#define SWIG_SetErrorf SWIG_Perl_SetErrorf
#ifdef PERL_OBJECT
# define SWIG_MAYBE_PERL_OBJECT CPerlObj *pPerl,
#else
# define SWIG_MAYBE_PERL_OBJECT
#endif
static swig_cast_info *
SWIG_Perl_TypeCheckRV(SWIG_MAYBE_PERL_OBJECT SV *rv, swig_type_info *ty) {
SWIG_TypeCheck_Template(sv_derived_from(rv, (char *) iter->type->name), ty);
}
/* Function for getting a pointer value */
static int
SWIG_Perl_ConvertPtr(SWIG_MAYBE_PERL_OBJECT SV *sv, void **ptr, swig_type_info *_t, int flags) {
swig_cast_info *tc;
void *voidptr = (void *)0;
/* If magical, apply more magic */
if (SvGMAGICAL(sv))
mg_get(sv);
/* Check to see if this is an object */
if (sv_isobject(sv)) {
SV *tsv = (SV*) SvRV(sv);
IV tmp = 0;
if ((SvTYPE(tsv) == SVt_PVHV)) {
MAGIC *mg;
if (SvMAGICAL(tsv)) {
mg = mg_find(tsv,'P');
if (mg) {
sv = mg->mg_obj;
if (sv_isobject(sv)) {
tmp = SvIV((SV*)SvRV(sv));
}
}
} else {
return -1;
}
} else {
tmp = SvIV((SV*)SvRV(sv));
}
voidptr = (void *)tmp;
if (!_t) {
*(ptr) = voidptr;
return 0;
}
} else if (! SvOK(sv)) { /* Check for undef */
*(ptr) = (void *) 0;
return 0;
} else if (SvTYPE(sv) == SVt_RV) { /* Check for NULL pointer */
*(ptr) = (void *) 0;
if (!SvROK(sv))
return 0;
else
return -1;
} else { /* Don't know what it is */
*(ptr) = (void *) 0;
return -1;
}
if (_t) {
/* Now see if the types match */
char *_c = HvNAME(SvSTASH(SvRV(sv)));
tc = SWIG_TypeCheck(_c,_t);
if (!tc) {
*ptr = voidptr;
return -1;
}
*ptr = SWIG_TypeCast(tc,voidptr);
return 0;
}
*ptr = voidptr;
return 0;
}
static void
SWIG_Perl_MakePtr(SWIG_MAYBE_PERL_OBJECT SV *sv, void *ptr, swig_type_info *t, int flags) {
if (ptr && (flags & SWIG_SHADOW)) {
SV *self;
SV *obj=newSV(0);
HV *hash=newHV();
HV *stash;
sv_setref_pv(obj, (char *) t->name, ptr);
stash=SvSTASH(SvRV(obj));
if (flags & SWIG_OWNER) {
HV *hv;
GV *gv=*(GV**)hv_fetch(stash, "OWNER", 5, TRUE);
if (!isGV(gv))
gv_init(gv, stash, "OWNER", 5, FALSE);
hv=GvHVn(gv);
hv_store_ent(hv, obj, newSViv(1), 0);
}
sv_magic((SV *)hash, (SV *)obj, 'P', Nullch, 0);
SvREFCNT_dec(obj);
self=newRV_noinc((SV *)hash);
sv_setsv(sv, self);
SvREFCNT_dec((SV *)self);
sv_bless(sv, stash);
}
else {
sv_setref_pv(sv, (char *) t->name, ptr);
}
}
static SWIGINLINE SV *
SWIG_Perl_NewPointerObj(SWIG_MAYBE_PERL_OBJECT void *ptr, swig_type_info *t, int flags) {
SV *result = sv_newmortal();
SWIG_MakePtr(result, ptr, t, flags);
return result;
}
static void
SWIG_Perl_MakePackedObj(SWIG_MAYBE_PERL_OBJECT SV *sv, void *ptr, int sz, swig_type_info *type) {
char result[1024];
char *r = result;
if ((2*sz + 1 + strlen(type->name)) > 1000) return;
*(r++) = '_';
r = SWIG_PackData(r,ptr,sz);
strcpy(r,type->name);
sv_setpv(sv, result);
}
/* Convert a packed value value */
static int
SWIG_Perl_ConvertPacked(SWIG_MAYBE_PERL_OBJECT SV *obj, void *ptr, int sz, swig_type_info *ty, int flags) {
swig_cast_info *tc;
const char *c = 0;
if ((!obj) || (!SvOK(obj))) return -1;
c = SvPV(obj, PL_na);
/* Pointer values must start with leading underscore */
if (*c != '_') return -1;
c++;
c = SWIG_UnpackData(c,ptr,sz);
if (ty) {
tc = SWIG_TypeCheck(c,ty);
if (!tc) return -1;
}
return 0;
}
static SWIGINLINE void
SWIG_Perl_SetError(SWIG_MAYBE_PERL_OBJECT const char *error) {
if (error) sv_setpv(perl_get_sv("@", TRUE), error);
}
static SWIGINLINE void
SWIG_Perl_SetErrorSV(SWIG_MAYBE_PERL_OBJECT SV *error) {
if (error) sv_setsv(perl_get_sv("@", TRUE), error);
}
static void
SWIG_Perl_SetErrorf(const char *fmt, ...) {
va_list args;
va_start(args, fmt);
sv_vsetpvfn(perl_get_sv("@", TRUE), fmt, strlen(fmt), &args, Null(SV**), 0, Null(bool*));
va_end(args);
}
/* Macros for low-level exception handling */
#define SWIG_fail goto fail
#define SWIG_croak(x) { SWIG_SetError(x); goto fail; }
#define SWIG_croakSV(x) { SWIG_SetErrorSV(x); goto fail; }
/* most preprocessors do not support vararg macros :-( */
/* #define SWIG_croakf(x...) { SWIG_SetErrorf(x); goto fail; } */
typedef XS(SwigPerlWrapper);
typedef SwigPerlWrapper *SwigPerlWrapperPtr;
/* Structure for command table */
typedef struct {
const char *name;
SwigPerlWrapperPtr wrapper;
} swig_command_info;
/* Information for constant table */
#define SWIG_INT 1
#define SWIG_FLOAT 2
#define SWIG_STRING 3
#define SWIG_POINTER 4
#define SWIG_BINARY 5
/* Constant information structure */
typedef struct swig_constant_info {
int type;
const char *name;
long lvalue;
double dvalue;
void *pvalue;
swig_type_info **ptype;
} swig_constant_info;
#ifdef __cplusplus
}
#endif
/* Structure for variable table */
typedef struct {
const char *name;
SwigMagicFunc set;
SwigMagicFunc get;
swig_type_info **type;
} swig_variable_info;
/* Magic variable code */
#ifndef PERL_OBJECT
#define swig_create_magic(s,a,b,c) _swig_create_magic(s,a,b,c)
#ifndef MULTIPLICITY
static void _swig_create_magic(SV *sv, char *name, int (*set)(SV *, MAGIC *), int (*get)(SV *,MAGIC *)) {
#else
static void _swig_create_magic(SV *sv, char *name, int (*set)(struct interpreter*, SV *, MAGIC *), int (*get)(struct interpreter*, SV *,MAGIC *)) {
#endif
#else
# define swig_create_magic(s,a,b,c) _swig_create_magic(pPerl,s,a,b,c)
static void _swig_create_magic(CPerlObj *pPerl, SV *sv, const char *name, int (CPerlObj::*set)(SV *, MAGIC *), int (CPerlObj::*get)(SV *, MAGIC *)) {
#endif
MAGIC *mg;
sv_magic(sv,sv,'U',(char *) name,strlen(name));
mg = mg_find(sv,'U');
mg->mg_virtual = (MGVTBL *) malloc(sizeof(MGVTBL));
mg->mg_virtual->svt_get = (SwigMagicFuncHack) get;
mg->mg_virtual->svt_set = (SwigMagicFuncHack) set;
mg->mg_virtual->svt_len = 0;
mg->mg_virtual->svt_clear = 0;
mg->mg_virtual->svt_free = 0;
}
static swig_module_info *
SWIG_Perl_GetModule() {
static void *type_pointer = (void *)0;
SV *pointer;
/* first check if pointer already created */
if (!type_pointer) {
pointer = get_sv("swig_runtime_data::type_pointer" SWIG_RUNTIME_VERSION SWIG_TYPE_TABLE_NAME, FALSE);
if (pointer && SvOK(pointer)) {
type_pointer = INT2PTR(swig_type_info **, SvIV(pointer));
}
}
return (swig_module_info *) type_pointer;
}
static void
SWIG_Perl_SetModule(swig_module_info *module) {
SV *pointer;
/* create a new pointer */
pointer = get_sv("swig_runtime_data::type_pointer" SWIG_RUNTIME_VERSION SWIG_TYPE_TABLE_NAME, TRUE);
sv_setiv(pointer, PTR2IV(module));
}
#ifdef do_open
#undef do_open
#endif
#ifdef do_close
#undef do_close
#endif
#ifdef scalar
#undef scalar
#endif
#ifdef list
#undef list
#endif
#ifdef apply
#undef apply
#endif
#ifdef convert
#undef convert
#endif
#ifdef Error
#undef Error
#endif
#ifdef form
#undef form
#endif
#ifdef vform
#undef vform
#endif
#ifdef LABEL
#undef LABEL
#endif
#ifdef METHOD
#undef METHOD
#endif
#ifdef Move
#undef Move
#endif
#ifdef yylex
#undef yylex
#endif
#ifdef yyparse
#undef yyparse
#endif
#ifdef yyerror
#undef yyerror
#endif
#ifdef invert
#undef invert
#endif
#ifdef ref
#undef ref
#endif
#ifdef ENTER
#undef ENTER
#endif
#ifdef read
#undef read
#endif
#ifdef write
#undef write
#endif
#ifdef eof
#undef eof
#endif
#ifdef bool
#undef bool
#endif
#ifdef close
#undef close
#endif
#ifdef rewind
#undef rewind
#endif
/* -------- TYPES TABLE (BEGIN) -------- */
#define SWIGTYPE_p_EST_FVector swig_types[0]
#define SWIGTYPE_p_EST_IVector swig_types[1]
#define SWIGTYPE_p_EST_Track swig_types[2]
#define SWIGTYPE_p_EST_read_status swig_types[3]
#define SWIGTYPE_p_EST_write_status swig_types[4]
#define SWIGTYPE_p_float swig_types[5]
static swig_type_info *swig_types[7];
static swig_module_info swig_module = {swig_types, 6, 0, 0, 0, 0};
#define SWIG_TypeQuery(name) SWIG_TypeQueryModule(&swig_module, &swig_module, name)
#define SWIG_MangledTypeQuery(name) SWIG_MangledTypeQueryModule(&swig_module, &swig_module, name)
/* -------- TYPES TABLE (END) -------- */
#define SWIG_init boot_EST_Track
#define SWIG_name "EST_Trackc::boot_EST_Track"
#define SWIG_prefix "EST_Trackc::"
#ifdef __cplusplus
extern "C"
#endif
#ifndef PERL_OBJECT
#ifndef MULTIPLICITY
SWIGEXPORT void SWIG_init (CV* cv);
#else
SWIGEXPORT void SWIG_init (pTHXo_ CV* cv);
#endif
#else
SWIGEXPORT void SWIG_init (CV *cv, CPerlObj *);
#endif
#include "EST_Track.h"
#include "EST_track_aux.h"
#ifdef PERL_OBJECT
#define MAGIC_CLASS _wrap_EST_Track_var::
class _wrap_EST_Track_var : public CPerlObj {
public:
#else
#define MAGIC_CLASS
#endif
SWIGCLASS_STATIC int swig_magic_readonly(pTHX_ SV *sv, MAGIC *mg) {
MAGIC_PPERL
sv = sv; mg = mg;
croak("Value is read-only.");
return 0;
}
#ifdef PERL_OBJECT
};
#endif
#ifdef __cplusplus
extern "C" {
#endif
XS(_wrap_EST_Track_default_frame_shift_get) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
float result;
int argvi = 0;
dXSARGS;
if ((items < 1) || (items > 1)) {
SWIG_croak("Usage: EST_Track_default_frame_shift_get(self);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_default_frame_shift_get. Expected _p_EST_Track");
}
}
result = (float)(float) ((arg1)->default_frame_shift);
ST(argvi) = sv_newmortal();
sv_setnv(ST(argvi++), (double) result);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_default_sample_rate_get) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
int result;
int argvi = 0;
dXSARGS;
if ((items < 1) || (items > 1)) {
SWIG_croak("Usage: EST_Track_default_sample_rate_get(self);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_default_sample_rate_get. Expected _p_EST_Track");
}
}
result = (int)(int) ((arg1)->default_sample_rate);
ST(argvi) = sv_newmortal();
sv_setiv(ST(argvi++), (IV) result);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_new_EST_Track__SWIG_0) {
{
EST_Track *result;
int argvi = 0;
dXSARGS;
if ((items < 0) || (items > 0)) {
SWIG_croak("Usage: new_EST_Track();");
}
result = (EST_Track *)new EST_Track();
ST(argvi) = sv_newmortal();
SWIG_MakePtr(ST(argvi++), (void *) result, SWIGTYPE_p_EST_Track, SWIG_SHADOW|SWIG_OWNER);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_new_EST_Track__SWIG_1) {
{
EST_Track *arg1 = 0 ;
EST_Track *result;
int argvi = 0;
dXSARGS;
if ((items < 1) || (items > 1)) {
SWIG_croak("Usage: new_EST_Track(a);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of new_EST_Track. Expected _p_EST_Track");
}
}
result = (EST_Track *)new EST_Track((EST_Track const &)*arg1);
ST(argvi) = sv_newmortal();
SWIG_MakePtr(ST(argvi++), (void *) result, SWIGTYPE_p_EST_Track, SWIG_SHADOW|SWIG_OWNER);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_new_EST_Track__SWIG_2) {
{
int arg1 ;
int arg2 ;
EST_Track *result;
int argvi = 0;
dXSARGS;
if ((items < 2) || (items > 2)) {
SWIG_croak("Usage: new_EST_Track(num_frames,num_channels);");
}
arg1 = (int) SvIV(ST(0));
arg2 = (int) SvIV(ST(1));
result = (EST_Track *)new EST_Track(arg1,arg2);
ST(argvi) = sv_newmortal();
SWIG_MakePtr(ST(argvi++), (void *) result, SWIGTYPE_p_EST_Track, SWIG_SHADOW|SWIG_OWNER);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_new_EST_Track) {
dXSARGS;
if (items == 0) {
(*PL_markstack_ptr++);SWIG_CALLXS(_wrap_new_EST_Track__SWIG_0); return;
}
if (items == 1) {
int _v;
{
void *tmp;
if (SWIG_ConvertPtr(ST(0), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
(*PL_markstack_ptr++);SWIG_CALLXS(_wrap_new_EST_Track__SWIG_1); return;
}
}
if (items == 2) {
int _v;
{
_v = SvIOK(ST(0)) ? 1 : 0;
}
if (_v) {
{
_v = SvIOK(ST(1)) ? 1 : 0;
}
if (_v) {
(*PL_markstack_ptr++);SWIG_CALLXS(_wrap_new_EST_Track__SWIG_2); return;
}
}
}
croak("No matching function for overloaded 'new_EST_Track'");
XSRETURN(0);
}
XS(_wrap_delete_EST_Track) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
int argvi = 0;
dXSARGS;
if ((items < 1) || (items > 1)) {
SWIG_croak("Usage: delete_EST_Track(self);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of delete_EST_Track. Expected _p_EST_Track");
}
}
delete arg1;
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_resize__SWIG_0) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
int arg2 ;
int arg3 ;
bool arg4 ;
int argvi = 0;
dXSARGS;
if ((items < 4) || (items > 4)) {
SWIG_croak("Usage: EST_Track_resize(self,num_frames,num_channels,preserve);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_resize. Expected _p_EST_Track");
}
}
arg2 = (int) SvIV(ST(1));
arg3 = (int) SvIV(ST(2));
arg4 = SvIV(ST(3)) ? true : false;
(arg1)->resize(arg2,arg3,arg4);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_resize__SWIG_1) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
int arg2 ;
int arg3 ;
int argvi = 0;
dXSARGS;
if ((items < 3) || (items > 3)) {
SWIG_croak("Usage: EST_Track_resize(self,num_frames,num_channels);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_resize. Expected _p_EST_Track");
}
}
arg2 = (int) SvIV(ST(1));
arg3 = (int) SvIV(ST(2));
(arg1)->resize(arg2,arg3);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_resize) {
dXSARGS;
if (items == 3) {
int _v;
{
void *tmp;
if (SWIG_ConvertPtr(ST(0), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
_v = SvIOK(ST(1)) ? 1 : 0;
}
if (_v) {
{
_v = SvIOK(ST(2)) ? 1 : 0;
}
if (_v) {
(*PL_markstack_ptr++);SWIG_CALLXS(_wrap_EST_Track_resize__SWIG_1); return;
}
}
}
}
if (items == 4) {
int _v;
{
void *tmp;
if (SWIG_ConvertPtr(ST(0), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
_v = SvIOK(ST(1)) ? 1 : 0;
}
if (_v) {
{
_v = SvIOK(ST(2)) ? 1 : 0;
}
if (_v) {
{
_v = SvIOK(ST(3)) ? 1 : 0;
}
if (_v) {
(*PL_markstack_ptr++);SWIG_CALLXS(_wrap_EST_Track_resize__SWIG_0); return;
}
}
}
}
}
croak("No matching function for overloaded 'EST_Track_resize'");
XSRETURN(0);
}
XS(_wrap_EST_Track_set_num_channels__SWIG_0) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
int arg2 ;
bool arg3 ;
int argvi = 0;
dXSARGS;
if ((items < 3) || (items > 3)) {
SWIG_croak("Usage: EST_Track_set_num_channels(self,n,preserve);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_set_num_channels. Expected _p_EST_Track");
}
}
arg2 = (int) SvIV(ST(1));
arg3 = SvIV(ST(2)) ? true : false;
(arg1)->set_num_channels(arg2,arg3);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_set_num_channels__SWIG_1) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
int arg2 ;
int argvi = 0;
dXSARGS;
if ((items < 2) || (items > 2)) {
SWIG_croak("Usage: EST_Track_set_num_channels(self,n);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_set_num_channels. Expected _p_EST_Track");
}
}
arg2 = (int) SvIV(ST(1));
(arg1)->set_num_channels(arg2);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_set_num_channels) {
dXSARGS;
if (items == 2) {
int _v;
{
void *tmp;
if (SWIG_ConvertPtr(ST(0), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
_v = SvIOK(ST(1)) ? 1 : 0;
}
if (_v) {
(*PL_markstack_ptr++);SWIG_CALLXS(_wrap_EST_Track_set_num_channels__SWIG_1); return;
}
}
}
if (items == 3) {
int _v;
{
void *tmp;
if (SWIG_ConvertPtr(ST(0), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
_v = SvIOK(ST(1)) ? 1 : 0;
}
if (_v) {
{
_v = SvIOK(ST(2)) ? 1 : 0;
}
if (_v) {
(*PL_markstack_ptr++);SWIG_CALLXS(_wrap_EST_Track_set_num_channels__SWIG_0); return;
}
}
}
}
croak("No matching function for overloaded 'EST_Track_set_num_channels'");
XSRETURN(0);
}
XS(_wrap_EST_Track_set_num_frames__SWIG_0) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
int arg2 ;
bool arg3 ;
int argvi = 0;
dXSARGS;
if ((items < 3) || (items > 3)) {
SWIG_croak("Usage: EST_Track_set_num_frames(self,n,preserve);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_set_num_frames. Expected _p_EST_Track");
}
}
arg2 = (int) SvIV(ST(1));
arg3 = SvIV(ST(2)) ? true : false;
(arg1)->set_num_frames(arg2,arg3);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_set_num_frames__SWIG_1) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
int arg2 ;
int argvi = 0;
dXSARGS;
if ((items < 2) || (items > 2)) {
SWIG_croak("Usage: EST_Track_set_num_frames(self,n);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_set_num_frames. Expected _p_EST_Track");
}
}
arg2 = (int) SvIV(ST(1));
(arg1)->set_num_frames(arg2);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_set_num_frames) {
dXSARGS;
if (items == 2) {
int _v;
{
void *tmp;
if (SWIG_ConvertPtr(ST(0), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
_v = SvIOK(ST(1)) ? 1 : 0;
}
if (_v) {
(*PL_markstack_ptr++);SWIG_CALLXS(_wrap_EST_Track_set_num_frames__SWIG_1); return;
}
}
}
if (items == 3) {
int _v;
{
void *tmp;
if (SWIG_ConvertPtr(ST(0), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
_v = SvIOK(ST(1)) ? 1 : 0;
}
if (_v) {
{
_v = SvIOK(ST(2)) ? 1 : 0;
}
if (_v) {
(*PL_markstack_ptr++);SWIG_CALLXS(_wrap_EST_Track_set_num_frames__SWIG_0); return;
}
}
}
}
croak("No matching function for overloaded 'EST_Track_set_num_frames'");
XSRETURN(0);
}
XS(_wrap_EST_Track_set_channel_name) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
EST_String *arg2 = 0 ;
int arg3 ;
EST_String temp2 ;
int argvi = 0;
dXSARGS;
if ((items < 3) || (items > 3)) {
SWIG_croak("Usage: EST_Track_set_channel_name(self,name,channel);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_set_channel_name. Expected _p_EST_Track");
}
}
{
STRLEN len; const char* str = SvPV(ST(1), len);
temp2 = EST_String( str, len, 0, len );
arg2 = &temp2;
}
arg3 = (int) SvIV(ST(2));
(arg1)->set_channel_name((EST_String const &)*arg2,arg3);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_set_aux_channel_name) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
EST_String *arg2 = 0 ;
int arg3 ;
EST_String temp2 ;
int argvi = 0;
dXSARGS;
if ((items < 3) || (items > 3)) {
SWIG_croak("Usage: EST_Track_set_aux_channel_name(self,name,channel);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_set_aux_channel_name. Expected _p_EST_Track");
}
}
{
STRLEN len; const char* str = SvPV(ST(1), len);
temp2 = EST_String( str, len, 0, len );
arg2 = &temp2;
}
arg3 = (int) SvIV(ST(2));
(arg1)->set_aux_channel_name((EST_String const &)*arg2,arg3);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_copy_setup) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
EST_Track *arg2 = 0 ;
int argvi = 0;
dXSARGS;
if ((items < 2) || (items > 2)) {
SWIG_croak("Usage: EST_Track_copy_setup(self,a);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_copy_setup. Expected _p_EST_Track");
}
}
{
if (SWIG_ConvertPtr(ST(1), (void **) &arg2, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 2 of EST_Track_copy_setup. Expected _p_EST_Track");
}
}
(arg1)->copy_setup((EST_Track const &)*arg2);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_name) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
EST_String result;
int argvi = 0;
dXSARGS;
if ((items < 1) || (items > 1)) {
SWIG_croak("Usage: EST_Track_name(self);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_name. Expected _p_EST_Track");
}
}
result = ((EST_Track const *)arg1)->name();
ST(argvi) = sv_newmortal();
sv_setpvn((SV*)ST(argvi++),(char *)result, (&result)->length());
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_set_name) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
EST_String *arg2 = 0 ;
EST_String temp2 ;
int argvi = 0;
dXSARGS;
if ((items < 2) || (items > 2)) {
SWIG_croak("Usage: EST_Track_set_name(self,n);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_set_name. Expected _p_EST_Track");
}
}
{
STRLEN len; const char* str = SvPV(ST(1), len);
temp2 = EST_String( str, len, 0, len );
arg2 = &temp2;
}
(arg1)->set_name((EST_String const &)*arg2);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_frame__SWIG_0) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
EST_FVector *arg2 = 0 ;
int arg3 ;
int arg4 ;
int arg5 ;
int argvi = 0;
dXSARGS;
if ((items < 5) || (items > 5)) {
SWIG_croak("Usage: EST_Track_frame(self,fv,n,startf,nf);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_frame. Expected _p_EST_Track");
}
}
{
if (SWIG_ConvertPtr(ST(1), (void **) &arg2, SWIGTYPE_p_EST_FVector,0) < 0) {
SWIG_croak("Type error in argument 2 of EST_Track_frame. Expected _p_EST_FVector");
}
}
arg3 = (int) SvIV(ST(2));
arg4 = (int) SvIV(ST(3));
arg5 = (int) SvIV(ST(4));
(arg1)->frame(*arg2,arg3,arg4,arg5);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_frame__SWIG_1) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
EST_FVector *arg2 = 0 ;
int arg3 ;
int arg4 ;
int argvi = 0;
dXSARGS;
if ((items < 4) || (items > 4)) {
SWIG_croak("Usage: EST_Track_frame(self,fv,n,startf);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_frame. Expected _p_EST_Track");
}
}
{
if (SWIG_ConvertPtr(ST(1), (void **) &arg2, SWIGTYPE_p_EST_FVector,0) < 0) {
SWIG_croak("Type error in argument 2 of EST_Track_frame. Expected _p_EST_FVector");
}
}
arg3 = (int) SvIV(ST(2));
arg4 = (int) SvIV(ST(3));
(arg1)->frame(*arg2,arg3,arg4);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_frame__SWIG_2) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
EST_FVector *arg2 = 0 ;
int arg3 ;
int argvi = 0;
dXSARGS;
if ((items < 3) || (items > 3)) {
SWIG_croak("Usage: EST_Track_frame(self,fv,n);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_frame. Expected _p_EST_Track");
}
}
{
if (SWIG_ConvertPtr(ST(1), (void **) &arg2, SWIGTYPE_p_EST_FVector,0) < 0) {
SWIG_croak("Type error in argument 2 of EST_Track_frame. Expected _p_EST_FVector");
}
}
arg3 = (int) SvIV(ST(2));
(arg1)->frame(*arg2,arg3);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_frame) {
dXSARGS;
if (items == 3) {
int _v;
{
void *tmp;
if (SWIG_ConvertPtr(ST(0), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
void *tmp;
if (SWIG_ConvertPtr(ST(1), (void **) &tmp, SWIGTYPE_p_EST_FVector, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
_v = SvIOK(ST(2)) ? 1 : 0;
}
if (_v) {
(*PL_markstack_ptr++);SWIG_CALLXS(_wrap_EST_Track_frame__SWIG_2); return;
}
}
}
}
if (items == 4) {
int _v;
{
void *tmp;
if (SWIG_ConvertPtr(ST(0), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
void *tmp;
if (SWIG_ConvertPtr(ST(1), (void **) &tmp, SWIGTYPE_p_EST_FVector, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
_v = SvIOK(ST(2)) ? 1 : 0;
}
if (_v) {
{
_v = SvIOK(ST(3)) ? 1 : 0;
}
if (_v) {
(*PL_markstack_ptr++);SWIG_CALLXS(_wrap_EST_Track_frame__SWIG_1); return;
}
}
}
}
}
if (items == 5) {
int _v;
{
void *tmp;
if (SWIG_ConvertPtr(ST(0), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
void *tmp;
if (SWIG_ConvertPtr(ST(1), (void **) &tmp, SWIGTYPE_p_EST_FVector, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
_v = SvIOK(ST(2)) ? 1 : 0;
}
if (_v) {
{
_v = SvIOK(ST(3)) ? 1 : 0;
}
if (_v) {
{
_v = SvIOK(ST(4)) ? 1 : 0;
}
if (_v) {
(*PL_markstack_ptr++);SWIG_CALLXS(_wrap_EST_Track_frame__SWIG_0); return;
}
}
}
}
}
}
croak("No matching function for overloaded 'EST_Track_frame'");
XSRETURN(0);
}
XS(_wrap_EST_Track_channel__SWIG_0) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
EST_FVector *arg2 = 0 ;
int arg3 ;
int arg4 ;
int arg5 ;
int argvi = 0;
dXSARGS;
if ((items < 5) || (items > 5)) {
SWIG_croak("Usage: EST_Track_channel(self,cv,n,startf,nf);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_channel. Expected _p_EST_Track");
}
}
{
if (SWIG_ConvertPtr(ST(1), (void **) &arg2, SWIGTYPE_p_EST_FVector,0) < 0) {
SWIG_croak("Type error in argument 2 of EST_Track_channel. Expected _p_EST_FVector");
}
}
arg3 = (int) SvIV(ST(2));
arg4 = (int) SvIV(ST(3));
arg5 = (int) SvIV(ST(4));
(arg1)->channel(*arg2,arg3,arg4,arg5);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_channel__SWIG_1) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
EST_FVector *arg2 = 0 ;
int arg3 ;
int arg4 ;
int argvi = 0;
dXSARGS;
if ((items < 4) || (items > 4)) {
SWIG_croak("Usage: EST_Track_channel(self,cv,n,startf);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_channel. Expected _p_EST_Track");
}
}
{
if (SWIG_ConvertPtr(ST(1), (void **) &arg2, SWIGTYPE_p_EST_FVector,0) < 0) {
SWIG_croak("Type error in argument 2 of EST_Track_channel. Expected _p_EST_FVector");
}
}
arg3 = (int) SvIV(ST(2));
arg4 = (int) SvIV(ST(3));
(arg1)->channel(*arg2,arg3,arg4);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_channel__SWIG_2) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
EST_FVector *arg2 = 0 ;
int arg3 ;
int argvi = 0;
dXSARGS;
if ((items < 3) || (items > 3)) {
SWIG_croak("Usage: EST_Track_channel(self,cv,n);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_channel. Expected _p_EST_Track");
}
}
{
if (SWIG_ConvertPtr(ST(1), (void **) &arg2, SWIGTYPE_p_EST_FVector,0) < 0) {
SWIG_croak("Type error in argument 2 of EST_Track_channel. Expected _p_EST_FVector");
}
}
arg3 = (int) SvIV(ST(2));
(arg1)->channel(*arg2,arg3);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_channel__SWIG_3) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
EST_FVector *arg2 = 0 ;
char *arg3 = (char *) 0 ;
int arg4 ;
int arg5 ;
int argvi = 0;
dXSARGS;
if ((items < 5) || (items > 5)) {
SWIG_croak("Usage: EST_Track_channel(self,cv,name,startf,nf);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_channel. Expected _p_EST_Track");
}
}
{
if (SWIG_ConvertPtr(ST(1), (void **) &arg2, SWIGTYPE_p_EST_FVector,0) < 0) {
SWIG_croak("Type error in argument 2 of EST_Track_channel. Expected _p_EST_FVector");
}
}
if (!SvOK((SV*) ST(2))) arg3 = 0;
else arg3 = (char *) SvPV(ST(2), PL_na);
arg4 = (int) SvIV(ST(3));
arg5 = (int) SvIV(ST(4));
(arg1)->channel(*arg2,(char const *)arg3,arg4,arg5);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_channel__SWIG_4) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
EST_FVector *arg2 = 0 ;
char *arg3 = (char *) 0 ;
int arg4 ;
int argvi = 0;
dXSARGS;
if ((items < 4) || (items > 4)) {
SWIG_croak("Usage: EST_Track_channel(self,cv,name,startf);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_channel. Expected _p_EST_Track");
}
}
{
if (SWIG_ConvertPtr(ST(1), (void **) &arg2, SWIGTYPE_p_EST_FVector,0) < 0) {
SWIG_croak("Type error in argument 2 of EST_Track_channel. Expected _p_EST_FVector");
}
}
if (!SvOK((SV*) ST(2))) arg3 = 0;
else arg3 = (char *) SvPV(ST(2), PL_na);
arg4 = (int) SvIV(ST(3));
(arg1)->channel(*arg2,(char const *)arg3,arg4);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_channel__SWIG_5) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
EST_FVector *arg2 = 0 ;
char *arg3 = (char *) 0 ;
int argvi = 0;
dXSARGS;
if ((items < 3) || (items > 3)) {
SWIG_croak("Usage: EST_Track_channel(self,cv,name);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_channel. Expected _p_EST_Track");
}
}
{
if (SWIG_ConvertPtr(ST(1), (void **) &arg2, SWIGTYPE_p_EST_FVector,0) < 0) {
SWIG_croak("Type error in argument 2 of EST_Track_channel. Expected _p_EST_FVector");
}
}
if (!SvOK((SV*) ST(2))) arg3 = 0;
else arg3 = (char *) SvPV(ST(2), PL_na);
(arg1)->channel(*arg2,(char const *)arg3);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_channel) {
dXSARGS;
if (items == 3) {
int _v;
{
void *tmp;
if (SWIG_ConvertPtr(ST(0), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
void *tmp;
if (SWIG_ConvertPtr(ST(1), (void **) &tmp, SWIGTYPE_p_EST_FVector, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
_v = SvIOK(ST(2)) ? 1 : 0;
}
if (_v) {
(*PL_markstack_ptr++);SWIG_CALLXS(_wrap_EST_Track_channel__SWIG_2); return;
}
}
}
}
if (items == 3) {
int _v;
{
void *tmp;
if (SWIG_ConvertPtr(ST(0), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
void *tmp;
if (SWIG_ConvertPtr(ST(1), (void **) &tmp, SWIGTYPE_p_EST_FVector, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
_v = SvPOK(ST(2)) ? 1 : 0;
}
if (_v) {
(*PL_markstack_ptr++);SWIG_CALLXS(_wrap_EST_Track_channel__SWIG_5); return;
}
}
}
}
if (items == 4) {
int _v;
{
void *tmp;
if (SWIG_ConvertPtr(ST(0), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
void *tmp;
if (SWIG_ConvertPtr(ST(1), (void **) &tmp, SWIGTYPE_p_EST_FVector, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
_v = SvIOK(ST(2)) ? 1 : 0;
}
if (_v) {
{
_v = SvIOK(ST(3)) ? 1 : 0;
}
if (_v) {
(*PL_markstack_ptr++);SWIG_CALLXS(_wrap_EST_Track_channel__SWIG_1); return;
}
}
}
}
}
if (items == 4) {
int _v;
{
void *tmp;
if (SWIG_ConvertPtr(ST(0), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
void *tmp;
if (SWIG_ConvertPtr(ST(1), (void **) &tmp, SWIGTYPE_p_EST_FVector, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
_v = SvPOK(ST(2)) ? 1 : 0;
}
if (_v) {
{
_v = SvIOK(ST(3)) ? 1 : 0;
}
if (_v) {
(*PL_markstack_ptr++);SWIG_CALLXS(_wrap_EST_Track_channel__SWIG_4); return;
}
}
}
}
}
if (items == 5) {
int _v;
{
void *tmp;
if (SWIG_ConvertPtr(ST(0), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
void *tmp;
if (SWIG_ConvertPtr(ST(1), (void **) &tmp, SWIGTYPE_p_EST_FVector, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
_v = SvIOK(ST(2)) ? 1 : 0;
}
if (_v) {
{
_v = SvIOK(ST(3)) ? 1 : 0;
}
if (_v) {
{
_v = SvIOK(ST(4)) ? 1 : 0;
}
if (_v) {
(*PL_markstack_ptr++);SWIG_CALLXS(_wrap_EST_Track_channel__SWIG_0); return;
}
}
}
}
}
}
if (items == 5) {
int _v;
{
void *tmp;
if (SWIG_ConvertPtr(ST(0), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
void *tmp;
if (SWIG_ConvertPtr(ST(1), (void **) &tmp, SWIGTYPE_p_EST_FVector, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
_v = SvPOK(ST(2)) ? 1 : 0;
}
if (_v) {
{
_v = SvIOK(ST(3)) ? 1 : 0;
}
if (_v) {
{
_v = SvIOK(ST(4)) ? 1 : 0;
}
if (_v) {
(*PL_markstack_ptr++);SWIG_CALLXS(_wrap_EST_Track_channel__SWIG_3); return;
}
}
}
}
}
}
croak("No matching function for overloaded 'EST_Track_channel'");
XSRETURN(0);
}
XS(_wrap_EST_Track_sub_track__SWIG_0) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
EST_Track *arg2 = 0 ;
int arg3 ;
int arg4 ;
int arg5 ;
int arg6 ;
int argvi = 0;
dXSARGS;
if ((items < 6) || (items > 6)) {
SWIG_croak("Usage: EST_Track_sub_track(self,st,start_frame,nframes,start_chan,nchans);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_sub_track. Expected _p_EST_Track");
}
}
{
if (SWIG_ConvertPtr(ST(1), (void **) &arg2, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 2 of EST_Track_sub_track. Expected _p_EST_Track");
}
}
arg3 = (int) SvIV(ST(2));
arg4 = (int) SvIV(ST(3));
arg5 = (int) SvIV(ST(4));
arg6 = (int) SvIV(ST(5));
(arg1)->sub_track(*arg2,arg3,arg4,arg5,arg6);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_sub_track__SWIG_1) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
EST_Track *arg2 = 0 ;
int arg3 ;
int arg4 ;
int arg5 ;
int argvi = 0;
dXSARGS;
if ((items < 5) || (items > 5)) {
SWIG_croak("Usage: EST_Track_sub_track(self,st,start_frame,nframes,start_chan);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_sub_track. Expected _p_EST_Track");
}
}
{
if (SWIG_ConvertPtr(ST(1), (void **) &arg2, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 2 of EST_Track_sub_track. Expected _p_EST_Track");
}
}
arg3 = (int) SvIV(ST(2));
arg4 = (int) SvIV(ST(3));
arg5 = (int) SvIV(ST(4));
(arg1)->sub_track(*arg2,arg3,arg4,arg5);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_sub_track__SWIG_2) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
EST_Track *arg2 = 0 ;
int arg3 ;
int arg4 ;
int argvi = 0;
dXSARGS;
if ((items < 4) || (items > 4)) {
SWIG_croak("Usage: EST_Track_sub_track(self,st,start_frame,nframes);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_sub_track. Expected _p_EST_Track");
}
}
{
if (SWIG_ConvertPtr(ST(1), (void **) &arg2, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 2 of EST_Track_sub_track. Expected _p_EST_Track");
}
}
arg3 = (int) SvIV(ST(2));
arg4 = (int) SvIV(ST(3));
(arg1)->sub_track(*arg2,arg3,arg4);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_sub_track__SWIG_3) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
EST_Track *arg2 = 0 ;
int arg3 ;
int argvi = 0;
dXSARGS;
if ((items < 3) || (items > 3)) {
SWIG_croak("Usage: EST_Track_sub_track(self,st,start_frame);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_sub_track. Expected _p_EST_Track");
}
}
{
if (SWIG_ConvertPtr(ST(1), (void **) &arg2, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 2 of EST_Track_sub_track. Expected _p_EST_Track");
}
}
arg3 = (int) SvIV(ST(2));
(arg1)->sub_track(*arg2,arg3);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_sub_track__SWIG_4) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
EST_Track *arg2 = 0 ;
int argvi = 0;
dXSARGS;
if ((items < 2) || (items > 2)) {
SWIG_croak("Usage: EST_Track_sub_track(self,st);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_sub_track. Expected _p_EST_Track");
}
}
{
if (SWIG_ConvertPtr(ST(1), (void **) &arg2, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 2 of EST_Track_sub_track. Expected _p_EST_Track");
}
}
(arg1)->sub_track(*arg2);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_sub_track) {
dXSARGS;
if (items == 2) {
int _v;
{
void *tmp;
if (SWIG_ConvertPtr(ST(0), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
void *tmp;
if (SWIG_ConvertPtr(ST(1), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
(*PL_markstack_ptr++);SWIG_CALLXS(_wrap_EST_Track_sub_track__SWIG_4); return;
}
}
}
if (items == 3) {
int _v;
{
void *tmp;
if (SWIG_ConvertPtr(ST(0), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
void *tmp;
if (SWIG_ConvertPtr(ST(1), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
_v = SvIOK(ST(2)) ? 1 : 0;
}
if (_v) {
(*PL_markstack_ptr++);SWIG_CALLXS(_wrap_EST_Track_sub_track__SWIG_3); return;
}
}
}
}
if (items == 4) {
int _v;
{
void *tmp;
if (SWIG_ConvertPtr(ST(0), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
void *tmp;
if (SWIG_ConvertPtr(ST(1), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
_v = SvIOK(ST(2)) ? 1 : 0;
}
if (_v) {
{
_v = SvIOK(ST(3)) ? 1 : 0;
}
if (_v) {
(*PL_markstack_ptr++);SWIG_CALLXS(_wrap_EST_Track_sub_track__SWIG_2); return;
}
}
}
}
}
if (items == 5) {
int _v;
{
void *tmp;
if (SWIG_ConvertPtr(ST(0), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
void *tmp;
if (SWIG_ConvertPtr(ST(1), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
_v = SvIOK(ST(2)) ? 1 : 0;
}
if (_v) {
{
_v = SvIOK(ST(3)) ? 1 : 0;
}
if (_v) {
{
_v = SvIOK(ST(4)) ? 1 : 0;
}
if (_v) {
(*PL_markstack_ptr++);SWIG_CALLXS(_wrap_EST_Track_sub_track__SWIG_1); return;
}
}
}
}
}
}
if (items == 6) {
int _v;
{
void *tmp;
if (SWIG_ConvertPtr(ST(0), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
void *tmp;
if (SWIG_ConvertPtr(ST(1), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
_v = SvIOK(ST(2)) ? 1 : 0;
}
if (_v) {
{
_v = SvIOK(ST(3)) ? 1 : 0;
}
if (_v) {
{
_v = SvIOK(ST(4)) ? 1 : 0;
}
if (_v) {
{
_v = SvIOK(ST(5)) ? 1 : 0;
}
if (_v) {
(*PL_markstack_ptr++);SWIG_CALLXS(_wrap_EST_Track_sub_track__SWIG_0); return;
}
}
}
}
}
}
}
croak("No matching function for overloaded 'EST_Track_sub_track'");
XSRETURN(0);
}
XS(_wrap_EST_Track_copy_sub_track__SWIG_0) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
EST_Track *arg2 = 0 ;
int arg3 ;
int arg4 ;
int arg5 ;
int arg6 ;
int argvi = 0;
dXSARGS;
if ((items < 6) || (items > 6)) {
SWIG_croak("Usage: EST_Track_copy_sub_track(self,st,start_frame,nframes,start_chan,nchans);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_copy_sub_track. Expected _p_EST_Track");
}
}
{
if (SWIG_ConvertPtr(ST(1), (void **) &arg2, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 2 of EST_Track_copy_sub_track. Expected _p_EST_Track");
}
}
arg3 = (int) SvIV(ST(2));
arg4 = (int) SvIV(ST(3));
arg5 = (int) SvIV(ST(4));
arg6 = (int) SvIV(ST(5));
((EST_Track const *)arg1)->copy_sub_track(*arg2,arg3,arg4,arg5,arg6);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_copy_sub_track__SWIG_1) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
EST_Track *arg2 = 0 ;
int arg3 ;
int arg4 ;
int arg5 ;
int argvi = 0;
dXSARGS;
if ((items < 5) || (items > 5)) {
SWIG_croak("Usage: EST_Track_copy_sub_track(self,st,start_frame,nframes,start_chan);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_copy_sub_track. Expected _p_EST_Track");
}
}
{
if (SWIG_ConvertPtr(ST(1), (void **) &arg2, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 2 of EST_Track_copy_sub_track. Expected _p_EST_Track");
}
}
arg3 = (int) SvIV(ST(2));
arg4 = (int) SvIV(ST(3));
arg5 = (int) SvIV(ST(4));
((EST_Track const *)arg1)->copy_sub_track(*arg2,arg3,arg4,arg5);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_copy_sub_track__SWIG_2) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
EST_Track *arg2 = 0 ;
int arg3 ;
int arg4 ;
int argvi = 0;
dXSARGS;
if ((items < 4) || (items > 4)) {
SWIG_croak("Usage: EST_Track_copy_sub_track(self,st,start_frame,nframes);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_copy_sub_track. Expected _p_EST_Track");
}
}
{
if (SWIG_ConvertPtr(ST(1), (void **) &arg2, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 2 of EST_Track_copy_sub_track. Expected _p_EST_Track");
}
}
arg3 = (int) SvIV(ST(2));
arg4 = (int) SvIV(ST(3));
((EST_Track const *)arg1)->copy_sub_track(*arg2,arg3,arg4);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_copy_sub_track__SWIG_3) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
EST_Track *arg2 = 0 ;
int arg3 ;
int argvi = 0;
dXSARGS;
if ((items < 3) || (items > 3)) {
SWIG_croak("Usage: EST_Track_copy_sub_track(self,st,start_frame);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_copy_sub_track. Expected _p_EST_Track");
}
}
{
if (SWIG_ConvertPtr(ST(1), (void **) &arg2, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 2 of EST_Track_copy_sub_track. Expected _p_EST_Track");
}
}
arg3 = (int) SvIV(ST(2));
((EST_Track const *)arg1)->copy_sub_track(*arg2,arg3);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_copy_sub_track__SWIG_4) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
EST_Track *arg2 = 0 ;
int argvi = 0;
dXSARGS;
if ((items < 2) || (items > 2)) {
SWIG_croak("Usage: EST_Track_copy_sub_track(self,st);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_copy_sub_track. Expected _p_EST_Track");
}
}
{
if (SWIG_ConvertPtr(ST(1), (void **) &arg2, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 2 of EST_Track_copy_sub_track. Expected _p_EST_Track");
}
}
((EST_Track const *)arg1)->copy_sub_track(*arg2);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_copy_sub_track) {
dXSARGS;
if (items == 2) {
int _v;
{
void *tmp;
if (SWIG_ConvertPtr(ST(0), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
void *tmp;
if (SWIG_ConvertPtr(ST(1), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
(*PL_markstack_ptr++);SWIG_CALLXS(_wrap_EST_Track_copy_sub_track__SWIG_4); return;
}
}
}
if (items == 3) {
int _v;
{
void *tmp;
if (SWIG_ConvertPtr(ST(0), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
void *tmp;
if (SWIG_ConvertPtr(ST(1), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
_v = SvIOK(ST(2)) ? 1 : 0;
}
if (_v) {
(*PL_markstack_ptr++);SWIG_CALLXS(_wrap_EST_Track_copy_sub_track__SWIG_3); return;
}
}
}
}
if (items == 4) {
int _v;
{
void *tmp;
if (SWIG_ConvertPtr(ST(0), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
void *tmp;
if (SWIG_ConvertPtr(ST(1), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
_v = SvIOK(ST(2)) ? 1 : 0;
}
if (_v) {
{
_v = SvIOK(ST(3)) ? 1 : 0;
}
if (_v) {
(*PL_markstack_ptr++);SWIG_CALLXS(_wrap_EST_Track_copy_sub_track__SWIG_2); return;
}
}
}
}
}
if (items == 5) {
int _v;
{
void *tmp;
if (SWIG_ConvertPtr(ST(0), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
void *tmp;
if (SWIG_ConvertPtr(ST(1), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
_v = SvIOK(ST(2)) ? 1 : 0;
}
if (_v) {
{
_v = SvIOK(ST(3)) ? 1 : 0;
}
if (_v) {
{
_v = SvIOK(ST(4)) ? 1 : 0;
}
if (_v) {
(*PL_markstack_ptr++);SWIG_CALLXS(_wrap_EST_Track_copy_sub_track__SWIG_1); return;
}
}
}
}
}
}
if (items == 6) {
int _v;
{
void *tmp;
if (SWIG_ConvertPtr(ST(0), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
void *tmp;
if (SWIG_ConvertPtr(ST(1), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
_v = SvIOK(ST(2)) ? 1 : 0;
}
if (_v) {
{
_v = SvIOK(ST(3)) ? 1 : 0;
}
if (_v) {
{
_v = SvIOK(ST(4)) ? 1 : 0;
}
if (_v) {
{
_v = SvIOK(ST(5)) ? 1 : 0;
}
if (_v) {
(*PL_markstack_ptr++);SWIG_CALLXS(_wrap_EST_Track_copy_sub_track__SWIG_0); return;
}
}
}
}
}
}
}
croak("No matching function for overloaded 'EST_Track_copy_sub_track'");
XSRETURN(0);
}
XS(_wrap_EST_Track_copy_sub_track_out__SWIG_0) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
EST_Track *arg2 = 0 ;
EST_FVector *arg3 = 0 ;
int argvi = 0;
dXSARGS;
if ((items < 3) || (items > 3)) {
SWIG_croak("Usage: EST_Track_copy_sub_track_out(self,st,frame_times);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_copy_sub_track_out. Expected _p_EST_Track");
}
}
{
if (SWIG_ConvertPtr(ST(1), (void **) &arg2, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 2 of EST_Track_copy_sub_track_out. Expected _p_EST_Track");
}
}
{
if (SWIG_ConvertPtr(ST(2), (void **) &arg3, SWIGTYPE_p_EST_FVector,0) < 0) {
SWIG_croak("Type error in argument 3 of EST_Track_copy_sub_track_out. Expected _p_EST_FVector");
}
}
((EST_Track const *)arg1)->copy_sub_track_out(*arg2,(EST_FVector const &)*arg3);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_copy_sub_track_out__SWIG_1) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
EST_Track *arg2 = 0 ;
EST_IVector *arg3 = 0 ;
int argvi = 0;
dXSARGS;
if ((items < 3) || (items > 3)) {
SWIG_croak("Usage: EST_Track_copy_sub_track_out(self,st,frame_indices);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_copy_sub_track_out. Expected _p_EST_Track");
}
}
{
if (SWIG_ConvertPtr(ST(1), (void **) &arg2, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 2 of EST_Track_copy_sub_track_out. Expected _p_EST_Track");
}
}
{
if (SWIG_ConvertPtr(ST(2), (void **) &arg3, SWIGTYPE_p_EST_IVector,0) < 0) {
SWIG_croak("Type error in argument 3 of EST_Track_copy_sub_track_out. Expected _p_EST_IVector");
}
}
((EST_Track const *)arg1)->copy_sub_track_out(*arg2,(EST_IVector const &)*arg3);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_copy_sub_track_out) {
dXSARGS;
if (items == 3) {
int _v;
{
void *tmp;
if (SWIG_ConvertPtr(ST(0), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
void *tmp;
if (SWIG_ConvertPtr(ST(1), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
void *tmp;
if (SWIG_ConvertPtr(ST(2), (void **) &tmp, SWIGTYPE_p_EST_FVector, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
(*PL_markstack_ptr++);SWIG_CALLXS(_wrap_EST_Track_copy_sub_track_out__SWIG_0); return;
}
}
}
}
if (items == 3) {
int _v;
{
void *tmp;
if (SWIG_ConvertPtr(ST(0), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
void *tmp;
if (SWIG_ConvertPtr(ST(1), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
void *tmp;
if (SWIG_ConvertPtr(ST(2), (void **) &tmp, SWIGTYPE_p_EST_IVector, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
(*PL_markstack_ptr++);SWIG_CALLXS(_wrap_EST_Track_copy_sub_track_out__SWIG_1); return;
}
}
}
}
croak("No matching function for overloaded 'EST_Track_copy_sub_track_out'");
XSRETURN(0);
}
XS(_wrap_EST_Track_copy_channel_out__SWIG_0) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
int arg2 ;
EST_FVector *arg3 = 0 ;
int arg4 ;
int arg5 ;
int argvi = 0;
dXSARGS;
if ((items < 5) || (items > 5)) {
SWIG_croak("Usage: EST_Track_copy_channel_out(self,n,f,offset,nf);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_copy_channel_out. Expected _p_EST_Track");
}
}
arg2 = (int) SvIV(ST(1));
{
if (SWIG_ConvertPtr(ST(2), (void **) &arg3, SWIGTYPE_p_EST_FVector,0) < 0) {
SWIG_croak("Type error in argument 3 of EST_Track_copy_channel_out. Expected _p_EST_FVector");
}
}
arg4 = (int) SvIV(ST(3));
arg5 = (int) SvIV(ST(4));
((EST_Track const *)arg1)->copy_channel_out(arg2,*arg3,arg4,arg5);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_copy_channel_out__SWIG_1) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
int arg2 ;
EST_FVector *arg3 = 0 ;
int arg4 ;
int argvi = 0;
dXSARGS;
if ((items < 4) || (items > 4)) {
SWIG_croak("Usage: EST_Track_copy_channel_out(self,n,f,offset);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_copy_channel_out. Expected _p_EST_Track");
}
}
arg2 = (int) SvIV(ST(1));
{
if (SWIG_ConvertPtr(ST(2), (void **) &arg3, SWIGTYPE_p_EST_FVector,0) < 0) {
SWIG_croak("Type error in argument 3 of EST_Track_copy_channel_out. Expected _p_EST_FVector");
}
}
arg4 = (int) SvIV(ST(3));
((EST_Track const *)arg1)->copy_channel_out(arg2,*arg3,arg4);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_copy_channel_out__SWIG_2) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
int arg2 ;
EST_FVector *arg3 = 0 ;
int argvi = 0;
dXSARGS;
if ((items < 3) || (items > 3)) {
SWIG_croak("Usage: EST_Track_copy_channel_out(self,n,f);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_copy_channel_out. Expected _p_EST_Track");
}
}
arg2 = (int) SvIV(ST(1));
{
if (SWIG_ConvertPtr(ST(2), (void **) &arg3, SWIGTYPE_p_EST_FVector,0) < 0) {
SWIG_croak("Type error in argument 3 of EST_Track_copy_channel_out. Expected _p_EST_FVector");
}
}
((EST_Track const *)arg1)->copy_channel_out(arg2,*arg3);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_copy_channel_out) {
dXSARGS;
if (items == 3) {
int _v;
{
void *tmp;
if (SWIG_ConvertPtr(ST(0), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
_v = SvIOK(ST(1)) ? 1 : 0;
}
if (_v) {
{
void *tmp;
if (SWIG_ConvertPtr(ST(2), (void **) &tmp, SWIGTYPE_p_EST_FVector, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
(*PL_markstack_ptr++);SWIG_CALLXS(_wrap_EST_Track_copy_channel_out__SWIG_2); return;
}
}
}
}
if (items == 4) {
int _v;
{
void *tmp;
if (SWIG_ConvertPtr(ST(0), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
_v = SvIOK(ST(1)) ? 1 : 0;
}
if (_v) {
{
void *tmp;
if (SWIG_ConvertPtr(ST(2), (void **) &tmp, SWIGTYPE_p_EST_FVector, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
_v = SvIOK(ST(3)) ? 1 : 0;
}
if (_v) {
(*PL_markstack_ptr++);SWIG_CALLXS(_wrap_EST_Track_copy_channel_out__SWIG_1); return;
}
}
}
}
}
if (items == 5) {
int _v;
{
void *tmp;
if (SWIG_ConvertPtr(ST(0), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
_v = SvIOK(ST(1)) ? 1 : 0;
}
if (_v) {
{
void *tmp;
if (SWIG_ConvertPtr(ST(2), (void **) &tmp, SWIGTYPE_p_EST_FVector, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
_v = SvIOK(ST(3)) ? 1 : 0;
}
if (_v) {
{
_v = SvIOK(ST(4)) ? 1 : 0;
}
if (_v) {
(*PL_markstack_ptr++);SWIG_CALLXS(_wrap_EST_Track_copy_channel_out__SWIG_0); return;
}
}
}
}
}
}
croak("No matching function for overloaded 'EST_Track_copy_channel_out'");
XSRETURN(0);
}
XS(_wrap_EST_Track_copy_frame_out__SWIG_0) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
int arg2 ;
EST_FVector *arg3 = 0 ;
int arg4 ;
int arg5 ;
int argvi = 0;
dXSARGS;
if ((items < 5) || (items > 5)) {
SWIG_croak("Usage: EST_Track_copy_frame_out(self,n,f,offset,nc);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_copy_frame_out. Expected _p_EST_Track");
}
}
arg2 = (int) SvIV(ST(1));
{
if (SWIG_ConvertPtr(ST(2), (void **) &arg3, SWIGTYPE_p_EST_FVector,0) < 0) {
SWIG_croak("Type error in argument 3 of EST_Track_copy_frame_out. Expected _p_EST_FVector");
}
}
arg4 = (int) SvIV(ST(3));
arg5 = (int) SvIV(ST(4));
((EST_Track const *)arg1)->copy_frame_out(arg2,*arg3,arg4,arg5);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_copy_frame_out__SWIG_1) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
int arg2 ;
EST_FVector *arg3 = 0 ;
int arg4 ;
int argvi = 0;
dXSARGS;
if ((items < 4) || (items > 4)) {
SWIG_croak("Usage: EST_Track_copy_frame_out(self,n,f,offset);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_copy_frame_out. Expected _p_EST_Track");
}
}
arg2 = (int) SvIV(ST(1));
{
if (SWIG_ConvertPtr(ST(2), (void **) &arg3, SWIGTYPE_p_EST_FVector,0) < 0) {
SWIG_croak("Type error in argument 3 of EST_Track_copy_frame_out. Expected _p_EST_FVector");
}
}
arg4 = (int) SvIV(ST(3));
((EST_Track const *)arg1)->copy_frame_out(arg2,*arg3,arg4);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_copy_frame_out__SWIG_2) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
int arg2 ;
EST_FVector *arg3 = 0 ;
int argvi = 0;
dXSARGS;
if ((items < 3) || (items > 3)) {
SWIG_croak("Usage: EST_Track_copy_frame_out(self,n,f);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_copy_frame_out. Expected _p_EST_Track");
}
}
arg2 = (int) SvIV(ST(1));
{
if (SWIG_ConvertPtr(ST(2), (void **) &arg3, SWIGTYPE_p_EST_FVector,0) < 0) {
SWIG_croak("Type error in argument 3 of EST_Track_copy_frame_out. Expected _p_EST_FVector");
}
}
((EST_Track const *)arg1)->copy_frame_out(arg2,*arg3);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_copy_frame_out) {
dXSARGS;
if (items == 3) {
int _v;
{
void *tmp;
if (SWIG_ConvertPtr(ST(0), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
_v = SvIOK(ST(1)) ? 1 : 0;
}
if (_v) {
{
void *tmp;
if (SWIG_ConvertPtr(ST(2), (void **) &tmp, SWIGTYPE_p_EST_FVector, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
(*PL_markstack_ptr++);SWIG_CALLXS(_wrap_EST_Track_copy_frame_out__SWIG_2); return;
}
}
}
}
if (items == 4) {
int _v;
{
void *tmp;
if (SWIG_ConvertPtr(ST(0), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
_v = SvIOK(ST(1)) ? 1 : 0;
}
if (_v) {
{
void *tmp;
if (SWIG_ConvertPtr(ST(2), (void **) &tmp, SWIGTYPE_p_EST_FVector, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
_v = SvIOK(ST(3)) ? 1 : 0;
}
if (_v) {
(*PL_markstack_ptr++);SWIG_CALLXS(_wrap_EST_Track_copy_frame_out__SWIG_1); return;
}
}
}
}
}
if (items == 5) {
int _v;
{
void *tmp;
if (SWIG_ConvertPtr(ST(0), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
_v = SvIOK(ST(1)) ? 1 : 0;
}
if (_v) {
{
void *tmp;
if (SWIG_ConvertPtr(ST(2), (void **) &tmp, SWIGTYPE_p_EST_FVector, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
_v = SvIOK(ST(3)) ? 1 : 0;
}
if (_v) {
{
_v = SvIOK(ST(4)) ? 1 : 0;
}
if (_v) {
(*PL_markstack_ptr++);SWIG_CALLXS(_wrap_EST_Track_copy_frame_out__SWIG_0); return;
}
}
}
}
}
}
croak("No matching function for overloaded 'EST_Track_copy_frame_out'");
XSRETURN(0);
}
XS(_wrap_EST_Track_copy_channel_in__SWIG_0) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
int arg2 ;
EST_FVector *arg3 = 0 ;
int arg4 ;
int arg5 ;
int argvi = 0;
dXSARGS;
if ((items < 5) || (items > 5)) {
SWIG_croak("Usage: EST_Track_copy_channel_in(self,n,f,offset,num);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_copy_channel_in. Expected _p_EST_Track");
}
}
arg2 = (int) SvIV(ST(1));
{
if (SWIG_ConvertPtr(ST(2), (void **) &arg3, SWIGTYPE_p_EST_FVector,0) < 0) {
SWIG_croak("Type error in argument 3 of EST_Track_copy_channel_in. Expected _p_EST_FVector");
}
}
arg4 = (int) SvIV(ST(3));
arg5 = (int) SvIV(ST(4));
(arg1)->copy_channel_in(arg2,(EST_FVector const &)*arg3,arg4,arg5);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_copy_channel_in__SWIG_1) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
int arg2 ;
EST_FVector *arg3 = 0 ;
int arg4 ;
int argvi = 0;
dXSARGS;
if ((items < 4) || (items > 4)) {
SWIG_croak("Usage: EST_Track_copy_channel_in(self,n,f,offset);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_copy_channel_in. Expected _p_EST_Track");
}
}
arg2 = (int) SvIV(ST(1));
{
if (SWIG_ConvertPtr(ST(2), (void **) &arg3, SWIGTYPE_p_EST_FVector,0) < 0) {
SWIG_croak("Type error in argument 3 of EST_Track_copy_channel_in. Expected _p_EST_FVector");
}
}
arg4 = (int) SvIV(ST(3));
(arg1)->copy_channel_in(arg2,(EST_FVector const &)*arg3,arg4);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_copy_channel_in__SWIG_2) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
int arg2 ;
EST_FVector *arg3 = 0 ;
int argvi = 0;
dXSARGS;
if ((items < 3) || (items > 3)) {
SWIG_croak("Usage: EST_Track_copy_channel_in(self,n,f);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_copy_channel_in. Expected _p_EST_Track");
}
}
arg2 = (int) SvIV(ST(1));
{
if (SWIG_ConvertPtr(ST(2), (void **) &arg3, SWIGTYPE_p_EST_FVector,0) < 0) {
SWIG_croak("Type error in argument 3 of EST_Track_copy_channel_in. Expected _p_EST_FVector");
}
}
(arg1)->copy_channel_in(arg2,(EST_FVector const &)*arg3);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_copy_channel_in__SWIG_3) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
int arg2 ;
EST_Track *arg3 = 0 ;
int arg4 ;
int arg5 ;
int arg6 ;
int arg7 ;
int argvi = 0;
dXSARGS;
if ((items < 7) || (items > 7)) {
SWIG_croak("Usage: EST_Track_copy_channel_in(self,c,from,from_c,from_offset,offset,num);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_copy_channel_in. Expected _p_EST_Track");
}
}
arg2 = (int) SvIV(ST(1));
{
if (SWIG_ConvertPtr(ST(2), (void **) &arg3, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 3 of EST_Track_copy_channel_in. Expected _p_EST_Track");
}
}
arg4 = (int) SvIV(ST(3));
arg5 = (int) SvIV(ST(4));
arg6 = (int) SvIV(ST(5));
arg7 = (int) SvIV(ST(6));
(arg1)->copy_channel_in(arg2,(EST_Track const &)*arg3,arg4,arg5,arg6,arg7);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_copy_channel_in__SWIG_4) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
int arg2 ;
EST_Track *arg3 = 0 ;
int arg4 ;
int arg5 ;
int arg6 ;
int argvi = 0;
dXSARGS;
if ((items < 6) || (items > 6)) {
SWIG_croak("Usage: EST_Track_copy_channel_in(self,c,from,from_c,from_offset,offset);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_copy_channel_in. Expected _p_EST_Track");
}
}
arg2 = (int) SvIV(ST(1));
{
if (SWIG_ConvertPtr(ST(2), (void **) &arg3, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 3 of EST_Track_copy_channel_in. Expected _p_EST_Track");
}
}
arg4 = (int) SvIV(ST(3));
arg5 = (int) SvIV(ST(4));
arg6 = (int) SvIV(ST(5));
(arg1)->copy_channel_in(arg2,(EST_Track const &)*arg3,arg4,arg5,arg6);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_copy_channel_in__SWIG_5) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
int arg2 ;
EST_Track *arg3 = 0 ;
int arg4 ;
int arg5 ;
int argvi = 0;
dXSARGS;
if ((items < 5) || (items > 5)) {
SWIG_croak("Usage: EST_Track_copy_channel_in(self,c,from,from_c,from_offset);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_copy_channel_in. Expected _p_EST_Track");
}
}
arg2 = (int) SvIV(ST(1));
{
if (SWIG_ConvertPtr(ST(2), (void **) &arg3, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 3 of EST_Track_copy_channel_in. Expected _p_EST_Track");
}
}
arg4 = (int) SvIV(ST(3));
arg5 = (int) SvIV(ST(4));
(arg1)->copy_channel_in(arg2,(EST_Track const &)*arg3,arg4,arg5);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_copy_channel_in__SWIG_6) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
int arg2 ;
EST_Track *arg3 = 0 ;
int arg4 ;
int argvi = 0;
dXSARGS;
if ((items < 4) || (items > 4)) {
SWIG_croak("Usage: EST_Track_copy_channel_in(self,c,from,from_c);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_copy_channel_in. Expected _p_EST_Track");
}
}
arg2 = (int) SvIV(ST(1));
{
if (SWIG_ConvertPtr(ST(2), (void **) &arg3, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 3 of EST_Track_copy_channel_in. Expected _p_EST_Track");
}
}
arg4 = (int) SvIV(ST(3));
(arg1)->copy_channel_in(arg2,(EST_Track const &)*arg3,arg4);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_copy_channel_in) {
dXSARGS;
if (items == 3) {
int _v;
{
void *tmp;
if (SWIG_ConvertPtr(ST(0), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
_v = SvIOK(ST(1)) ? 1 : 0;
}
if (_v) {
{
void *tmp;
if (SWIG_ConvertPtr(ST(2), (void **) &tmp, SWIGTYPE_p_EST_FVector, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
(*PL_markstack_ptr++);SWIG_CALLXS(_wrap_EST_Track_copy_channel_in__SWIG_2); return;
}
}
}
}
if (items == 4) {
int _v;
{
void *tmp;
if (SWIG_ConvertPtr(ST(0), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
_v = SvIOK(ST(1)) ? 1 : 0;
}
if (_v) {
{
void *tmp;
if (SWIG_ConvertPtr(ST(2), (void **) &tmp, SWIGTYPE_p_EST_FVector, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
_v = SvIOK(ST(3)) ? 1 : 0;
}
if (_v) {
(*PL_markstack_ptr++);SWIG_CALLXS(_wrap_EST_Track_copy_channel_in__SWIG_1); return;
}
}
}
}
}
if (items == 4) {
int _v;
{
void *tmp;
if (SWIG_ConvertPtr(ST(0), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
_v = SvIOK(ST(1)) ? 1 : 0;
}
if (_v) {
{
void *tmp;
if (SWIG_ConvertPtr(ST(2), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
_v = SvIOK(ST(3)) ? 1 : 0;
}
if (_v) {
(*PL_markstack_ptr++);SWIG_CALLXS(_wrap_EST_Track_copy_channel_in__SWIG_6); return;
}
}
}
}
}
if (items == 5) {
int _v;
{
void *tmp;
if (SWIG_ConvertPtr(ST(0), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
_v = SvIOK(ST(1)) ? 1 : 0;
}
if (_v) {
{
void *tmp;
if (SWIG_ConvertPtr(ST(2), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
_v = SvIOK(ST(3)) ? 1 : 0;
}
if (_v) {
{
_v = SvIOK(ST(4)) ? 1 : 0;
}
if (_v) {
(*PL_markstack_ptr++);SWIG_CALLXS(_wrap_EST_Track_copy_channel_in__SWIG_5); return;
}
}
}
}
}
}
if (items == 5) {
int _v;
{
void *tmp;
if (SWIG_ConvertPtr(ST(0), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
_v = SvIOK(ST(1)) ? 1 : 0;
}
if (_v) {
{
void *tmp;
if (SWIG_ConvertPtr(ST(2), (void **) &tmp, SWIGTYPE_p_EST_FVector, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
_v = SvIOK(ST(3)) ? 1 : 0;
}
if (_v) {
{
_v = SvIOK(ST(4)) ? 1 : 0;
}
if (_v) {
(*PL_markstack_ptr++);SWIG_CALLXS(_wrap_EST_Track_copy_channel_in__SWIG_0); return;
}
}
}
}
}
}
if (items == 6) {
int _v;
{
void *tmp;
if (SWIG_ConvertPtr(ST(0), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
_v = SvIOK(ST(1)) ? 1 : 0;
}
if (_v) {
{
void *tmp;
if (SWIG_ConvertPtr(ST(2), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
_v = SvIOK(ST(3)) ? 1 : 0;
}
if (_v) {
{
_v = SvIOK(ST(4)) ? 1 : 0;
}
if (_v) {
{
_v = SvIOK(ST(5)) ? 1 : 0;
}
if (_v) {
(*PL_markstack_ptr++);SWIG_CALLXS(_wrap_EST_Track_copy_channel_in__SWIG_4); return;
}
}
}
}
}
}
}
if (items == 7) {
int _v;
{
void *tmp;
if (SWIG_ConvertPtr(ST(0), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
_v = SvIOK(ST(1)) ? 1 : 0;
}
if (_v) {
{
void *tmp;
if (SWIG_ConvertPtr(ST(2), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
_v = SvIOK(ST(3)) ? 1 : 0;
}
if (_v) {
{
_v = SvIOK(ST(4)) ? 1 : 0;
}
if (_v) {
{
_v = SvIOK(ST(5)) ? 1 : 0;
}
if (_v) {
{
_v = SvIOK(ST(6)) ? 1 : 0;
}
if (_v) {
(*PL_markstack_ptr++);SWIG_CALLXS(_wrap_EST_Track_copy_channel_in__SWIG_3); return;
}
}
}
}
}
}
}
}
croak("No matching function for overloaded 'EST_Track_copy_channel_in'");
XSRETURN(0);
}
XS(_wrap_EST_Track_copy_frame_in__SWIG_0) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
int arg2 ;
EST_FVector *arg3 = 0 ;
int arg4 ;
int arg5 ;
int argvi = 0;
dXSARGS;
if ((items < 5) || (items > 5)) {
SWIG_croak("Usage: EST_Track_copy_frame_in(self,n,f,offset,nf);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_copy_frame_in. Expected _p_EST_Track");
}
}
arg2 = (int) SvIV(ST(1));
{
if (SWIG_ConvertPtr(ST(2), (void **) &arg3, SWIGTYPE_p_EST_FVector,0) < 0) {
SWIG_croak("Type error in argument 3 of EST_Track_copy_frame_in. Expected _p_EST_FVector");
}
}
arg4 = (int) SvIV(ST(3));
arg5 = (int) SvIV(ST(4));
(arg1)->copy_frame_in(arg2,(EST_FVector const &)*arg3,arg4,arg5);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_copy_frame_in__SWIG_1) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
int arg2 ;
EST_FVector *arg3 = 0 ;
int arg4 ;
int argvi = 0;
dXSARGS;
if ((items < 4) || (items > 4)) {
SWIG_croak("Usage: EST_Track_copy_frame_in(self,n,f,offset);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_copy_frame_in. Expected _p_EST_Track");
}
}
arg2 = (int) SvIV(ST(1));
{
if (SWIG_ConvertPtr(ST(2), (void **) &arg3, SWIGTYPE_p_EST_FVector,0) < 0) {
SWIG_croak("Type error in argument 3 of EST_Track_copy_frame_in. Expected _p_EST_FVector");
}
}
arg4 = (int) SvIV(ST(3));
(arg1)->copy_frame_in(arg2,(EST_FVector const &)*arg3,arg4);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_copy_frame_in__SWIG_2) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
int arg2 ;
EST_FVector *arg3 = 0 ;
int argvi = 0;
dXSARGS;
if ((items < 3) || (items > 3)) {
SWIG_croak("Usage: EST_Track_copy_frame_in(self,n,f);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_copy_frame_in. Expected _p_EST_Track");
}
}
arg2 = (int) SvIV(ST(1));
{
if (SWIG_ConvertPtr(ST(2), (void **) &arg3, SWIGTYPE_p_EST_FVector,0) < 0) {
SWIG_croak("Type error in argument 3 of EST_Track_copy_frame_in. Expected _p_EST_FVector");
}
}
(arg1)->copy_frame_in(arg2,(EST_FVector const &)*arg3);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_copy_frame_in__SWIG_3) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
int arg2 ;
EST_Track *arg3 = 0 ;
int arg4 ;
int arg5 ;
int arg6 ;
int arg7 ;
int argvi = 0;
dXSARGS;
if ((items < 7) || (items > 7)) {
SWIG_croak("Usage: EST_Track_copy_frame_in(self,i,from,from_f,from_offset,offset,num);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_copy_frame_in. Expected _p_EST_Track");
}
}
arg2 = (int) SvIV(ST(1));
{
if (SWIG_ConvertPtr(ST(2), (void **) &arg3, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 3 of EST_Track_copy_frame_in. Expected _p_EST_Track");
}
}
arg4 = (int) SvIV(ST(3));
arg5 = (int) SvIV(ST(4));
arg6 = (int) SvIV(ST(5));
arg7 = (int) SvIV(ST(6));
(arg1)->copy_frame_in(arg2,(EST_Track const &)*arg3,arg4,arg5,arg6,arg7);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_copy_frame_in__SWIG_4) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
int arg2 ;
EST_Track *arg3 = 0 ;
int arg4 ;
int arg5 ;
int arg6 ;
int argvi = 0;
dXSARGS;
if ((items < 6) || (items > 6)) {
SWIG_croak("Usage: EST_Track_copy_frame_in(self,i,from,from_f,from_offset,offset);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_copy_frame_in. Expected _p_EST_Track");
}
}
arg2 = (int) SvIV(ST(1));
{
if (SWIG_ConvertPtr(ST(2), (void **) &arg3, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 3 of EST_Track_copy_frame_in. Expected _p_EST_Track");
}
}
arg4 = (int) SvIV(ST(3));
arg5 = (int) SvIV(ST(4));
arg6 = (int) SvIV(ST(5));
(arg1)->copy_frame_in(arg2,(EST_Track const &)*arg3,arg4,arg5,arg6);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_copy_frame_in__SWIG_5) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
int arg2 ;
EST_Track *arg3 = 0 ;
int arg4 ;
int arg5 ;
int argvi = 0;
dXSARGS;
if ((items < 5) || (items > 5)) {
SWIG_croak("Usage: EST_Track_copy_frame_in(self,i,from,from_f,from_offset);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_copy_frame_in. Expected _p_EST_Track");
}
}
arg2 = (int) SvIV(ST(1));
{
if (SWIG_ConvertPtr(ST(2), (void **) &arg3, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 3 of EST_Track_copy_frame_in. Expected _p_EST_Track");
}
}
arg4 = (int) SvIV(ST(3));
arg5 = (int) SvIV(ST(4));
(arg1)->copy_frame_in(arg2,(EST_Track const &)*arg3,arg4,arg5);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_copy_frame_in__SWIG_6) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
int arg2 ;
EST_Track *arg3 = 0 ;
int arg4 ;
int argvi = 0;
dXSARGS;
if ((items < 4) || (items > 4)) {
SWIG_croak("Usage: EST_Track_copy_frame_in(self,i,from,from_f);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_copy_frame_in. Expected _p_EST_Track");
}
}
arg2 = (int) SvIV(ST(1));
{
if (SWIG_ConvertPtr(ST(2), (void **) &arg3, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 3 of EST_Track_copy_frame_in. Expected _p_EST_Track");
}
}
arg4 = (int) SvIV(ST(3));
(arg1)->copy_frame_in(arg2,(EST_Track const &)*arg3,arg4);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_copy_frame_in) {
dXSARGS;
if (items == 3) {
int _v;
{
void *tmp;
if (SWIG_ConvertPtr(ST(0), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
_v = SvIOK(ST(1)) ? 1 : 0;
}
if (_v) {
{
void *tmp;
if (SWIG_ConvertPtr(ST(2), (void **) &tmp, SWIGTYPE_p_EST_FVector, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
(*PL_markstack_ptr++);SWIG_CALLXS(_wrap_EST_Track_copy_frame_in__SWIG_2); return;
}
}
}
}
if (items == 4) {
int _v;
{
void *tmp;
if (SWIG_ConvertPtr(ST(0), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
_v = SvIOK(ST(1)) ? 1 : 0;
}
if (_v) {
{
void *tmp;
if (SWIG_ConvertPtr(ST(2), (void **) &tmp, SWIGTYPE_p_EST_FVector, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
_v = SvIOK(ST(3)) ? 1 : 0;
}
if (_v) {
(*PL_markstack_ptr++);SWIG_CALLXS(_wrap_EST_Track_copy_frame_in__SWIG_1); return;
}
}
}
}
}
if (items == 4) {
int _v;
{
void *tmp;
if (SWIG_ConvertPtr(ST(0), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
_v = SvIOK(ST(1)) ? 1 : 0;
}
if (_v) {
{
void *tmp;
if (SWIG_ConvertPtr(ST(2), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
_v = SvIOK(ST(3)) ? 1 : 0;
}
if (_v) {
(*PL_markstack_ptr++);SWIG_CALLXS(_wrap_EST_Track_copy_frame_in__SWIG_6); return;
}
}
}
}
}
if (items == 5) {
int _v;
{
void *tmp;
if (SWIG_ConvertPtr(ST(0), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
_v = SvIOK(ST(1)) ? 1 : 0;
}
if (_v) {
{
void *tmp;
if (SWIG_ConvertPtr(ST(2), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
_v = SvIOK(ST(3)) ? 1 : 0;
}
if (_v) {
{
_v = SvIOK(ST(4)) ? 1 : 0;
}
if (_v) {
(*PL_markstack_ptr++);SWIG_CALLXS(_wrap_EST_Track_copy_frame_in__SWIG_5); return;
}
}
}
}
}
}
if (items == 5) {
int _v;
{
void *tmp;
if (SWIG_ConvertPtr(ST(0), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
_v = SvIOK(ST(1)) ? 1 : 0;
}
if (_v) {
{
void *tmp;
if (SWIG_ConvertPtr(ST(2), (void **) &tmp, SWIGTYPE_p_EST_FVector, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
_v = SvIOK(ST(3)) ? 1 : 0;
}
if (_v) {
{
_v = SvIOK(ST(4)) ? 1 : 0;
}
if (_v) {
(*PL_markstack_ptr++);SWIG_CALLXS(_wrap_EST_Track_copy_frame_in__SWIG_0); return;
}
}
}
}
}
}
if (items == 6) {
int _v;
{
void *tmp;
if (SWIG_ConvertPtr(ST(0), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
_v = SvIOK(ST(1)) ? 1 : 0;
}
if (_v) {
{
void *tmp;
if (SWIG_ConvertPtr(ST(2), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
_v = SvIOK(ST(3)) ? 1 : 0;
}
if (_v) {
{
_v = SvIOK(ST(4)) ? 1 : 0;
}
if (_v) {
{
_v = SvIOK(ST(5)) ? 1 : 0;
}
if (_v) {
(*PL_markstack_ptr++);SWIG_CALLXS(_wrap_EST_Track_copy_frame_in__SWIG_4); return;
}
}
}
}
}
}
}
if (items == 7) {
int _v;
{
void *tmp;
if (SWIG_ConvertPtr(ST(0), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
_v = SvIOK(ST(1)) ? 1 : 0;
}
if (_v) {
{
void *tmp;
if (SWIG_ConvertPtr(ST(2), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
_v = SvIOK(ST(3)) ? 1 : 0;
}
if (_v) {
{
_v = SvIOK(ST(4)) ? 1 : 0;
}
if (_v) {
{
_v = SvIOK(ST(5)) ? 1 : 0;
}
if (_v) {
{
_v = SvIOK(ST(6)) ? 1 : 0;
}
if (_v) {
(*PL_markstack_ptr++);SWIG_CALLXS(_wrap_EST_Track_copy_frame_in__SWIG_3); return;
}
}
}
}
}
}
}
}
croak("No matching function for overloaded 'EST_Track_copy_frame_in'");
XSRETURN(0);
}
XS(_wrap_EST_Track_channel_position__SWIG_0) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
char *arg2 = (char *) 0 ;
int arg3 ;
int result;
int argvi = 0;
dXSARGS;
if ((items < 3) || (items > 3)) {
SWIG_croak("Usage: EST_Track_channel_position(self,name,offset);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_channel_position. Expected _p_EST_Track");
}
}
if (!SvOK((SV*) ST(1))) arg2 = 0;
else arg2 = (char *) SvPV(ST(1), PL_na);
arg3 = (int) SvIV(ST(2));
result = (int)((EST_Track const *)arg1)->channel_position((char const *)arg2,arg3);
ST(argvi) = sv_newmortal();
sv_setiv(ST(argvi++), (IV) result);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_channel_position__SWIG_1) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
char *arg2 = (char *) 0 ;
int result;
int argvi = 0;
dXSARGS;
if ((items < 2) || (items > 2)) {
SWIG_croak("Usage: EST_Track_channel_position(self,name);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_channel_position. Expected _p_EST_Track");
}
}
if (!SvOK((SV*) ST(1))) arg2 = 0;
else arg2 = (char *) SvPV(ST(1), PL_na);
result = (int)((EST_Track const *)arg1)->channel_position((char const *)arg2);
ST(argvi) = sv_newmortal();
sv_setiv(ST(argvi++), (IV) result);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_channel_position) {
dXSARGS;
if (items == 2) {
int _v;
{
void *tmp;
if (SWIG_ConvertPtr(ST(0), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
_v = SvPOK(ST(1)) ? 1 : 0;
}
if (_v) {
(*PL_markstack_ptr++);SWIG_CALLXS(_wrap_EST_Track_channel_position__SWIG_1); return;
}
}
}
if (items == 3) {
int _v;
{
void *tmp;
if (SWIG_ConvertPtr(ST(0), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
_v = SvPOK(ST(1)) ? 1 : 0;
}
if (_v) {
{
_v = SvIOK(ST(2)) ? 1 : 0;
}
if (_v) {
(*PL_markstack_ptr++);SWIG_CALLXS(_wrap_EST_Track_channel_position__SWIG_0); return;
}
}
}
}
croak("No matching function for overloaded 'EST_Track_channel_position'");
XSRETURN(0);
}
XS(_wrap_EST_Track_has_channel) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
char *arg2 = (char *) 0 ;
bool result;
int argvi = 0;
dXSARGS;
if ((items < 2) || (items > 2)) {
SWIG_croak("Usage: EST_Track_has_channel(self,name);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_has_channel. Expected _p_EST_Track");
}
}
if (!SvOK((SV*) ST(1))) arg2 = 0;
else arg2 = (char *) SvPV(ST(1), PL_na);
result = (bool)((EST_Track const *)arg1)->has_channel((char const *)arg2);
ST(argvi) = sv_newmortal();
sv_setiv(ST(argvi++), (IV) result);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_a__SWIG_0) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
int arg2 ;
int arg3 ;
float result;
int argvi = 0;
dXSARGS;
if ((items < 3) || (items > 3)) {
SWIG_croak("Usage: EST_Track_a(self,i,c);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_a. Expected _p_EST_Track");
}
}
arg2 = (int) SvIV(ST(1));
arg3 = (int) SvIV(ST(2));
result = (float)((EST_Track const *)arg1)->a(arg2,arg3);
ST(argvi) = sv_newmortal();
sv_setnv(ST(argvi++), (double) result);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_a__SWIG_1) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
int arg2 ;
float result;
int argvi = 0;
dXSARGS;
if ((items < 2) || (items > 2)) {
SWIG_croak("Usage: EST_Track_a(self,i);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_a. Expected _p_EST_Track");
}
}
arg2 = (int) SvIV(ST(1));
result = (float)((EST_Track const *)arg1)->a(arg2);
ST(argvi) = sv_newmortal();
sv_setnv(ST(argvi++), (double) result);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_a__SWIG_2) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
float arg2 ;
int arg3 ;
float result;
int argvi = 0;
dXSARGS;
if ((items < 3) || (items > 3)) {
SWIG_croak("Usage: EST_Track_a(self,t,c);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_a. Expected _p_EST_Track");
}
}
arg2 = (float) SvNV(ST(1));
arg3 = (int) SvIV(ST(2));
result = (float)((EST_Track const *)arg1)->a(arg2,arg3);
ST(argvi) = sv_newmortal();
sv_setnv(ST(argvi++), (double) result);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_a__SWIG_3) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
float arg2 ;
float result;
int argvi = 0;
dXSARGS;
if ((items < 2) || (items > 2)) {
SWIG_croak("Usage: EST_Track_a(self,t);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_a. Expected _p_EST_Track");
}
}
arg2 = (float) SvNV(ST(1));
result = (float)((EST_Track const *)arg1)->a(arg2);
ST(argvi) = sv_newmortal();
sv_setnv(ST(argvi++), (double) result);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_a) {
dXSARGS;
if (items == 2) {
int _v;
{
void *tmp;
if (SWIG_ConvertPtr(ST(0), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
_v = SvIOK(ST(1)) ? 1 : 0;
}
if (_v) {
(*PL_markstack_ptr++);SWIG_CALLXS(_wrap_EST_Track_a__SWIG_1); return;
}
}
}
if (items == 2) {
int _v;
{
void *tmp;
if (SWIG_ConvertPtr(ST(0), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
_v = SvNIOK(ST(1)) ? 1 : 0;
}
if (_v) {
(*PL_markstack_ptr++);SWIG_CALLXS(_wrap_EST_Track_a__SWIG_3); return;
}
}
}
if (items == 3) {
int _v;
{
void *tmp;
if (SWIG_ConvertPtr(ST(0), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
_v = SvIOK(ST(1)) ? 1 : 0;
}
if (_v) {
{
_v = SvIOK(ST(2)) ? 1 : 0;
}
if (_v) {
(*PL_markstack_ptr++);SWIG_CALLXS(_wrap_EST_Track_a__SWIG_0); return;
}
}
}
}
if (items == 3) {
int _v;
{
void *tmp;
if (SWIG_ConvertPtr(ST(0), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
_v = SvNIOK(ST(1)) ? 1 : 0;
}
if (_v) {
{
_v = SvIOK(ST(2)) ? 1 : 0;
}
if (_v) {
(*PL_markstack_ptr++);SWIG_CALLXS(_wrap_EST_Track_a__SWIG_2); return;
}
}
}
}
croak("No matching function for overloaded 'EST_Track_a'");
XSRETURN(0);
}
XS(_wrap_EST_Track_t__SWIG_0) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
int arg2 ;
float result;
int argvi = 0;
dXSARGS;
if ((items < 2) || (items > 2)) {
SWIG_croak("Usage: EST_Track_t(self,i);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_t. Expected _p_EST_Track");
}
}
arg2 = (int) SvIV(ST(1));
result = (float)((EST_Track const *)arg1)->t(arg2);
ST(argvi) = sv_newmortal();
sv_setnv(ST(argvi++), (double) result);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_t__SWIG_1) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
float result;
int argvi = 0;
dXSARGS;
if ((items < 1) || (items > 1)) {
SWIG_croak("Usage: EST_Track_t(self);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_t. Expected _p_EST_Track");
}
}
result = (float)((EST_Track const *)arg1)->t();
ST(argvi) = sv_newmortal();
sv_setnv(ST(argvi++), (double) result);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_t) {
dXSARGS;
if (items == 1) {
int _v;
{
void *tmp;
if (SWIG_ConvertPtr(ST(0), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
(*PL_markstack_ptr++);SWIG_CALLXS(_wrap_EST_Track_t__SWIG_1); return;
}
}
if (items == 2) {
int _v;
{
void *tmp;
if (SWIG_ConvertPtr(ST(0), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
_v = SvIOK(ST(1)) ? 1 : 0;
}
if (_v) {
(*PL_markstack_ptr++);SWIG_CALLXS(_wrap_EST_Track_t__SWIG_0); return;
}
}
}
croak("No matching function for overloaded 'EST_Track_t'");
XSRETURN(0);
}
XS(_wrap_EST_Track_ms_t) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
int arg2 ;
float result;
int argvi = 0;
dXSARGS;
if ((items < 2) || (items > 2)) {
SWIG_croak("Usage: EST_Track_ms_t(self,i);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_ms_t. Expected _p_EST_Track");
}
}
arg2 = (int) SvIV(ST(1));
result = (float)((EST_Track const *)arg1)->ms_t(arg2);
ST(argvi) = sv_newmortal();
sv_setnv(ST(argvi++), (double) result);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_fill_time__SWIG_0) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
float arg2 ;
float arg3 ;
int argvi = 0;
dXSARGS;
if ((items < 3) || (items > 3)) {
SWIG_croak("Usage: EST_Track_fill_time(self,t,startt);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_fill_time. Expected _p_EST_Track");
}
}
arg2 = (float) SvNV(ST(1));
arg3 = (float) SvNV(ST(2));
(arg1)->fill_time(arg2,arg3);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_fill_time__SWIG_1) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
float arg2 ;
int argvi = 0;
dXSARGS;
if ((items < 2) || (items > 2)) {
SWIG_croak("Usage: EST_Track_fill_time(self,t);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_fill_time. Expected _p_EST_Track");
}
}
arg2 = (float) SvNV(ST(1));
(arg1)->fill_time(arg2);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_fill_time__SWIG_2) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
EST_Track *arg2 = 0 ;
int argvi = 0;
dXSARGS;
if ((items < 2) || (items > 2)) {
SWIG_croak("Usage: EST_Track_fill_time(self,t);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_fill_time. Expected _p_EST_Track");
}
}
{
if (SWIG_ConvertPtr(ST(1), (void **) &arg2, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 2 of EST_Track_fill_time. Expected _p_EST_Track");
}
}
(arg1)->fill_time(*arg2);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_fill_time) {
dXSARGS;
if (items == 2) {
int _v;
{
void *tmp;
if (SWIG_ConvertPtr(ST(0), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
void *tmp;
if (SWIG_ConvertPtr(ST(1), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
(*PL_markstack_ptr++);SWIG_CALLXS(_wrap_EST_Track_fill_time__SWIG_2); return;
}
}
}
if (items == 2) {
int _v;
{
void *tmp;
if (SWIG_ConvertPtr(ST(0), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
_v = SvNIOK(ST(1)) ? 1 : 0;
}
if (_v) {
(*PL_markstack_ptr++);SWIG_CALLXS(_wrap_EST_Track_fill_time__SWIG_1); return;
}
}
}
if (items == 3) {
int _v;
{
void *tmp;
if (SWIG_ConvertPtr(ST(0), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
_v = SvNIOK(ST(1)) ? 1 : 0;
}
if (_v) {
{
_v = SvNIOK(ST(2)) ? 1 : 0;
}
if (_v) {
(*PL_markstack_ptr++);SWIG_CALLXS(_wrap_EST_Track_fill_time__SWIG_0); return;
}
}
}
}
croak("No matching function for overloaded 'EST_Track_fill_time'");
XSRETURN(0);
}
XS(_wrap_EST_Track_fill) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
float arg2 ;
int argvi = 0;
dXSARGS;
if ((items < 2) || (items > 2)) {
SWIG_croak("Usage: EST_Track_fill(self,v);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_fill. Expected _p_EST_Track");
}
}
arg2 = (float) SvNV(ST(1));
(arg1)->fill(arg2);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_sample) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
float arg2 ;
int argvi = 0;
dXSARGS;
if ((items < 2) || (items > 2)) {
SWIG_croak("Usage: EST_Track_sample(self,shift);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_sample. Expected _p_EST_Track");
}
}
arg2 = (float) SvNV(ST(1));
(arg1)->sample(arg2);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_shift) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
float result;
int argvi = 0;
dXSARGS;
if ((items < 1) || (items > 1)) {
SWIG_croak("Usage: EST_Track_shift(self);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_shift. Expected _p_EST_Track");
}
}
result = (float)((EST_Track const *)arg1)->shift();
ST(argvi) = sv_newmortal();
sv_setnv(ST(argvi++), (double) result);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_start) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
float result;
int argvi = 0;
dXSARGS;
if ((items < 1) || (items > 1)) {
SWIG_croak("Usage: EST_Track_start(self);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_start. Expected _p_EST_Track");
}
}
result = (float)((EST_Track const *)arg1)->start();
ST(argvi) = sv_newmortal();
sv_setnv(ST(argvi++), (double) result);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_end) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
float result;
int argvi = 0;
dXSARGS;
if ((items < 1) || (items > 1)) {
SWIG_croak("Usage: EST_Track_end(self);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_end. Expected _p_EST_Track");
}
}
result = (float)((EST_Track const *)arg1)->end();
ST(argvi) = sv_newmortal();
sv_setnv(ST(argvi++), (double) result);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_load__SWIG_0) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
char *arg2 = (char *) 0 ;
float arg3 ;
float arg4 ;
EST_read_status result;
int argvi = 0;
dXSARGS;
if ((items < 4) || (items > 4)) {
SWIG_croak("Usage: EST_Track_load(self,name,ishift,startt);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_load. Expected _p_EST_Track");
}
}
if (!SvOK((SV*) ST(1))) arg2 = 0;
else arg2 = (char *) SvPV(ST(1), PL_na);
arg3 = (float) SvNV(ST(2));
arg4 = (float) SvNV(ST(3));
result = (arg1)->load((char const *)arg2,arg3,arg4);
{
EST_read_status * resultobj = new EST_read_status((EST_read_status &)result);
ST(argvi) = sv_newmortal();
SWIG_MakePtr(ST(argvi++), (void *) resultobj, SWIGTYPE_p_EST_read_status, 0|SWIG_OWNER);
}
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_load__SWIG_1) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
char *arg2 = (char *) 0 ;
float arg3 ;
EST_read_status result;
int argvi = 0;
dXSARGS;
if ((items < 3) || (items > 3)) {
SWIG_croak("Usage: EST_Track_load(self,name,ishift);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_load. Expected _p_EST_Track");
}
}
if (!SvOK((SV*) ST(1))) arg2 = 0;
else arg2 = (char *) SvPV(ST(1), PL_na);
arg3 = (float) SvNV(ST(2));
result = (arg1)->load((char const *)arg2,arg3);
{
EST_read_status * resultobj = new EST_read_status((EST_read_status &)result);
ST(argvi) = sv_newmortal();
SWIG_MakePtr(ST(argvi++), (void *) resultobj, SWIGTYPE_p_EST_read_status, 0|SWIG_OWNER);
}
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_load__SWIG_2) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
char *arg2 = (char *) 0 ;
EST_read_status result;
int argvi = 0;
dXSARGS;
if ((items < 2) || (items > 2)) {
SWIG_croak("Usage: EST_Track_load(self,name);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_load. Expected _p_EST_Track");
}
}
if (!SvOK((SV*) ST(1))) arg2 = 0;
else arg2 = (char *) SvPV(ST(1), PL_na);
result = (arg1)->load((char const *)arg2);
{
EST_read_status * resultobj = new EST_read_status((EST_read_status &)result);
ST(argvi) = sv_newmortal();
SWIG_MakePtr(ST(argvi++), (void *) resultobj, SWIGTYPE_p_EST_read_status, 0|SWIG_OWNER);
}
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_load) {
dXSARGS;
if (items == 2) {
int _v;
{
void *tmp;
if (SWIG_ConvertPtr(ST(0), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
_v = SvPOK(ST(1)) ? 1 : 0;
}
if (_v) {
(*PL_markstack_ptr++);SWIG_CALLXS(_wrap_EST_Track_load__SWIG_2); return;
}
}
}
if (items == 3) {
int _v;
{
void *tmp;
if (SWIG_ConvertPtr(ST(0), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
_v = SvPOK(ST(1)) ? 1 : 0;
}
if (_v) {
{
_v = SvNIOK(ST(2)) ? 1 : 0;
}
if (_v) {
(*PL_markstack_ptr++);SWIG_CALLXS(_wrap_EST_Track_load__SWIG_1); return;
}
}
}
}
if (items == 4) {
int _v;
{
void *tmp;
if (SWIG_ConvertPtr(ST(0), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
_v = SvPOK(ST(1)) ? 1 : 0;
}
if (_v) {
{
_v = SvNIOK(ST(2)) ? 1 : 0;
}
if (_v) {
{
_v = SvNIOK(ST(3)) ? 1 : 0;
}
if (_v) {
(*PL_markstack_ptr++);SWIG_CALLXS(_wrap_EST_Track_load__SWIG_0); return;
}
}
}
}
}
croak("No matching function for overloaded 'EST_Track_load'");
XSRETURN(0);
}
XS(_wrap_EST_Track_save__SWIG_0) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
char *arg2 = (char *) 0 ;
char *arg3 = (char *) 0 ;
EST_write_status result;
int argvi = 0;
dXSARGS;
if ((items < 3) || (items > 3)) {
SWIG_croak("Usage: EST_Track_save(self,name,EST_filetype);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_save. Expected _p_EST_Track");
}
}
if (!SvOK((SV*) ST(1))) arg2 = 0;
else arg2 = (char *) SvPV(ST(1), PL_na);
if (!SvOK((SV*) ST(2))) arg3 = 0;
else arg3 = (char *) SvPV(ST(2), PL_na);
result = (arg1)->save((char const *)arg2,(char const *)arg3);
{
EST_write_status * resultobj = new EST_write_status((EST_write_status &)result);
ST(argvi) = sv_newmortal();
SWIG_MakePtr(ST(argvi++), (void *) resultobj, SWIGTYPE_p_EST_write_status, 0|SWIG_OWNER);
}
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_save__SWIG_1) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
char *arg2 = (char *) 0 ;
EST_write_status result;
int argvi = 0;
dXSARGS;
if ((items < 2) || (items > 2)) {
SWIG_croak("Usage: EST_Track_save(self,name);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_save. Expected _p_EST_Track");
}
}
if (!SvOK((SV*) ST(1))) arg2 = 0;
else arg2 = (char *) SvPV(ST(1), PL_na);
result = (arg1)->save((char const *)arg2);
{
EST_write_status * resultobj = new EST_write_status((EST_write_status &)result);
ST(argvi) = sv_newmortal();
SWIG_MakePtr(ST(argvi++), (void *) resultobj, SWIGTYPE_p_EST_write_status, 0|SWIG_OWNER);
}
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_save) {
dXSARGS;
if (items == 2) {
int _v;
{
void *tmp;
if (SWIG_ConvertPtr(ST(0), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
_v = SvPOK(ST(1)) ? 1 : 0;
}
if (_v) {
(*PL_markstack_ptr++);SWIG_CALLXS(_wrap_EST_Track_save__SWIG_1); return;
}
}
}
if (items == 3) {
int _v;
{
void *tmp;
if (SWIG_ConvertPtr(ST(0), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
_v = SvPOK(ST(1)) ? 1 : 0;
}
if (_v) {
{
_v = SvPOK(ST(2)) ? 1 : 0;
}
if (_v) {
(*PL_markstack_ptr++);SWIG_CALLXS(_wrap_EST_Track_save__SWIG_0); return;
}
}
}
}
croak("No matching function for overloaded 'EST_Track_save'");
XSRETURN(0);
}
XS(_wrap_EST_Track_empty) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
int result;
int argvi = 0;
dXSARGS;
if ((items < 1) || (items > 1)) {
SWIG_croak("Usage: EST_Track_empty(self);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_empty. Expected _p_EST_Track");
}
}
result = (int)((EST_Track const *)arg1)->empty();
ST(argvi) = sv_newmortal();
sv_setiv(ST(argvi++), (IV) result);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_index) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
float arg2 ;
int result;
int argvi = 0;
dXSARGS;
if ((items < 2) || (items > 2)) {
SWIG_croak("Usage: EST_Track_index(self,t);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_index. Expected _p_EST_Track");
}
}
arg2 = (float) SvNV(ST(1));
result = (int)((EST_Track const *)arg1)->index(arg2);
ST(argvi) = sv_newmortal();
sv_setiv(ST(argvi++), (IV) result);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_index_below) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
float arg2 ;
int result;
int argvi = 0;
dXSARGS;
if ((items < 2) || (items > 2)) {
SWIG_croak("Usage: EST_Track_index_below(self,x);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_index_below. Expected _p_EST_Track");
}
}
arg2 = (float) SvNV(ST(1));
result = (int)((EST_Track const *)arg1)->index_below(arg2);
ST(argvi) = sv_newmortal();
sv_setiv(ST(argvi++), (IV) result);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_num_frames) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
int result;
int argvi = 0;
dXSARGS;
if ((items < 1) || (items > 1)) {
SWIG_croak("Usage: EST_Track_num_frames(self);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_num_frames. Expected _p_EST_Track");
}
}
result = (int)((EST_Track const *)arg1)->num_frames();
ST(argvi) = sv_newmortal();
sv_setiv(ST(argvi++), (IV) result);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_length) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
int result;
int argvi = 0;
dXSARGS;
if ((items < 1) || (items > 1)) {
SWIG_croak("Usage: EST_Track_length(self);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_length. Expected _p_EST_Track");
}
}
result = (int)((EST_Track const *)arg1)->length();
ST(argvi) = sv_newmortal();
sv_setiv(ST(argvi++), (IV) result);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_num_channels) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
int result;
int argvi = 0;
dXSARGS;
if ((items < 1) || (items > 1)) {
SWIG_croak("Usage: EST_Track_num_channels(self);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_num_channels. Expected _p_EST_Track");
}
}
result = (int)((EST_Track const *)arg1)->num_channels();
ST(argvi) = sv_newmortal();
sv_setiv(ST(argvi++), (IV) result);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_num_aux_channels) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
int result;
int argvi = 0;
dXSARGS;
if ((items < 1) || (items > 1)) {
SWIG_croak("Usage: EST_Track_num_aux_channels(self);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_num_aux_channels. Expected _p_EST_Track");
}
}
result = (int)((EST_Track const *)arg1)->num_aux_channels();
ST(argvi) = sv_newmortal();
sv_setiv(ST(argvi++), (IV) result);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_equal_space) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
bool result;
int argvi = 0;
dXSARGS;
if ((items < 1) || (items > 1)) {
SWIG_croak("Usage: EST_Track_equal_space(self);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_equal_space. Expected _p_EST_Track");
}
}
result = (bool)((EST_Track const *)arg1)->equal_space();
ST(argvi) = sv_newmortal();
sv_setiv(ST(argvi++), (IV) result);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_single_break) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
bool result;
int argvi = 0;
dXSARGS;
if ((items < 1) || (items > 1)) {
SWIG_croak("Usage: EST_Track_single_break(self);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_single_break. Expected _p_EST_Track");
}
}
result = (bool)((EST_Track const *)arg1)->single_break();
ST(argvi) = sv_newmortal();
sv_setiv(ST(argvi++), (IV) result);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_set_equal_space) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
bool arg2 ;
int argvi = 0;
dXSARGS;
if ((items < 2) || (items > 2)) {
SWIG_croak("Usage: EST_Track_set_equal_space(self,t);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_set_equal_space. Expected _p_EST_Track");
}
}
arg2 = SvIV(ST(1)) ? true : false;
(arg1)->set_equal_space(arg2);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_set_single_break) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
bool arg2 ;
int argvi = 0;
dXSARGS;
if ((items < 2) || (items > 2)) {
SWIG_croak("Usage: EST_Track_set_single_break(self,t);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_set_single_break. Expected _p_EST_Track");
}
}
arg2 = SvIV(ST(1)) ? true : false;
(arg1)->set_single_break(arg2);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_load_channel_names) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
EST_String arg2 ;
EST_read_status result;
int argvi = 0;
dXSARGS;
if ((items < 2) || (items > 2)) {
SWIG_croak("Usage: EST_Track_load_channel_names(self,name);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_load_channel_names. Expected _p_EST_Track");
}
}
{
STRLEN len; const char* str = SvPV(ST(1), len);
arg2 = EST_String( str, len, 0, len );
}
result = (arg1)->load_channel_names(arg2);
{
EST_read_status * resultobj = new EST_read_status((EST_read_status &)result);
ST(argvi) = sv_newmortal();
SWIG_MakePtr(ST(argvi++), (void *) resultobj, SWIGTYPE_p_EST_read_status, 0|SWIG_OWNER);
}
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_save_channel_names) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
EST_String arg2 ;
EST_write_status result;
int argvi = 0;
dXSARGS;
if ((items < 2) || (items > 2)) {
SWIG_croak("Usage: EST_Track_save_channel_names(self,name);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_save_channel_names. Expected _p_EST_Track");
}
}
{
STRLEN len; const char* str = SvPV(ST(1), len);
arg2 = EST_String( str, len, 0, len );
}
result = (arg1)->save_channel_names(arg2);
{
EST_write_status * resultobj = new EST_write_status((EST_write_status &)result);
ST(argvi) = sv_newmortal();
SWIG_MakePtr(ST(argvi++), (void *) resultobj, SWIGTYPE_p_EST_write_status, 0|SWIG_OWNER);
}
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_channel_name__SWIG_0) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
int arg2 ;
int arg3 ;
EST_String result;
int argvi = 0;
dXSARGS;
if ((items < 3) || (items > 3)) {
SWIG_croak("Usage: EST_Track_channel_name(self,channel,strings_override);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_channel_name. Expected _p_EST_Track");
}
}
arg2 = (int) SvIV(ST(1));
arg3 = (int) SvIV(ST(2));
result = ((EST_Track const *)arg1)->channel_name(arg2,arg3);
ST(argvi) = sv_newmortal();
sv_setpvn((SV*)ST(argvi++),(char *)result, (&result)->length());
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_channel_name__SWIG_1) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
int arg2 ;
EST_String result;
int argvi = 0;
dXSARGS;
if ((items < 2) || (items > 2)) {
SWIG_croak("Usage: EST_Track_channel_name(self,channel);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_channel_name. Expected _p_EST_Track");
}
}
arg2 = (int) SvIV(ST(1));
result = ((EST_Track const *)arg1)->channel_name(arg2);
ST(argvi) = sv_newmortal();
sv_setpvn((SV*)ST(argvi++),(char *)result, (&result)->length());
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_EST_Track_channel_name) {
dXSARGS;
if (items == 2) {
int _v;
{
void *tmp;
if (SWIG_ConvertPtr(ST(0), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
_v = SvIOK(ST(1)) ? 1 : 0;
}
if (_v) {
(*PL_markstack_ptr++);SWIG_CALLXS(_wrap_EST_Track_channel_name__SWIG_1); return;
}
}
}
if (items == 3) {
int _v;
{
void *tmp;
if (SWIG_ConvertPtr(ST(0), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
_v = SvIOK(ST(1)) ? 1 : 0;
}
if (_v) {
{
_v = SvIOK(ST(2)) ? 1 : 0;
}
if (_v) {
(*PL_markstack_ptr++);SWIG_CALLXS(_wrap_EST_Track_channel_name__SWIG_0); return;
}
}
}
}
croak("No matching function for overloaded 'EST_Track_channel_name'");
XSRETURN(0);
}
XS(_wrap_EST_Track_aux_channel_name) {
{
EST_Track *arg1 = (EST_Track *) 0 ;
int arg2 ;
EST_String result;
int argvi = 0;
dXSARGS;
if ((items < 2) || (items > 2)) {
SWIG_croak("Usage: EST_Track_aux_channel_name(self,channel);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of EST_Track_aux_channel_name. Expected _p_EST_Track");
}
}
arg2 = (int) SvIV(ST(1));
result = ((EST_Track const *)arg1)->aux_channel_name(arg2);
ST(argvi) = sv_newmortal();
sv_setpvn((SV*)ST(argvi++),(char *)result, (&result)->length());
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_mean__SWIG_0) {
{
EST_Track *arg1 = 0 ;
int arg2 ;
float result;
int argvi = 0;
dXSARGS;
if ((items < 2) || (items > 2)) {
SWIG_croak("Usage: mean(tr,channel);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of mean. Expected _p_EST_Track");
}
}
arg2 = (int) SvIV(ST(1));
result = (float)mean((EST_Track const &)*arg1,arg2);
ST(argvi) = sv_newmortal();
sv_setnv(ST(argvi++), (double) result);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_mean__SWIG_1) {
{
EST_Track *arg1 = 0 ;
EST_FVector *arg2 = 0 ;
int argvi = 0;
dXSARGS;
if ((items < 2) || (items > 2)) {
SWIG_croak("Usage: mean(tr,means);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of mean. Expected _p_EST_Track");
}
}
{
if (SWIG_ConvertPtr(ST(1), (void **) &arg2, SWIGTYPE_p_EST_FVector,0) < 0) {
SWIG_croak("Type error in argument 2 of mean. Expected _p_EST_FVector");
}
}
mean((EST_Track const &)*arg1,*arg2);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_mean) {
dXSARGS;
if (items == 2) {
int _v;
{
void *tmp;
if (SWIG_ConvertPtr(ST(0), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
void *tmp;
if (SWIG_ConvertPtr(ST(1), (void **) &tmp, SWIGTYPE_p_EST_FVector, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
(*PL_markstack_ptr++);SWIG_CALLXS(_wrap_mean__SWIG_1); return;
}
}
}
if (items == 2) {
int _v;
{
void *tmp;
if (SWIG_ConvertPtr(ST(0), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
_v = SvIOK(ST(1)) ? 1 : 0;
}
if (_v) {
(*PL_markstack_ptr++);SWIG_CALLXS(_wrap_mean__SWIG_0); return;
}
}
}
croak("No matching function for overloaded 'mean'");
XSRETURN(0);
}
XS(_wrap_meansd__SWIG_0) {
{
EST_Track *arg1 = 0 ;
float *arg2 = 0 ;
float *arg3 = 0 ;
int arg4 ;
float temp2 ;
float temp3 ;
int argvi = 0;
dXSARGS;
arg2 = &temp2;
arg3 = &temp3;
if ((items < 2) || (items > 2)) {
SWIG_croak("Usage: meansd(tr,channel);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of meansd. Expected _p_EST_Track");
}
}
arg4 = (int) SvIV(ST(1));
meansd(*arg1,*arg2,*arg3,arg4);
{
if (argvi >= items) {
EXTEND(sp,1);
}
ST(argvi) = sv_newmortal();
sv_setnv(ST(argvi),(double) *(arg2));
argvi++;
}
{
if (argvi >= items) {
EXTEND(sp,1);
}
ST(argvi) = sv_newmortal();
sv_setnv(ST(argvi),(double) *(arg3));
argvi++;
}
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_meansd__SWIG_1) {
{
EST_Track *arg1 = 0 ;
EST_FVector *arg2 = 0 ;
EST_FVector *arg3 = 0 ;
int argvi = 0;
dXSARGS;
if ((items < 3) || (items > 3)) {
SWIG_croak("Usage: meansd(tr,m,sd);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of meansd. Expected _p_EST_Track");
}
}
{
if (SWIG_ConvertPtr(ST(1), (void **) &arg2, SWIGTYPE_p_EST_FVector,0) < 0) {
SWIG_croak("Type error in argument 2 of meansd. Expected _p_EST_FVector");
}
}
{
if (SWIG_ConvertPtr(ST(2), (void **) &arg3, SWIGTYPE_p_EST_FVector,0) < 0) {
SWIG_croak("Type error in argument 3 of meansd. Expected _p_EST_FVector");
}
}
meansd(*arg1,*arg2,*arg3);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_meansd) {
dXSARGS;
if (items == 2) {
int _v;
{
void *tmp;
if (SWIG_ConvertPtr(ST(0), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
_v = SvIOK(ST(1)) ? 1 : 0;
}
if (_v) {
(*PL_markstack_ptr++);SWIG_CALLXS(_wrap_meansd__SWIG_0); return;
}
}
}
if (items == 3) {
int _v;
{
void *tmp;
if (SWIG_ConvertPtr(ST(0), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
void *tmp;
if (SWIG_ConvertPtr(ST(1), (void **) &tmp, SWIGTYPE_p_EST_FVector, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
void *tmp;
if (SWIG_ConvertPtr(ST(2), (void **) &tmp, SWIGTYPE_p_EST_FVector, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
(*PL_markstack_ptr++);SWIG_CALLXS(_wrap_meansd__SWIG_1); return;
}
}
}
}
croak("No matching function for overloaded 'meansd'");
XSRETURN(0);
}
XS(_wrap_normalise__SWIG_0) {
{
EST_Track *arg1 = 0 ;
int argvi = 0;
dXSARGS;
if ((items < 1) || (items > 1)) {
SWIG_croak("Usage: normalise(tr);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of normalise. Expected _p_EST_Track");
}
}
normalise(*arg1);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_normalise__SWIG_1) {
{
EST_Track *arg1 = 0 ;
float arg2 ;
float arg3 ;
int arg4 ;
float arg5 ;
float arg6 ;
int argvi = 0;
dXSARGS;
if ((items < 6) || (items > 6)) {
SWIG_croak("Usage: normalise(tr,mean,sd,channel,upper,lower);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of normalise. Expected _p_EST_Track");
}
}
arg2 = (float) SvNV(ST(1));
arg3 = (float) SvNV(ST(2));
arg4 = (int) SvIV(ST(3));
arg5 = (float) SvNV(ST(4));
arg6 = (float) SvNV(ST(5));
normalise(*arg1,arg2,arg3,arg4,arg5,arg6);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_normalise__SWIG_2) {
{
EST_Track *arg1 = 0 ;
EST_FVector *arg2 = 0 ;
EST_FVector *arg3 = 0 ;
float arg4 ;
float arg5 ;
int argvi = 0;
dXSARGS;
if ((items < 5) || (items > 5)) {
SWIG_croak("Usage: normalise(tr,mean,sd,upper,lower);");
}
{
if (SWIG_ConvertPtr(ST(0), (void **) &arg1, SWIGTYPE_p_EST_Track,0) < 0) {
SWIG_croak("Type error in argument 1 of normalise. Expected _p_EST_Track");
}
}
{
if (SWIG_ConvertPtr(ST(1), (void **) &arg2, SWIGTYPE_p_EST_FVector,0) < 0) {
SWIG_croak("Type error in argument 2 of normalise. Expected _p_EST_FVector");
}
}
{
if (SWIG_ConvertPtr(ST(2), (void **) &arg3, SWIGTYPE_p_EST_FVector,0) < 0) {
SWIG_croak("Type error in argument 3 of normalise. Expected _p_EST_FVector");
}
}
arg4 = (float) SvNV(ST(3));
arg5 = (float) SvNV(ST(4));
normalise(*arg1,*arg2,*arg3,arg4,arg5);
XSRETURN(argvi);
fail:
;
}
croak(Nullch);
}
XS(_wrap_normalise) {
dXSARGS;
if (items == 1) {
int _v;
{
void *tmp;
if (SWIG_ConvertPtr(ST(0), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
(*PL_markstack_ptr++);SWIG_CALLXS(_wrap_normalise__SWIG_0); return;
}
}
if (items == 5) {
int _v;
{
void *tmp;
if (SWIG_ConvertPtr(ST(0), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
void *tmp;
if (SWIG_ConvertPtr(ST(1), (void **) &tmp, SWIGTYPE_p_EST_FVector, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
void *tmp;
if (SWIG_ConvertPtr(ST(2), (void **) &tmp, SWIGTYPE_p_EST_FVector, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
_v = SvNIOK(ST(3)) ? 1 : 0;
}
if (_v) {
{
_v = SvNIOK(ST(4)) ? 1 : 0;
}
if (_v) {
(*PL_markstack_ptr++);SWIG_CALLXS(_wrap_normalise__SWIG_2); return;
}
}
}
}
}
}
if (items == 6) {
int _v;
{
void *tmp;
if (SWIG_ConvertPtr(ST(0), (void **) &tmp, SWIGTYPE_p_EST_Track, 0) == -1) {
_v = 0;
} else {
_v = 1;
}
}
if (_v) {
{
_v = SvNIOK(ST(1)) ? 1 : 0;
}
if (_v) {
{
_v = SvNIOK(ST(2)) ? 1 : 0;
}
if (_v) {
{
_v = SvIOK(ST(3)) ? 1 : 0;
}
if (_v) {
{
_v = SvNIOK(ST(4)) ? 1 : 0;
}
if (_v) {
{
_v = SvNIOK(ST(5)) ? 1 : 0;
}
if (_v) {
(*PL_markstack_ptr++);SWIG_CALLXS(_wrap_normalise__SWIG_1); return;
}
}
}
}
}
}
}
croak("No matching function for overloaded 'normalise'");
XSRETURN(0);
}
/* -------- TYPE CONVERSION AND EQUIVALENCE RULES (BEGIN) -------- */
static swig_type_info _swigt__p_EST_FVector = {"EST_FVector::EST_FVector", "EST_FVector *", 0, 0, 0};
static swig_type_info _swigt__p_EST_IVector = {"_p_EST_IVector", "EST_IVector *", 0, 0, 0};
static swig_type_info _swigt__p_EST_Track = {"EST_Track::EST_Track", "EST_Track *", 0, 0, 0};
static swig_type_info _swigt__p_EST_read_status = {"_p_EST_read_status", "EST_read_status *", 0, 0, 0};
static swig_type_info _swigt__p_EST_write_status = {"_p_EST_write_status", "EST_write_status *", 0, 0, 0};
static swig_type_info _swigt__p_float = {"_p_float", "float *", 0, 0, 0};
static swig_type_info *swig_type_initial[] = {
&_swigt__p_EST_FVector,
&_swigt__p_EST_IVector,
&_swigt__p_EST_Track,
&_swigt__p_EST_read_status,
&_swigt__p_EST_write_status,
&_swigt__p_float,
};
static swig_cast_info _swigc__p_EST_FVector[] = { {&_swigt__p_EST_FVector, 0, 0, 0},{0, 0, 0, 0}};
static swig_cast_info _swigc__p_EST_IVector[] = { {&_swigt__p_EST_IVector, 0, 0, 0},{0, 0, 0, 0}};
static swig_cast_info _swigc__p_EST_Track[] = { {&_swigt__p_EST_Track, 0, 0, 0},{0, 0, 0, 0}};
static swig_cast_info _swigc__p_EST_read_status[] = { {&_swigt__p_EST_read_status, 0, 0, 0},{0, 0, 0, 0}};
static swig_cast_info _swigc__p_EST_write_status[] = { {&_swigt__p_EST_write_status, 0, 0, 0},{0, 0, 0, 0}};
static swig_cast_info _swigc__p_float[] = { {&_swigt__p_float, 0, 0, 0},{0, 0, 0, 0}};
static swig_cast_info *swig_cast_initial[] = {
_swigc__p_EST_FVector,
_swigc__p_EST_IVector,
_swigc__p_EST_Track,
_swigc__p_EST_read_status,
_swigc__p_EST_write_status,
_swigc__p_float,
};
/* -------- TYPE CONVERSION AND EQUIVALENCE RULES (END) -------- */
static swig_constant_info swig_constants[] = {
{0,0,0,0,0,0}
};
#ifdef __cplusplus
}
#endif
static swig_variable_info swig_variables[] = {
{0,0,0,0}
};
static swig_command_info swig_commands[] = {
{"EST_Trackc::EST_Track_default_frame_shift_get", _wrap_EST_Track_default_frame_shift_get},
{"EST_Trackc::EST_Track_default_sample_rate_get", _wrap_EST_Track_default_sample_rate_get},
{"EST_Trackc::new_EST_Track", _wrap_new_EST_Track},
{"EST_Trackc::delete_EST_Track", _wrap_delete_EST_Track},
{"EST_Trackc::EST_Track_resize", _wrap_EST_Track_resize},
{"EST_Trackc::EST_Track_set_num_channels", _wrap_EST_Track_set_num_channels},
{"EST_Trackc::EST_Track_set_num_frames", _wrap_EST_Track_set_num_frames},
{"EST_Trackc::EST_Track_set_channel_name", _wrap_EST_Track_set_channel_name},
{"EST_Trackc::EST_Track_set_aux_channel_name", _wrap_EST_Track_set_aux_channel_name},
{"EST_Trackc::EST_Track_copy_setup", _wrap_EST_Track_copy_setup},
{"EST_Trackc::EST_Track_name", _wrap_EST_Track_name},
{"EST_Trackc::EST_Track_set_name", _wrap_EST_Track_set_name},
{"EST_Trackc::EST_Track_frame", _wrap_EST_Track_frame},
{"EST_Trackc::EST_Track_channel", _wrap_EST_Track_channel},
{"EST_Trackc::EST_Track_sub_track", _wrap_EST_Track_sub_track},
{"EST_Trackc::EST_Track_copy_sub_track", _wrap_EST_Track_copy_sub_track},
{"EST_Trackc::EST_Track_copy_sub_track_out", _wrap_EST_Track_copy_sub_track_out},
{"EST_Trackc::EST_Track_copy_channel_out", _wrap_EST_Track_copy_channel_out},
{"EST_Trackc::EST_Track_copy_frame_out", _wrap_EST_Track_copy_frame_out},
{"EST_Trackc::EST_Track_copy_channel_in", _wrap_EST_Track_copy_channel_in},
{"EST_Trackc::EST_Track_copy_frame_in", _wrap_EST_Track_copy_frame_in},
{"EST_Trackc::EST_Track_channel_position", _wrap_EST_Track_channel_position},
{"EST_Trackc::EST_Track_has_channel", _wrap_EST_Track_has_channel},
{"EST_Trackc::EST_Track_a", _wrap_EST_Track_a},
{"EST_Trackc::EST_Track_t", _wrap_EST_Track_t},
{"EST_Trackc::EST_Track_ms_t", _wrap_EST_Track_ms_t},
{"EST_Trackc::EST_Track_fill_time", _wrap_EST_Track_fill_time},
{"EST_Trackc::EST_Track_fill", _wrap_EST_Track_fill},
{"EST_Trackc::EST_Track_sample", _wrap_EST_Track_sample},
{"EST_Trackc::EST_Track_shift", _wrap_EST_Track_shift},
{"EST_Trackc::EST_Track_start", _wrap_EST_Track_start},
{"EST_Trackc::EST_Track_end", _wrap_EST_Track_end},
{"EST_Trackc::EST_Track_load", _wrap_EST_Track_load},
{"EST_Trackc::EST_Track_save", _wrap_EST_Track_save},
{"EST_Trackc::EST_Track_empty", _wrap_EST_Track_empty},
{"EST_Trackc::EST_Track_index", _wrap_EST_Track_index},
{"EST_Trackc::EST_Track_index_below", _wrap_EST_Track_index_below},
{"EST_Trackc::EST_Track_num_frames", _wrap_EST_Track_num_frames},
{"EST_Trackc::EST_Track_length", _wrap_EST_Track_length},
{"EST_Trackc::EST_Track_num_channels", _wrap_EST_Track_num_channels},
{"EST_Trackc::EST_Track_num_aux_channels", _wrap_EST_Track_num_aux_channels},
{"EST_Trackc::EST_Track_equal_space", _wrap_EST_Track_equal_space},
{"EST_Trackc::EST_Track_single_break", _wrap_EST_Track_single_break},
{"EST_Trackc::EST_Track_set_equal_space", _wrap_EST_Track_set_equal_space},
{"EST_Trackc::EST_Track_set_single_break", _wrap_EST_Track_set_single_break},
{"EST_Trackc::EST_Track_load_channel_names", _wrap_EST_Track_load_channel_names},
{"EST_Trackc::EST_Track_save_channel_names", _wrap_EST_Track_save_channel_names},
{"EST_Trackc::EST_Track_channel_name", _wrap_EST_Track_channel_name},
{"EST_Trackc::EST_Track_aux_channel_name", _wrap_EST_Track_aux_channel_name},
{"EST_Trackc::mean", _wrap_mean},
{"EST_Trackc::meansd", _wrap_meansd},
{"EST_Trackc::normalise", _wrap_normalise},
{0,0}
};
/*************************************************************************
* Type initialization:
* This problem is tough by the requirement that no dynamic
* memory is used. Also, since swig_type_info structures store pointers to
* swig_cast_info structures and swig_cast_info structures store pointers back
* to swig_type_info structures, we need some lookup code at initialization.
* The idea is that swig generates all the structures that are needed.
* The runtime then collects these partially filled structures.
* The SWIG_InitializeModule function takes these initial arrays out of
* swig_module, and does all the lookup, filling in the swig_module.types
* array with the correct data and linking the correct swig_cast_info
* structures together.
* The generated swig_type_info structures are assigned staticly to an initial
* array. We just loop though that array, and handle each type individually.
* First we lookup if this type has been already loaded, and if so, use the
* loaded structure instead of the generated one. Then we have to fill in the
* cast linked list. The cast data is initially stored in something like a
* two-dimensional array. Each row corresponds to a type (there are the same
* number of rows as there are in the swig_type_initial array). Each entry in
* a column is one of the swig_cast_info structures for that type.
* The cast_initial array is actually an array of arrays, because each row has
* a variable number of columns. So to actually build the cast linked list,
* we find the array of casts associated with the type, and loop through it
* adding the casts to the list. The one last trick we need to do is making
* sure the type pointer in the swig_cast_info struct is correct.
* First off, we lookup the cast->type name to see if it is already loaded.
* There are three cases to handle:
* 1) If the cast->type has already been loaded AND the type we are adding
* casting info to has not been loaded (it is in this module), THEN we
* replace the cast->type pointer with the type pointer that has already
* been loaded.
* 2) If BOTH types (the one we are adding casting info to, and the
* cast->type) are loaded, THEN the cast info has already been loaded by
* the previous module so we just ignore it.
* 3) Finally, if cast->type has not already been loaded, then we add that
* swig_cast_info to the linked list (because the cast->type) pointer will
* be correct.
**/
#ifdef __cplusplus
extern "C" {
#endif
SWIGRUNTIME void
SWIG_InitializeModule(void *clientdata) {
swig_type_info *type, *ret;
swig_cast_info *cast;
size_t i;
swig_module_info *module_head;
static int init_run = 0;
clientdata = clientdata;
if (init_run) return;
init_run = 1;
/* Initialize the swig_module */
swig_module.type_initial = swig_type_initial;
swig_module.cast_initial = swig_cast_initial;
/* Try and load any already created modules */
module_head = SWIG_GetModule(clientdata);
if (module_head) {
swig_module.next = module_head->next;
module_head->next = &swig_module;
} else {
/* This is the first module loaded */
swig_module.next = &swig_module;
SWIG_SetModule(clientdata, &swig_module);
}
/* Now work on filling in swig_module.types */
for (i = 0; i < swig_module.size; ++i) {
type = 0;
/* if there is another module already loaded */
if (swig_module.next != &swig_module) {
type = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, swig_module.type_initial[i]->name);
}
if (type) {
/* Overwrite clientdata field */
if (swig_module.type_initial[i]->clientdata) type->clientdata = swig_module.type_initial[i]->clientdata;
} else {
type = swig_module.type_initial[i];
}
/* Insert casting types */
cast = swig_module.cast_initial[i];
while (cast->type) {
/* Don't need to add information already in the list */
ret = 0;
if (swig_module.next != &swig_module) {
ret = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, cast->type->name);
}
if (ret && type == swig_module.type_initial[i]) {
cast->type = ret;
ret = 0;
}
if (!ret) {
if (type->cast) {
type->cast->prev = cast;
cast->next = type->cast;
}
type->cast = cast;
}
cast++;
}
/* Set entry in modules->types array equal to the type */
swig_module.types[i] = type;
}
swig_module.types[i] = 0;
}
/* This function will propagate the clientdata field of type to
* any new swig_type_info structures that have been added into the list
* of equivalent types. It is like calling
* SWIG_TypeClientData(type, clientdata) a second time.
*/
SWIGRUNTIME void
SWIG_PropagateClientData(void) {
size_t i;
swig_cast_info *equiv;
static int init_run = 0;
if (init_run) return;
init_run = 1;
for (i = 0; i < swig_module.size; i++) {
if (swig_module.types[i]->clientdata) {
equiv = swig_module.types[i]->cast;
while (equiv) {
if (!equiv->converter) {
if (equiv->type && !equiv->type->clientdata)
SWIG_TypeClientData(equiv->type, swig_module.types[i]->clientdata);
}
equiv = equiv->next;
}
}
}
}
#ifdef __cplusplus
}
#endif
#ifdef __cplusplus
extern "C"
#endif
XS(SWIG_init) {
dXSARGS;
int i;
SWIG_InitializeModule(0);
/* Install commands */
for (i = 0; swig_commands[i].name; i++) {
newXS((char*) swig_commands[i].name,swig_commands[i].wrapper, (char*)__FILE__);
}
/* Install variables */
for (i = 0; swig_variables[i].name; i++) {
SV *sv;
sv = perl_get_sv((char*) swig_variables[i].name, TRUE | 0x2);
if (swig_variables[i].type) {
SWIG_MakePtr(sv,(void *)1, *swig_variables[i].type,0);
} else {
sv_setiv(sv,(IV) 0);
}
swig_create_magic(sv, (char *) swig_variables[i].name, swig_variables[i].set, swig_variables[i].get);
}
/* Install constant */
for (i = 0; swig_constants[i].type; i++) {
SV *sv;
sv = perl_get_sv((char*)swig_constants[i].name, TRUE | 0x2);
switch(swig_constants[i].type) {
case SWIG_INT:
sv_setiv(sv, (IV) swig_constants[i].lvalue);
break;
case SWIG_FLOAT:
sv_setnv(sv, (double) swig_constants[i].dvalue);
break;
case SWIG_STRING:
sv_setpv(sv, (char *) swig_constants[i].pvalue);
break;
case SWIG_POINTER:
SWIG_MakePtr(sv, swig_constants[i].pvalue, *(swig_constants[i].ptype),0);
break;
case SWIG_BINARY:
SWIG_MakePackedObj(sv, swig_constants[i].pvalue, swig_constants[i].lvalue, *(swig_constants[i].ptype));
break;
default:
break;
}
SvREADONLY_on(sv);
}
SWIG_TypeClientData(SWIGTYPE_p_EST_Track, (void*) "EST_Track::EST_Track");
ST(0) = &PL_sv_yes;
XSRETURN(1);
}
| 28.127181 | 152 | 0.460831 | [
"object"
] |
d34f29cdc679ce89c6495f8778a806a15b80a066 | 3,241 | cpp | C++ | SPOJ/trash/5-longlong.cpp | AbstractXan/CompetitiveProgramming | a53bf9c3d5dbabd6bc8f13fd1e42613fdd4968d7 | [
"MIT"
] | null | null | null | SPOJ/trash/5-longlong.cpp | AbstractXan/CompetitiveProgramming | a53bf9c3d5dbabd6bc8f13fd1e42613fdd4968d7 | [
"MIT"
] | null | null | null | SPOJ/trash/5-longlong.cpp | AbstractXan/CompetitiveProgramming | a53bf9c3d5dbabd6bc8f13fd1e42613fdd4968d7 | [
"MIT"
] | null | null | null | // Find next smallest palindrome
// Issue : Trailing zeroes
#include<iostream>
#include<cmath>
#include<vector>
using namespace std;
typedef long long int ll;
// Helper
ll FindLength(ll k){return ceil(log10(k));}
ll reverse(ll k){
ll rev=0;
while(k){ rev = rev*10 + k%10; k/=10; }
return rev;
}
class Solution{
ll number;
public:
Solution(ll k){number = k;}
ll nextPrime();
};
ll Solution::nextPrime(){
//FindLength
cout << "called" << endl;
ll length = FindLength(number);
if(number<9){
return number+1;
}else if(number==9 || number==10){
return 11;
}
bool isEvenLength = (fmod(length,2)==0);
// left length and right length
ll llen , rlen;
rlen = length / 2;
if(!isEvenLength){rlen += 1;}
llen = length-rlen;
ll left = number/pow(10,rlen);
ll rev_left = reverse(left);
ll mid_right = fmod( number ,pow(10,rlen)); // mid + right
ll right = (isEvenLength)? mid_right : fmod(mid_right,pow(10,rlen-1));
ll mid = (mid_right - right) / (pow(10,rlen-1)); // Mid for odd lengths
ll num=0;
// cout << left << " " << mid << " " << right << endl;
if (rev_left > right){
num = rev_left + left*pow(10,rlen);
if(!isEvenLength){
num+= ((mid) * pow(10,rlen-1));
}
} else if (rev_left == right){
// Case 2 : If already a palindrome, find the next
Solution n(number+1);
num = n.nextPrime();
} else {
// Case 3 : find new
if(isEvenLength){
// 1234 -> 13 but 1999 -> 2002
num = reverse(left+1) + (left + 1)*pow(10,rlen);
} else {
// 191 -> 201 not palindrom ; 192 -> 202 already a palindrome
if (mid == 9 && (reverse(left+1)!=right) ){
Solution n((mid+1) * pow(10,rlen-1) + left * pow(10,rlen));
num = n.nextPrime();
} else if (mid == 9 && (reverse(left+1)==right) ){ //If adding one gives a palindrome 192 -> 202
num = right + (mid+1) * pow(10,rlen-1) + left * pow(10,rlen);
} else { //Mid not 9
// 131 -> 141
num = rev_left + (mid+1) * pow(10,rlen-1) + left * pow(10,rlen);
}
}
}
return num;
}
vector<pair<ll,ll>> tests;
void runtests(){
tests.push_back(make_pair(1234123,1234321));
tests.push_back(make_pair(123123,123321));
tests.push_back(make_pair(1234321,1235321));
tests.push_back(make_pair(123321,124421));
tests.push_back(make_pair(321321,322223));
tests.push_back(make_pair(191,202));
tests.push_back(make_pair(192,202));
tests.push_back(make_pair(192,202));
tests.push_back(make_pair(131,141));
for(auto x:tests){
Solution s(x.first);
ll next = s.nextPrime();
if(next==x.second){
cout << "Correct" << endl;
} else {
cout << x.first << " " << x.second << " " << next << endl;
}
}
}
int main(){
int testcases;
cin >> testcases;
for ( int i=0; i<testcases ; i++){
ll number;
cin >> number;
Solution s(number);
cout << s.nextPrime() << endl;
}
// runtests();
} | 27.466102 | 108 | 0.533477 | [
"vector"
] |
d35bfd2e4c9ecc2798b8c3ed0c331c8ab0183a15 | 7,814 | cpp | C++ | Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/media/CFaceDetector.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 7 | 2017-07-13T10:34:54.000Z | 2021-04-16T05:40:35.000Z | Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/media/CFaceDetector.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | null | null | null | Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/media/CFaceDetector.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 9 | 2017-07-13T12:33:20.000Z | 2021-06-19T02:46:48.000Z | //=========================================================================
// Copyright (C) 2012 The Elastos Open Source Project
//
// 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 "elastos/droid/media/CFaceDetector.h"
#include "elastos/droid/media/CFace.h"
#include <elastos/utility/logging/Slogger.h>
#include <utils/misc.h>
#include <utils/String8.h>
#include <utils/Log.h>
#include <skia/core/SkBitmap.h>
using namespace Elastos::Core;
using Elastos::Utility::Logging::Slogger;
namespace Elastos {
namespace Droid {
namespace Media {
/*static {
sInitialized = FALSE;
try {
System.loadLibrary("FFTEm");
} catch (UnsatisfiedLinkError e) {
Log.d("FFTEm", "face detection library not found!");
}
}*/
CAR_INTERFACE_IMPL(CFaceDetector, Object, IFaceDetector)
CAR_OBJECT_IMPL(CFaceDetector)
CFaceDetector::CFaceDetector()
: mFD(0)
, mSDK(0)
, mDCR(0)
, mWidth(0)
, mHeight(0)
, mMaxFaces(0)
{
}
CFaceDetector::~CFaceDetector()
{
Finalize();
}
ECode CFaceDetector::constructor(
/* [in] */ Int32 width,
/* [in] */ Int32 height,
/* [in] */ Int32 maxFaces)
{
Int32 status;
FAIL_RETURN(fft_initialize(width, height, maxFaces, &status));
mWidth = width;
mHeight = height;
mMaxFaces = maxFaces;
mBWBuffer = ArrayOf<Byte>::Alloc(width * height);
return NOERROR;
}
ECode CFaceDetector::FindFaces(
/* [in] */ IBitmap* bitmap,
/* [in] */ ArrayOf<IFace*>* faces,
/* [out] */ Int32* num)
{
VALIDATE_NOT_NULL(num);
*num = 0;
VALIDATE_NOT_NULL(bitmap);
Int32 w, h;
bitmap->GetWidth(&w);
bitmap->GetHeight(&h);
if (w != mWidth ||h != mHeight) {
Slogger::E("CFaceDetector", "bitmap size doesn't match initialization");
return E_ILLEGAL_ARGUMENT_EXCEPTION;
}
if (faces->GetLength() < mMaxFaces) {
Slogger::E("CFaceDetector", "faces[] smaller than maxFaces");
return E_ILLEGAL_ARGUMENT_EXCEPTION;
}
Int32 numFaces = fft_detect(bitmap);
if (numFaces >= mMaxFaces)
numFaces = mMaxFaces;
for (Int32 i = 0 ; i < numFaces ; i++) {
if ((*faces)[i] == NULL) {
AutoPtr<IFace> face;
CFace::New((IFace**)&face);
faces->Set(i, face);
}
fft_get_face((*faces)[i], i);
}
*num = numFaces;
return NOERROR;
}
/* no user serviceable parts here ... */
void CFaceDetector::Finalize()
{
fft_destroy();
}
ECode CFaceDetector::fft_initialize(
/* [in] */ Int32 width,
/* [in] */ Int32 height,
/* [in] */ Int32 maxFaces,
/* [out] */ Int32* status)
{
VALIDATE_NOT_NULL(status);
*status = 0;
// // load the configuration file
// const char* root = getenv("ANDROID_ROOT");
// android::String8 path(root);
// path.appendPath("usr/share/bmd/RFFstd_501.bmd");
// // path.appendPath("usr/share/bmd/RFFspeed_501.bmd");
// const int MAX_FILE_SIZE = 65536;
// void* initData = malloc( MAX_FILE_SIZE ); /* enough to fit entire file */
// int filedesc = open(path.string(), O_RDONLY);
// int initDataSize = read(filedesc, initData, MAX_FILE_SIZE);
// close(filedesc);
// // --------------------------------------------------------------------
// btk_HSDK sdk = NULL;
// btk_SDKCreateParam sdkParam = btk_SDK_defaultParam();
// sdkParam.fpMalloc = malloc;
// sdkParam.fpFree = free;
// sdkParam.maxImageWidth = w;
// sdkParam.maxImageHeight = h;
// btk_Status status = btk_SDK_create(&sdkParam, &sdk);
// // make sure everything went well
// if (status != btk_STATUS_OK) {
// // XXX: be more precise about what went wrong
// return E_OUT_OF_MEMORY_ERROR;
// }
// btk_HDCR dcr = NULL;
// btk_DCRCreateParam dcrParam = btk_DCR_defaultParam();
// btk_DCR_create( sdk, &dcrParam, &dcr );
// btk_HFaceFinder fd = NULL;
// btk_FaceFinderCreateParam fdParam = btk_FaceFinder_defaultParam();
// fdParam.pModuleParam = initData;
// fdParam.moduleParamSize = initDataSize;
// fdParam.maxDetectableFaces = maxFaces;
// status = btk_FaceFinder_create( sdk, &fdParam, &fd );
// btk_FaceFinder_setRange(fd, 20, w/2); /* set eye distance range */
// // make sure everything went well
// if (status != btk_STATUS_OK) {
// // XXX: be more precise about what went wrong
// return E_OUT_OF_MEMORY_ERROR;
// }
// // free the configuration file
// free(initData);
// mFD = fd;
// mSDK = sdk;
// mDCR = dcr;
return NOERROR;
}
Int32 CFaceDetector::fft_detect(
/* [in] */ IBitmap* bitmap)
{
// get the fields we need
// btk_HDCR hdcr = (btk_HDCR)(mDCR);
// btk_HFaceFinder hfd = (btk_HFaceFinder)(mFD);
// u32 maxFaces = mMaxFaces;
// u32 width = mWidth;
// u32 height = mHeight;
// // get to the native bitmap
// Handle64 nativeBitmatp = ((CBitmap*)bitmap)->mNativeBitmap;
// SkBitmap const * nativeBitmap = (SkBitmap const *)nativeBitmatp;
// // convert the image to B/W
// uint8_t* dst = (uint8_t*)mBWBuffer.GetPayLoad();
// // manage the life-time of locking our pixels
// SkAutoLockPixels alp(*nativeBitmap);
// uint16_t const* src = (uint16_t const*)nativeBitmap->getPixels();
// int wpr = nativeBitmap->rowBytes() / 2;
// for (u32 y = 0; y < height; y++) {
// for (u32 x = 0 ; x < width ; x++) {
// uint16_t rgb = src[x];
// int r = rgb >> 11;
// int g2 = (rgb >> 5) & 0x3F;
// int b = rgb & 0x1F;
// // L coefficients 0.299 0.587 0.11
// int L = (r<<1) + (g2<<1) + (g2>>1) + b;
// *dst++ = L;
// }
// src += wpr;
// }
// // run detection
// btk_DCR_assignGrayByteImage(hdcr, bwbuffer, width, height);
int numberOfFaces = 0;
// if (btk_FaceFinder_putDCR(hfd, hdcr) == btk_STATUS_OK) {
// numberOfFaces = btk_FaceFinder_faces(hfd);
// }
// else {
// Slogger::E("CFaceDetector", "ERROR: Return 0 faces because error exists in btk_FaceFinder_putDCR.\n");
// }
return numberOfFaces;
}
void CFaceDetector::fft_get_face(
/* [in] */ IFace* face,
/* [in] */ Int32 i)
{
if (face == NULL) {
return;
}
CFace* faceObj = (CFace*)face;
// btk_HDCR hdcr = (btk_HDCR)(mDCR);
// btk_HFaceFinder hfd = (btk_HFaceFinder)(mFD);
// FaceData faceData;
// btk_FaceFinder_getDCR(hfd, hdcr);
// getFaceData(hdcr, &faceData);
// const float X2F = 1.0f / 65536.0f;
// faceObj->mConfidence = faceData.confidence;
// faceObj->mMidpointX = faceData.midpointx;
// faceObj->mMidpointY = faceData.midpointy;
// faceObj->mEyedist = faceData.eyedist;
// faceObj->mEulerX = 0;
// faceObj->mEulerY = 0;
// faceObj->mEulerZ = 0;
}
void CFaceDetector::fft_destroy()
{
// btk_HFaceFinder hfd = (btk_HFaceFinder)(mFD);
// btk_FaceFinder_close( hfd );
// btk_HDCR hdcr = (btk_HDCR)(mDCR);
// btk_DCR_close( hdcr );
// btk_HSDK hsdk = (btk_HSDK)(mSDK);
// btk_SDK_close( hsdk );
}
} // namespace Media
} // namepsace Droid
} // namespace Elastos
| 28.311594 | 113 | 0.592398 | [
"object"
] |
d35ebc1095d89f565f81879cd84f02383d879860 | 1,332 | cpp | C++ | zg_morph.cpp | kejran/zenglue | cdd84ab539b958c09669a2a4091f15a55d139e65 | [
"MIT"
] | null | null | null | zg_morph.cpp | kejran/zenglue | cdd84ab539b958c09669a2a4091f15a55d139e65 | [
"MIT"
] | null | null | null | zg_morph.cpp | kejran/zenglue | cdd84ab539b958c09669a2a4091f15a55d139e65 | [
"MIT"
] | null | null | null | #include <vdfs/fileIndex.h>
#include <zenload/zenParser.h>
#include <zenload/zCMorphMesh.h>
#define EXPORT extern "C" __declspec(dllexport)
using Mesh = ZenLoad::zCMorphMesh;
EXPORT Mesh *zg_morph_init(VDFS::FileIndex *vdfs, const char *name) {
return new Mesh(name, *vdfs);
}
EXPORT void zg_morph_deinit(Mesh *mesh) {
delete mesh;
}
EXPORT uint32_t zg_morph_blend_count(Mesh *mesh) {
return static_cast<uint32_t>(mesh->aniList.size());
}
EXPORT uint32_t zg_morph_frame_count(Mesh *mesh, uint32_t index) {
return static_cast<uint32_t>(mesh->aniList[index].numFrames);
}
EXPORT uint32_t zg_morph_vertex_count(Mesh *mesh, uint32_t index) {
return static_cast<uint32_t>(mesh->aniList[index].vertexIndex.size());
}
EXPORT uint32_t zg_morph_vertex_index_get(Mesh *mesh, uint32_t aniindex, uint32_t vertexindex) {
return static_cast<uint32_t>(mesh->aniList[aniindex].vertexIndex[vertexindex]);
}
EXPORT float *zg_morph_vertex_sample_get(Mesh *mesh, uint32_t aniindex, uint32_t sampleindex) {
return mesh->aniList[aniindex].samples[sampleindex].v;
}
EXPORT const char *zg_morph_name_get(Mesh *mesh, uint32_t index) {
return mesh->aniList[index].name.c_str();
}
EXPORT ZenLoad::PackedMesh *zg_morph_mesh(Mesh *mesh) {
auto result = new ZenLoad::PackedMesh();
mesh->getMesh().packMesh(*result, false);
return result;
}
| 28.956522 | 96 | 0.768769 | [
"mesh"
] |
d35f1798e1c355c814d1e44f016404b4046ac702 | 15,707 | hpp | C++ | craam/Transition.hpp | marekpetrik/CRAAM | 62cc392e876b5383faa5cb15ab1f6b70b26ff395 | [
"MIT"
] | 22 | 2015-09-28T14:41:00.000Z | 2020-07-03T00:16:19.000Z | craam/Transition.hpp | marekpetrik/CRAAM | 62cc392e876b5383faa5cb15ab1f6b70b26ff395 | [
"MIT"
] | 6 | 2017-08-10T18:35:40.000Z | 2018-10-13T01:38:04.000Z | craam/Transition.hpp | marekpetrik/CRAAM | 62cc392e876b5383faa5cb15ab1f6b70b26ff395 | [
"MIT"
] | 10 | 2016-09-19T18:31:07.000Z | 2018-07-05T08:59:45.000Z | // This file is part of CRAAM, a C++ library for solving plain
// and robust Markov decision processes.
//
// 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.
#pragma once
#include "definitions.hpp"
#include <rm/range.hpp>
#include<vector>
#include<string>
#include <algorithm>
#include <stdexcept>
#include <numeric>
#include <cmath>
namespace craam {
using namespace std;
using namespace util::lang;
/** tolerance for checking whether a transition probability is normalized */
const prec_t tolerance = 1e-5;
/**
Represents sparse transition probabilities and rewards from a single state.
The class can be also used to represent a generic sparse distribution.
The destination indexes are sorted increasingly (as added). This makes it simpler to
aggregate multiple transition probabilities and should also make value iteration
more cache friendly. However, transitions need to be added with increasing IDs to
prevent excessive performance degradation.
*/
class Transition {
public:
Transition() : indices(0), probabilities(0), rewards(0) {}
/**
Creates a single transition from raw data.
Because the transition indexes are stored increasingly sorted, this method
must sort (and aggregate duplicate) the indices.
\param indices The indexes of states to transition to
\param probabilities The probabilities of transitions
\param rewards The associated rewards with each transition
*/
Transition(const indvec& indices,
const numvec& probabilities,
const numvec& rewards) : Transition() {
if(indices.size() != probabilities.size() || indices.size() != rewards.size())
throw invalid_argument("All parameters for the constructor of Transition must have the same size.");
auto sorted = sort_indexes(indices);
for(auto k : sorted)
add_sample(indices[k],probabilities[k],rewards[k]);
}
/**
Creates a single transition from raw data with uniformly zero rewards.
Because the transition indexes are stored increasingly sorted, this method
must sort (and aggregate duplicate) the indices.
\param indices The indexes of states to transition to
\param probabilities The probabilities of transitions
*/
Transition(const indvec& indices,
const numvec& probabilities) : Transition() {
if(indices.size() != probabilities.size())
throw invalid_argument("All parameters for the constructor of Transition must have the same size.");
auto sorted = sort_indexes(indices);
for(auto k : sorted)
add_sample(indices[k],probabilities[k],0.0);
}
/**
Creates a single transition from raw data with uniformly zero rewards,
where destination states are indexed automatically starting with 0.
\param probabilities The probabilities of transitions; indexes are implicit.
*/
Transition(const numvec& probabilities) : Transition() {
for(auto k : util::lang::indices(probabilities))
add_sample(long(k), probabilities[k], 0.0);
}
/**
Adds a single transitions probability to the existing probabilities.
If the transition to a state does not exist, then it is simply added to the
list. If the transition to the desired state already exists, then the transition
probability is added and the reward is updated as a weighted combination.
Let \f$ p(s) \f$ and \f$ r(s) \f$ be the current transition probability
and reward respectively. The updated transition probability and reward are:
- Probability:
\f[ p'(s) = p(s) + p \f]
- Reward:
\f[ r'(s) = \frac{p(s) \, r(s) + p \, r}{p'(s)} \f]
Here, \f$ p \f$ is the argument probability and \f$ r \f$ is the argument
reward.
When the function is called multiple times with \f$ p_1 \ldots p_n \f$ and
\f$ r_1 \ldots r_n \f$ for a single \f$ s \f$ then:
- Probability:
\f[ p'(s) = \sum_{i=1}^{n} p_i \f]
- Reward:
\f[ r'(s) = \frac{ \sum_{i=1}^{n} p_i \, r_i}{p'(s)} \f]
Transition probabilities are not checked to sum to one.
\param stateid ID of the target state
\param probability Probability of transitioning to this state
\param reward The reward associated with the transition
*/
void add_sample(long stateid, prec_t probability, prec_t reward){
if(probability < -0.001) throw invalid_argument("probabilities must be non-negative.");
if(stateid < 0) throw invalid_argument("State id must be non-negative.");
// if the probability is 0 or negative, just do not add the sample
if(probability <= 0) return;
// test for the last index; the index is not in the transition yet and belong to the end
if(indices.size() == 0 || this->indices.back() < stateid){
indices.push_back(stateid);
probabilities.push_back(probability);
rewards.push_back(reward);
}
// the index is already in the transitions, or belongs in the middle
else{
size_t findex; // lower bound on the index of the element
bool present; // whether the index was found
// test the last element for efficiency sake
if(stateid == indices.back()){
findex = indices.size() - 1;
present = true;
}
else{
// find the closest existing index to the new one
auto fiter = lower_bound(indices.cbegin(),indices.cend(),stateid);
findex = fiter - indices.cbegin();
present = (*fiter == stateid);
}
// there is a transition to this element already
if(present){
auto p_old = probabilities[findex];
probabilities[findex] += probability;
auto r_old = rewards[findex];
auto new_reward = (p_old * r_old + probability * reward) /
(probabilities[findex]);
rewards[findex] = new_reward;
// the transition is not there, the element needs to be inserted
}else{
indices.insert(indices.cbegin() + findex, stateid);
probabilities.insert(probabilities.cbegin() + findex,probability);
rewards.insert(rewards.cbegin() + findex,reward);
}
}
}
prec_t sum_probabilities() const{
return accumulate(probabilities.cbegin(),probabilities.cend(),0.0);
}
/**
Normalizes the transition probabilities to sum to 1. Exception is thrown if the
distribution sums to 0.
*/
void normalize(){
// nothing to do if there are no transitions
if(probabilities.empty())
return;
prec_t sp = sum_probabilities();
if(sp > tolerance){
for(auto& p : probabilities)
p /= sp;
}else{
throw invalid_argument("Probabilities sum to 0 (or close) and cannot be normalized.");
}
}
/** \returns Whether the transition probabilities sum to 1. */
bool is_normalized() const{
if(indices.empty()) return true;
else return abs(1.0 - sum_probabilities()) < tolerance;
}
/**
Computes value for the transition and a value function.
When there are no target states, the function terminates with an error.
\param valuefunction Value function, or an arbitrary vector of values
\param discount Discount factor, optional (default value 1)
\param probabilities Custom probability distribution. It must be of the same length as
the number of *nonzero* transition probabilities. The length is NOT checked
in a release build.
*/
prec_t value(numvec const& valuefunction, prec_t discount, numvec probabilities) const{
assert(valuefunction.size() >= probabilities.size());
assert(rewards.size() == probabilities.size());
assert(probabilities.size() == indices.size());
if(indices.empty())
throw range_error("No transitions defined for the state action-pair. Cannot compute value.");
prec_t value = 0.0;
//Note: in simple benchmarks, the simd statement seems to speed up the computation
// by a factor of 2-4 with -march=native on a computer with AVX support
#pragma omp simd reduction(+:value)
for(size_t c = 0; c < size(); c++){
value += probabilities[c] * (rewards[c] + discount * valuefunction[indices[c]]);
}
return value;
}
/**
Computes value for the transition and a value function.
When there are no target states, the function terminates with an error.
\param valuefunction Value function, or an arbitrary vector of values
\param discount Discount factor, optional (default value 1)
*/
prec_t value(numvec const& valuefunction, prec_t discount = 1.0) const{
return value(valuefunction, discount, probabilities);
}
/** Computes the mean return from this transition with custom transition probabilities */
prec_t mean_reward(const numvec& probabilities) const{
assert(probabilities.size() == size());
if(indices.empty())
throw range_error("No transitions defined. Cannot compute mean reward.");
return inner_product(probabilities.cbegin(), probabilities.cend(), rewards.cbegin(), 0.0);
}
/** Computes the mean return from this transition */
prec_t mean_reward() const{
return mean_reward(probabilities);
}
/** Returns the number of target states with non-zero transition probabilities. */
size_t size() const {
return indices.size();
}
/** Checks if the transition is empty. */
bool empty() const {
return indices.empty();
}
/**
Returns the maximal indexes involved in the transition.
Returns -1 for and empty transition.
*/
long max_index() const {
return indices.empty() ? -1 : indices.back();
}
/**
Scales transition probabilities according to the provided parameter
and adds them to the provided vector. This method ignores rewards.
\param scale Multiplicative modification of transition probabilities
\param transition Transition probabilities being added to. This value
is modified within the function.
*/
void probabilities_addto(prec_t scale, numvec& transition) const{
for(size_t i : util::lang::indices(*this))
transition[indices[i]] += scale * probabilities[i];
}
/**
Scales transition probabilities and rewards according to the provided parameter
and adds them to the provided vector.
\param scale Multiplicative modification of transition probabilities
\param transition Transition probabilities being added to. This value
is modified within the function.
*/
void probabilities_addto(prec_t scale, Transition& transition) const{
for(size_t i : util::lang::indices(*this))
transition.add_sample(indices[i], scale*probabilities[i], scale*rewards[i]);
}
/**
Constructs and returns a dense vector of probabilities, which
includes 0 transition probabilities.
\param size Size of the constructed vector
*/
numvec probabilities_vector(size_t size) const{
if(max_index() >= 0 && static_cast<long>(size) <= max_index())
throw range_error("Size must be greater than the maximal index");
numvec result(size, 0.0);
for(size_t i : util::lang::indices(indices))
result[indices[i]] = probabilities[i];
return result;
}
/**
Constructs and returns a dense vector of rewards, which
includes 0 transition probabilities. Rewards for indices with
zero transition probability are zero.
\param size Size of the constructed vector
*/
numvec rewards_vector(size_t size) const{
if(max_index() >= 0 && static_cast<long>(size) <= max_index())
throw range_error("Size must be greater than the maximal index");
numvec result(size, 0.0);
for(size_t i : util::lang::indices(indices))
result[indices[i]] = rewards[i];
return result;
}
/** Indices with positive probabilities. */
const indvec& get_indices() const {return indices;};
/** Index of the k-th state with non-zero probability */
long get_index(long k){assert(k>=0 && k < long(size())); return indices[k];}
/**
Returns list of positive probabilities for indexes returned by
get_indices. See also probabilities_vector.
*/
const numvec& get_probabilities() const {return probabilities;};
void set_probabilities(numvec probabilities){
this->probabilities = probabilities;
}
/**
Rewards for indices with positive probabilities returned by
get_indices. See also rewards_vector.
*/
const numvec& get_rewards() const {return rewards;};
/** Sets the reward for a transition to a particular state */
void set_reward(long sampleid, prec_t reward) {rewards[sampleid] = reward;};
/** Gets the reward for a transition to a particular state */
prec_t get_reward(long sampleid) const {
assert(sampleid >= 0 && sampleid < long(size()));
return rewards[sampleid];
};
/** Returns a json representation of transition probabilities
\param outcomeid Includes also outcome id*/
string to_json(long outcomeid = -1) const{
string result{"{"};
result += "\"outcomeid\" : ";
result += std::to_string(outcomeid);
result += ",\"stateids\" : [";
for(auto i : indices){
result += std::to_string(i);
result += ",";
}
if(!indices.empty()) result.pop_back();// remove last comma
result += "],\"probabilities\" : [";
for(auto p : probabilities){
result += std::to_string(p);
result += ",";
}
if(!probabilities.empty()) result.pop_back();// remove last comma
result += "],\"rewards\" : [" ;
for(auto r : rewards){
result += std::to_string(r);
result += ",";
}
if(!rewards.empty()) result.pop_back();// remove last comma
result += "]}";
return result;
}
protected:
/// List of state indices
indvec indices;
/// List of probability distributions to states
numvec probabilities;
/// List of rewards associated with transitions
numvec rewards;
};
}
| 37.939614 | 112 | 0.646463 | [
"vector"
] |
d3676bddfdf3d3fc190b53411f290af27d216c73 | 4,321 | hpp | C++ | data-structures-and-algorithms/project-hashmap/map_vector.hpp | vampy/university | 9496cb63594dcf1cc2cec8650b8eee603f85fdab | [
"MIT"
] | 6 | 2015-06-22T19:43:13.000Z | 2019-07-15T18:08:41.000Z | data-structures-and-algorithms/project-hashmap/map_vector.hpp | vampy/university | 9496cb63594dcf1cc2cec8650b8eee603f85fdab | [
"MIT"
] | null | null | null | data-structures-and-algorithms/project-hashmap/map_vector.hpp | vampy/university | 9496cb63594dcf1cc2cec8650b8eee603f85fdab | [
"MIT"
] | 1 | 2015-09-26T09:01:54.000Z | 2015-09-26T09:01:54.000Z | #ifndef MAP_VECTOR_H_
#define MAP_VECTOR_H_
#include "vector.hpp"
namespace MapVector
{
template <typename TKey, typename TValue>
class Map;
template <typename TKey, typename TValue>
class Entry
{
public:
Entry() {}
Entry(TKey key, TValue value)
{
this->key = key;
this->value = value;
}
TKey key;
TValue value;
};
template <typename TKey, typename TValue>
class Iterator
{
protected:
Map<TKey, TValue>* map;
unsigned int currentPointer;
public:
/**
* Iterrator constructor
* @param map the map
*/
Iterator(Map<TKey, TValue>* map)
{
this->map = map;
currentPointer = 0;
}
/**
* Check if we have more elements in the map
* @return bool
*/
bool hasNext() { return currentPointer < map->getLength(); }
/**
* Move the interal pointer futher into the map, return the current entry
* @return Entry<TValue>*
*/
const Entry<TKey, TValue>* next()
{
Entry<TKey, TValue>* entry = map->mapElements->get(currentPointer);
currentPointer++;
return entry;
}
};
template <typename TKey, typename TValue>
class Map
{
friend class MapVector::Iterator<TKey, TValue>;
public:
/**
* The map constructor
*/
Map() { this->initInternalData(); }
~Map() { this->deleteInternalData(); }
/**
* Get a value by the key string
* @param string key
* @return TValue the value associated with that key
*/
TValue get(TKey key)
{
long index = this->findKey(key);
if (index == -1)
{
printDebug("Key is not in the map");
throw "Key is not in the map";
}
return mapElements->get(index)->value;
}
/**
* Create a new key with the value, or replace the current key with the new value
* if that key already exists
* @param string key
* @param TValue value
*/
void put(TKey key, TValue value)
{
long index = this->findKey(key);
if (index == -1) // key does not exist
{
mapElements->add(new Entry<TKey, TValue>(key, value));
return;
}
// key exists
mapElements->get(index)->value = value;
}
/**
* Remove a map entry based on the key. If the key does not exist, do nothing.
* @param string key
*/
void remove(TKey key)
{
long index = this->findKey(key);
if (index != -1) // found
{
delete mapElements->get(index);
mapElements->remove(index);
}
}
/**
* Checks if the key is in the map
* @param string key
* @return bool
*/
bool containsKey(TKey key) { return (this->findKey(key) != -1); }
/**
* Get the map itertor. You must eliberate the iterator yourself from memory with delete.
* @return MapHash::Iterator<TValue>*
*/
MapVector::Iterator<TKey, TValue>* getIterator() { return new MapVector::Iterator<TKey, TValue>(this); }
/**
* Checks if the map is empty
* @return bool
*/
bool isEmpty() const { return (mapElements->getLength() == 0); }
/**
* Get the number of entries in the map
* @return unsigned int
*/
unsigned int getLength() const { return mapElements->getLength(); }
/**
* Clear all the entries in the map
*/
void clear()
{
this->deleteInternalData();
this->initInternalData();
}
protected:
DynamicArray<Entry<TKey, TValue>*>* mapElements;
/**
* Find the index of a key in the vector elements
* @param string key
* @return long the index in the bucket or -1 otherwise
*/
long findKey(TKey key)
{
for (unsigned int i = 0; i < mapElements->getLength(); i++)
{
if (mapElements->get(i)->key == key)
{
return i;
}
}
return -1;
}
void initInternalData() { mapElements = new DynamicArray<Entry<TKey, TValue>*>; }
void deleteInternalData()
{
for (unsigned int i = 0; i < mapElements->getLength(); i++)
{
delete mapElements->get(i);
}
delete mapElements;
mapElements = NULL;
}
};
}
#endif // MAP_VECTOR_H_
| 21.93401 | 108 | 0.558436 | [
"vector"
] |
d36b3291896c0c31961ebcff73b6d4593a33cd65 | 867 | hpp | C++ | three/extras/geometries/text_2d_geometry.hpp | Lecrapouille/three_cpp | 5c3b4f4ca02bda6af232898c17e62caf8f887aa0 | [
"MIT"
] | null | null | null | three/extras/geometries/text_2d_geometry.hpp | Lecrapouille/three_cpp | 5c3b4f4ca02bda6af232898c17e62caf8f887aa0 | [
"MIT"
] | null | null | null | three/extras/geometries/text_2d_geometry.hpp | Lecrapouille/three_cpp | 5c3b4f4ca02bda6af232898c17e62caf8f887aa0 | [
"MIT"
] | null | null | null | #ifndef THREE_TEXT_2D_GEOMETRY_HPP
#define THREE_TEXT_2D_GEOMETRY_HPP
#include <three/core/geometry.hpp>
#include <three/extras/utils/font.hpp>
namespace three {
class Text2DGeometry : public Geometry
{
public:
typedef std::shared_ptr<Text2DGeometry> Ptr;
THREE_DECL static Ptr create(const std::string& text,
const Font::Ptr& font);
#ifdef TODO_THREE_DYNAMIC_GEOMETRY
THREE_DECL void update(const std::string& text);
#endif
protected:
THREE_DECL Text2DGeometry(const std::string& text,
const Font::Ptr& font);
THREE_DECL void update();
std::string text;
Font::Ptr font;
};
} // namespace three
#if defined(THREE_HEADER_ONLY)
# include <three/extras/geometries/impl/text_2d_geometry.ipp>
#endif // defined(THREE_HEADER_ONLY)
#endif // THREE_TEXT_2D_GEOMETRY_HPP | 22.815789 | 64 | 0.700115 | [
"geometry"
] |
d36b846be01d930b28819829b578fac499b97acb | 6,055 | cpp | C++ | src/tools/ast_generator.cpp | spraza/lox-cpp | 7ebd34080324051371e00cd9e9d0fea5022a2c3a | [
"MIT"
] | 5 | 2019-08-04T17:32:46.000Z | 2022-01-03T07:37:19.000Z | src/tools/ast_generator.cpp | paymaan/lox-cpp | 7ebd34080324051371e00cd9e9d0fea5022a2c3a | [
"MIT"
] | null | null | null | src/tools/ast_generator.cpp | paymaan/lox-cpp | 7ebd34080324051371e00cd9e9d0fea5022a2c3a | [
"MIT"
] | 2 | 2021-11-13T19:28:57.000Z | 2022-02-03T04:21:12.000Z | #include <fstream>
#include <iostream>
#include <string>
#include <utility>
#include <vector>
namespace so_utils {
// source:
// https://stackoverflow.com/questions/14265581/parse-split-a-string-in-c-using-string-delimiter-standard-c
static std::vector<std::string> split(const std::string& str,
const std::string& delim) {
std::vector<std::string> tokens;
size_t prev = 0, pos = 0;
do {
pos = str.find(delim, prev);
if (pos == std::string::npos)
pos = str.length();
auto token = str.substr(prev, pos - prev);
if (!token.empty())
tokens.push_back(token);
prev = pos + delim.length();
} while (pos < str.length() && prev < str.length());
return tokens;
}
} // namespace so_utils
class ASTGenerator {
public:
using ASTSpecification = std::pair<std::string, std::vector<std::string>>;
ASTGenerator(const std::string& aDir, const ASTSpecification aSpec)
: outDir(aDir)
, astSpec(aSpec) {}
void generate() {
std::cout << outDir << std::endl;
defineAST();
}
void defineAST() {
auto baseName = astSpec.first;
auto path = outDir + "/" + baseName + ".hpp";
std::ofstream file(path);
if (!file.is_open()) {
std::cout << "Unable to open file." << std::endl;
return;
}
/// #ifndef guard
file << "#ifndef " + baseName + "_HPP" << std::endl;
file << "#define " + baseName + "_HPP" << std::endl;
// Expr base abstract interface
file << "#include \"scanner/token.hpp\"" << std::endl;
file << "using namespace lox;" << std::endl;
// forward declarations
file << "class " << baseName << "; // forward declare" << std::endl;
for (auto type : astSpec.second) {
auto className = type.substr(0, type.find(":"));
file << "class " << className << "; // forward declare"
<< std::endl;
}
defineVisitor(file, baseName);
file << "class " << baseName << " {" << std::endl;
file << "public:" << std::endl;
file << "virtual ~" << baseName << "() {}" << std::endl;
file << "virtual void accept(" << baseName + "Visitor* visitor) = 0;"
<< std::endl;
file << "};" << std::endl;
// Derived concrete classes
for (auto type : astSpec.second) {
auto className = type.substr(0, type.find(":"));
auto fields = type.substr(type.find(":") + 1, type.size());
defineType(file, baseName, className, fields);
}
/// #endif for #ifndef
file << "#endif" << std::endl;
file.close();
}
void defineType(std::ofstream& file, const std::string& baseName,
const std::string& className, const std::string fields) {
file << "class " + className + " : public " + baseName + " { "
<< std::endl;
file << "public: " << std::endl;
file << className + "(";
auto fieldList = so_utils::split(fields, ",");
bool first = true;
for (auto field : fieldList) {
if (!first)
file << ", ";
if (first)
first = false;
auto fieldType = so_utils::split(field, " ")[0];
auto fieldName = so_utils::split(field, " ")[1];
if (!fieldType.compare(baseName)) {
file << fieldType + "* " + fieldName;
} else {
file << fieldType + " " + fieldName;
}
}
file << ") : ";
first = true;
for (auto field : fieldList) {
if (!first)
file << ", ";
if (first)
first = false;
auto fieldName = so_utils::split(field, " ")[1];
file << fieldName + "(" + fieldName + ")";
}
file << " {}" << std::endl;
file << "void accept(" << baseName + "Visitor* visitor) override {"
<< std::endl;
file << "visitor->visit" << className << "(this);" << std::endl;
file << "}" << std::endl;
file << "public: " << std::endl;
for (auto field : fieldList) {
auto fieldType = so_utils::split(field, " ")[0];
auto fieldName = so_utils::split(field, " ")[1];
if (!fieldType.compare(baseName)) {
file << fieldType + "* " + fieldName + ";" << std::endl;
} else {
file << fieldType + " " + fieldName + ";" << std::endl;
}
}
file << "};" << std::endl;
}
void defineVisitor(std::ofstream& file, const std::string& baseName) {
auto visitorClassName = baseName + "Visitor";
file << "class " << visitorClassName << " {" << std::endl;
file << "public:" << std::endl;
file << "virtual ~" << visitorClassName << "() {}" << std::endl;
for (auto type : astSpec.second) {
auto className = type.substr(0, type.find(":"));
file << "virtual void "
<< "visit" + className << "(" << className << "* " << baseName
<< ") = 0;" << std::endl;
}
file << "};" << std::endl;
}
private:
const std::string outDir;
const ASTSpecification astSpec;
};
int main(int argc, char** argv) {
if (argc != 2) {
std::cout << "Usage: ast_generator <output directory>" << std::endl;
} else {
const std::string outDir = argv[1];
const ASTGenerator::ASTSpecification astSpec = {
"Expr",
{"BinaryExpr :Expr left,Token Operator,Expr right",
"GroupingExpr :Expr expression", "LiteralExpr :std::string value",
"UnaryExpr :Token Operator,Expr right"}};
ASTGenerator astGenerator(outDir, astSpec);
astGenerator.generate();
}
return 0;
}
| 36.69697 | 111 | 0.488026 | [
"vector"
] |
d36fdd67d218821cc458b599bf5db8dc1eb05f5a | 17,174 | cpp | C++ | apiwzsk/CrdWzskLlv.cpp | mpsitech/wzsk-Whiznium-StarterK | 94a0a8a05a0fac06c4360b8f835556a299b9425a | [
"MIT"
] | 1 | 2020-09-20T16:25:07.000Z | 2020-09-20T16:25:07.000Z | apiwzsk/CrdWzskLlv.cpp | mpsitech/wzsk-Whiznium-StarterKit | 94a0a8a05a0fac06c4360b8f835556a299b9425a | [
"MIT"
] | null | null | null | apiwzsk/CrdWzskLlv.cpp | mpsitech/wzsk-Whiznium-StarterKit | 94a0a8a05a0fac06c4360b8f835556a299b9425a | [
"MIT"
] | null | null | null | /**
* \file CrdWzskLlv.cpp
* API code for job CrdWzskLlv (implementation)
* \copyright (C) 2016-2020 MPSI Technologies GmbH
* \author Emily Johnson (auto-generation)
* \date created: 5 Dec 2020
*/
// IP header --- ABOVE
#include "CrdWzskLlv.h"
using namespace std;
using namespace Sbecore;
using namespace Xmlio;
/******************************************************************************
class CrdWzskLlv::VecVDo
******************************************************************************/
uint CrdWzskLlv::VecVDo::getIx(
const string& sref
) {
string s = StrMod::lc(sref);
if (s == "close") return CLOSE;
if (s == "mitappabtclick") return MITAPPABTCLICK;
return(0);
};
string CrdWzskLlv::VecVDo::getSref(
const uint ix
) {
if (ix == CLOSE) return("close");
if (ix == MITAPPABTCLICK) return("MitAppAbtClick");
return("");
};
/******************************************************************************
class CrdWzskLlv::VecVSge
******************************************************************************/
uint CrdWzskLlv::VecVSge::getIx(
const string& sref
) {
string s = StrMod::lc(sref);
if (s == "idle") return IDLE;
if (s == "alrwzskabt") return ALRWZSKABT;
return(0);
};
string CrdWzskLlv::VecVSge::getSref(
const uint ix
) {
if (ix == IDLE) return("idle");
if (ix == ALRWZSKABT) return("alrwzskabt");
return("");
};
/******************************************************************************
class CrdWzskLlv::ContInf
******************************************************************************/
CrdWzskLlv::ContInf::ContInf(
const uint numFSge
, const string& MrlAppHlp
) :
Block()
{
this->numFSge = numFSge;
this->MrlAppHlp = MrlAppHlp;
mask = {NUMFSGE, MRLAPPHLP};
};
bool CrdWzskLlv::ContInf::readXML(
xmlXPathContext* docctx
, string basexpath
, bool addbasetag
) {
clear();
bool basefound;
if (addbasetag)
basefound = checkUclcXPaths(docctx, basexpath, basexpath, "ContInfWzskLlv");
else
basefound = checkXPath(docctx, basexpath);
string itemtag = "ContitemInfWzskLlv";
if (basefound) {
if (extractUintAttrUclc(docctx, basexpath, itemtag, "Ci", "sref", "numFSge", numFSge)) add(NUMFSGE);
if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ci", "sref", "MrlAppHlp", MrlAppHlp)) add(MRLAPPHLP);
};
return basefound;
};
set<uint> CrdWzskLlv::ContInf::comm(
const ContInf* comp
) {
set<uint> items;
if (numFSge == comp->numFSge) insert(items, NUMFSGE);
if (MrlAppHlp == comp->MrlAppHlp) insert(items, MRLAPPHLP);
return(items);
};
set<uint> CrdWzskLlv::ContInf::diff(
const ContInf* comp
) {
set<uint> commitems;
set<uint> diffitems;
commitems = comm(comp);
diffitems = {NUMFSGE, MRLAPPHLP};
for (auto it = commitems.begin(); it != commitems.end(); it++) diffitems.erase(*it);
return(diffitems);
};
/******************************************************************************
class CrdWzskLlv::StatApp
******************************************************************************/
CrdWzskLlv::StatApp::StatApp(
const uint ixWzskVReqitmode
, const usmallint latency
, const string& shortMenu
, const uint widthMenu
, const bool initdoneHeadbar
, const bool initdoneTermArty
, const bool initdoneTermClnxevb
, const bool initdoneTermIcicle
, const bool initdoneTermMcvevp
, const bool initdoneTermUvbdvk
, const bool initdoneCamera
, const bool initdoneTtable
, const bool initdoneLaser
) :
Block()
{
this->ixWzskVReqitmode = ixWzskVReqitmode;
this->latency = latency;
this->shortMenu = shortMenu;
this->widthMenu = widthMenu;
this->initdoneHeadbar = initdoneHeadbar;
this->initdoneTermArty = initdoneTermArty;
this->initdoneTermClnxevb = initdoneTermClnxevb;
this->initdoneTermIcicle = initdoneTermIcicle;
this->initdoneTermMcvevp = initdoneTermMcvevp;
this->initdoneTermUvbdvk = initdoneTermUvbdvk;
this->initdoneCamera = initdoneCamera;
this->initdoneTtable = initdoneTtable;
this->initdoneLaser = initdoneLaser;
mask = {IXWZSKVREQITMODE, LATENCY, SHORTMENU, WIDTHMENU, INITDONEHEADBAR, INITDONETERMARTY, INITDONETERMCLNXEVB, INITDONETERMICICLE, INITDONETERMMCVEVP, INITDONETERMUVBDVK, INITDONECAMERA, INITDONETTABLE, INITDONELASER};
};
bool CrdWzskLlv::StatApp::readXML(
xmlXPathContext* docctx
, string basexpath
, bool addbasetag
) {
clear();
string srefIxWzskVReqitmode;
bool basefound;
if (addbasetag)
basefound = checkUclcXPaths(docctx, basexpath, basexpath, "StatAppWzskLlv");
else
basefound = checkXPath(docctx, basexpath);
string itemtag = "StatitemAppWzskLlv";
if (basefound) {
if (extractStringAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "srefIxWzskVReqitmode", srefIxWzskVReqitmode)) {
ixWzskVReqitmode = VecWzskVReqitmode::getIx(srefIxWzskVReqitmode);
add(IXWZSKVREQITMODE);
};
if (extractUsmallintAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "latency", latency)) add(LATENCY);
if (extractStringAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "shortMenu", shortMenu)) add(SHORTMENU);
if (extractUintAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "widthMenu", widthMenu)) add(WIDTHMENU);
if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "initdoneHeadbar", initdoneHeadbar)) add(INITDONEHEADBAR);
if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "initdoneTermArty", initdoneTermArty)) add(INITDONETERMARTY);
if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "initdoneTermClnxevb", initdoneTermClnxevb)) add(INITDONETERMCLNXEVB);
if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "initdoneTermIcicle", initdoneTermIcicle)) add(INITDONETERMICICLE);
if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "initdoneTermMcvevp", initdoneTermMcvevp)) add(INITDONETERMMCVEVP);
if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "initdoneTermUvbdvk", initdoneTermUvbdvk)) add(INITDONETERMUVBDVK);
if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "initdoneCamera", initdoneCamera)) add(INITDONECAMERA);
if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "initdoneTtable", initdoneTtable)) add(INITDONETTABLE);
if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "initdoneLaser", initdoneLaser)) add(INITDONELASER);
};
return basefound;
};
set<uint> CrdWzskLlv::StatApp::comm(
const StatApp* comp
) {
set<uint> items;
if (ixWzskVReqitmode == comp->ixWzskVReqitmode) insert(items, IXWZSKVREQITMODE);
if (latency == comp->latency) insert(items, LATENCY);
if (shortMenu == comp->shortMenu) insert(items, SHORTMENU);
if (widthMenu == comp->widthMenu) insert(items, WIDTHMENU);
if (initdoneHeadbar == comp->initdoneHeadbar) insert(items, INITDONEHEADBAR);
if (initdoneTermArty == comp->initdoneTermArty) insert(items, INITDONETERMARTY);
if (initdoneTermClnxevb == comp->initdoneTermClnxevb) insert(items, INITDONETERMCLNXEVB);
if (initdoneTermIcicle == comp->initdoneTermIcicle) insert(items, INITDONETERMICICLE);
if (initdoneTermMcvevp == comp->initdoneTermMcvevp) insert(items, INITDONETERMMCVEVP);
if (initdoneTermUvbdvk == comp->initdoneTermUvbdvk) insert(items, INITDONETERMUVBDVK);
if (initdoneCamera == comp->initdoneCamera) insert(items, INITDONECAMERA);
if (initdoneTtable == comp->initdoneTtable) insert(items, INITDONETTABLE);
if (initdoneLaser == comp->initdoneLaser) insert(items, INITDONELASER);
return(items);
};
set<uint> CrdWzskLlv::StatApp::diff(
const StatApp* comp
) {
set<uint> commitems;
set<uint> diffitems;
commitems = comm(comp);
diffitems = {IXWZSKVREQITMODE, LATENCY, SHORTMENU, WIDTHMENU, INITDONEHEADBAR, INITDONETERMARTY, INITDONETERMCLNXEVB, INITDONETERMICICLE, INITDONETERMMCVEVP, INITDONETERMUVBDVK, INITDONECAMERA, INITDONETTABLE, INITDONELASER};
for (auto it = commitems.begin(); it != commitems.end(); it++) diffitems.erase(*it);
return(diffitems);
};
/******************************************************************************
class CrdWzskLlv::StatShr
******************************************************************************/
CrdWzskLlv::StatShr::StatShr(
const string& scrJrefHeadbar
, const string& scrJrefTermArty
, const bool pnltermartyAvail
, const string& scrJrefTermClnxevb
, const bool pnltermclnxevbAvail
, const string& scrJrefTermIcicle
, const bool pnltermicicleAvail
, const string& scrJrefTermMcvevp
, const bool pnltermmcvevpAvail
, const string& scrJrefTermUvbdvk
, const bool pnltermuvbdvkAvail
, const string& scrJrefCamera
, const string& scrJrefTtable
, const string& scrJrefLaser
) :
Block()
{
this->scrJrefHeadbar = scrJrefHeadbar;
this->scrJrefTermArty = scrJrefTermArty;
this->pnltermartyAvail = pnltermartyAvail;
this->scrJrefTermClnxevb = scrJrefTermClnxevb;
this->pnltermclnxevbAvail = pnltermclnxevbAvail;
this->scrJrefTermIcicle = scrJrefTermIcicle;
this->pnltermicicleAvail = pnltermicicleAvail;
this->scrJrefTermMcvevp = scrJrefTermMcvevp;
this->pnltermmcvevpAvail = pnltermmcvevpAvail;
this->scrJrefTermUvbdvk = scrJrefTermUvbdvk;
this->pnltermuvbdvkAvail = pnltermuvbdvkAvail;
this->scrJrefCamera = scrJrefCamera;
this->scrJrefTtable = scrJrefTtable;
this->scrJrefLaser = scrJrefLaser;
mask = {SCRJREFHEADBAR, SCRJREFTERMARTY, PNLTERMARTYAVAIL, SCRJREFTERMCLNXEVB, PNLTERMCLNXEVBAVAIL, SCRJREFTERMICICLE, PNLTERMICICLEAVAIL, SCRJREFTERMMCVEVP, PNLTERMMCVEVPAVAIL, SCRJREFTERMUVBDVK, PNLTERMUVBDVKAVAIL, SCRJREFCAMERA, SCRJREFTTABLE, SCRJREFLASER};
};
bool CrdWzskLlv::StatShr::readXML(
xmlXPathContext* docctx
, string basexpath
, bool addbasetag
) {
clear();
bool basefound;
if (addbasetag)
basefound = checkUclcXPaths(docctx, basexpath, basexpath, "StatShrWzskLlv");
else
basefound = checkXPath(docctx, basexpath);
string itemtag = "StatitemShrWzskLlv";
if (basefound) {
if (extractStringAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "scrJrefHeadbar", scrJrefHeadbar)) add(SCRJREFHEADBAR);
if (extractStringAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "scrJrefTermArty", scrJrefTermArty)) add(SCRJREFTERMARTY);
if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "pnltermartyAvail", pnltermartyAvail)) add(PNLTERMARTYAVAIL);
if (extractStringAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "scrJrefTermClnxevb", scrJrefTermClnxevb)) add(SCRJREFTERMCLNXEVB);
if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "pnltermclnxevbAvail", pnltermclnxevbAvail)) add(PNLTERMCLNXEVBAVAIL);
if (extractStringAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "scrJrefTermIcicle", scrJrefTermIcicle)) add(SCRJREFTERMICICLE);
if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "pnltermicicleAvail", pnltermicicleAvail)) add(PNLTERMICICLEAVAIL);
if (extractStringAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "scrJrefTermMcvevp", scrJrefTermMcvevp)) add(SCRJREFTERMMCVEVP);
if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "pnltermmcvevpAvail", pnltermmcvevpAvail)) add(PNLTERMMCVEVPAVAIL);
if (extractStringAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "scrJrefTermUvbdvk", scrJrefTermUvbdvk)) add(SCRJREFTERMUVBDVK);
if (extractBoolAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "pnltermuvbdvkAvail", pnltermuvbdvkAvail)) add(PNLTERMUVBDVKAVAIL);
if (extractStringAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "scrJrefCamera", scrJrefCamera)) add(SCRJREFCAMERA);
if (extractStringAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "scrJrefTtable", scrJrefTtable)) add(SCRJREFTTABLE);
if (extractStringAttrUclc(docctx, basexpath, itemtag, "Si", "sref", "scrJrefLaser", scrJrefLaser)) add(SCRJREFLASER);
};
return basefound;
};
set<uint> CrdWzskLlv::StatShr::comm(
const StatShr* comp
) {
set<uint> items;
if (scrJrefHeadbar == comp->scrJrefHeadbar) insert(items, SCRJREFHEADBAR);
if (scrJrefTermArty == comp->scrJrefTermArty) insert(items, SCRJREFTERMARTY);
if (pnltermartyAvail == comp->pnltermartyAvail) insert(items, PNLTERMARTYAVAIL);
if (scrJrefTermClnxevb == comp->scrJrefTermClnxevb) insert(items, SCRJREFTERMCLNXEVB);
if (pnltermclnxevbAvail == comp->pnltermclnxevbAvail) insert(items, PNLTERMCLNXEVBAVAIL);
if (scrJrefTermIcicle == comp->scrJrefTermIcicle) insert(items, SCRJREFTERMICICLE);
if (pnltermicicleAvail == comp->pnltermicicleAvail) insert(items, PNLTERMICICLEAVAIL);
if (scrJrefTermMcvevp == comp->scrJrefTermMcvevp) insert(items, SCRJREFTERMMCVEVP);
if (pnltermmcvevpAvail == comp->pnltermmcvevpAvail) insert(items, PNLTERMMCVEVPAVAIL);
if (scrJrefTermUvbdvk == comp->scrJrefTermUvbdvk) insert(items, SCRJREFTERMUVBDVK);
if (pnltermuvbdvkAvail == comp->pnltermuvbdvkAvail) insert(items, PNLTERMUVBDVKAVAIL);
if (scrJrefCamera == comp->scrJrefCamera) insert(items, SCRJREFCAMERA);
if (scrJrefTtable == comp->scrJrefTtable) insert(items, SCRJREFTTABLE);
if (scrJrefLaser == comp->scrJrefLaser) insert(items, SCRJREFLASER);
return(items);
};
set<uint> CrdWzskLlv::StatShr::diff(
const StatShr* comp
) {
set<uint> commitems;
set<uint> diffitems;
commitems = comm(comp);
diffitems = {SCRJREFHEADBAR, SCRJREFTERMARTY, PNLTERMARTYAVAIL, SCRJREFTERMCLNXEVB, PNLTERMCLNXEVBAVAIL, SCRJREFTERMICICLE, PNLTERMICICLEAVAIL, SCRJREFTERMMCVEVP, PNLTERMMCVEVPAVAIL, SCRJREFTERMUVBDVK, PNLTERMUVBDVKAVAIL, SCRJREFCAMERA, SCRJREFTTABLE, SCRJREFLASER};
for (auto it = commitems.begin(); it != commitems.end(); it++) diffitems.erase(*it);
return(diffitems);
};
/******************************************************************************
class CrdWzskLlv::Tag
******************************************************************************/
CrdWzskLlv::Tag::Tag(
const string& MitAppAbt
, const string& MrlAppHlp
) :
Block()
{
this->MitAppAbt = MitAppAbt;
this->MrlAppHlp = MrlAppHlp;
mask = {MITAPPABT, MRLAPPHLP};
};
bool CrdWzskLlv::Tag::readXML(
xmlXPathContext* docctx
, string basexpath
, bool addbasetag
) {
clear();
bool basefound;
if (addbasetag)
basefound = checkUclcXPaths(docctx, basexpath, basexpath, "TagWzskLlv");
else
basefound = checkXPath(docctx, basexpath);
string itemtag = "TagitemWzskLlv";
if (basefound) {
if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "MitAppAbt", MitAppAbt)) add(MITAPPABT);
if (extractStringAttrUclc(docctx, basexpath, itemtag, "Ti", "sref", "MrlAppHlp", MrlAppHlp)) add(MRLAPPHLP);
};
return basefound;
};
/******************************************************************************
class CrdWzskLlv::DpchAppDo
******************************************************************************/
CrdWzskLlv::DpchAppDo::DpchAppDo(
const string& scrJref
, const uint ixVDo
, const set<uint>& mask
) :
DpchAppWzsk(VecWzskVDpch::DPCHAPPWZSKLLVDO, scrJref)
{
if (find(mask, ALL)) this->mask = {SCRJREF, IXVDO};
else this->mask = mask;
this->ixVDo = ixVDo;
};
string CrdWzskLlv::DpchAppDo::getSrefsMask() {
vector<string> ss;
string srefs;
if (has(SCRJREF)) ss.push_back("scrJref");
if (has(IXVDO)) ss.push_back("ixVDo");
StrMod::vectorToString(ss, srefs);
return(srefs);
};
void CrdWzskLlv::DpchAppDo::writeXML(
xmlTextWriter* wr
) {
xmlTextWriterStartElement(wr, BAD_CAST "DpchAppWzskLlvDo");
xmlTextWriterWriteAttribute(wr, BAD_CAST "xmlns", BAD_CAST "http://www.mpsitech.com/wzsk");
if (has(SCRJREF)) writeString(wr, "scrJref", scrJref);
if (has(IXVDO)) writeString(wr, "srefIxVDo", VecVDo::getSref(ixVDo));
xmlTextWriterEndElement(wr);
};
/******************************************************************************
class CrdWzskLlv::DpchEngData
******************************************************************************/
CrdWzskLlv::DpchEngData::DpchEngData() :
DpchEngWzsk(VecWzskVDpch::DPCHENGWZSKLLVDATA)
{
feedFSge.tag = "FeedFSge";
};
string CrdWzskLlv::DpchEngData::getSrefsMask() {
vector<string> ss;
string srefs;
if (has(SCRJREF)) ss.push_back("scrJref");
if (has(CONTINF)) ss.push_back("continf");
if (has(FEEDFSGE)) ss.push_back("feedFSge");
if (has(STATAPP)) ss.push_back("statapp");
if (has(STATSHR)) ss.push_back("statshr");
if (has(TAG)) ss.push_back("tag");
StrMod::vectorToString(ss, srefs);
return(srefs);
};
void CrdWzskLlv::DpchEngData::readXML(
xmlXPathContext* docctx
, string basexpath
, bool addbasetag
) {
clear();
bool basefound;
if (addbasetag)
basefound = checkUclcXPaths(docctx, basexpath, basexpath, "DpchEngWzskLlvData");
else
basefound = checkXPath(docctx, basexpath);
if (basefound) {
if (extractStringUclc(docctx, basexpath, "scrJref", "", scrJref)) add(SCRJREF);
if (continf.readXML(docctx, basexpath, true)) add(CONTINF);
if (feedFSge.readXML(docctx, basexpath, true)) add(FEEDFSGE);
if (statapp.readXML(docctx, basexpath, true)) add(STATAPP);
if (statshr.readXML(docctx, basexpath, true)) add(STATSHR);
if (tag.readXML(docctx, basexpath, true)) add(TAG);
} else {
continf = ContInf();
feedFSge.clear();
statapp = StatApp();
statshr = StatShr();
tag = Tag();
};
};
| 35.04898 | 267 | 0.685862 | [
"vector"
] |
c965350f6d02526c1c29e826b20bca60b951f964 | 4,062 | hpp | C++ | src/lib/FeltElements/internal/Format.hpp | feltech/FeltElements | 8f6374945e46a9c9a2a742482ffe6b923b8b5c25 | [
"MIT"
] | null | null | null | src/lib/FeltElements/internal/Format.hpp | feltech/FeltElements | 8f6374945e46a9c9a2a742482ffe6b923b8b5c25 | [
"MIT"
] | null | null | null | src/lib/FeltElements/internal/Format.hpp | feltech/FeltElements | 8f6374945e46a9c9a2a742482ffe6b923b8b5c25 | [
"MIT"
] | null | null | null | #pragma once
#ifndef EIGEN_DEFAULT_IO_FORMAT
#define EIGEN_DEFAULT_IO_FORMAT Eigen::IOFormat(12, 0, ", ", ",\n", "", "", "", "")
#endif
#include <fmt/format.h>
#include <fmt/ostream.h>
#include <spdlog/fmt/ostr.h>
#include <FeltElements/Typedefs.hpp>
#include <boost/algorithm/string/join.hpp>
#include <boost/range/adaptor/transformed.hpp>
#include <boost/range/irange.hpp>
namespace
{
// std::to_string has non-configurable precision of too many decimal places.
auto const to_string = [](auto const f) { return fmt::format("{:f}", f); };
} // namespace
namespace Fastor
{
template <std::size_t dim0, std::size_t dim1, std::size_t dim2, std::size_t dim3>
std::ostream & operator<<(
std::ostream & os, FeltElements::Tensor::Multi<dim0, dim1, dim2, dim3> value)
{
using FeltElements::Tensor::Index;
using FeltElements::Tensor::Vector;
using boost::algorithm::join;
std::array<std::string, value.dimension(0)> is{};
std::array<std::string, value.dimension(1)> js{};
std::array<std::string, value.dimension(2)> ks{};
for (Index i = 0; i < value.dimension(0); i++)
{
for (Index j = 0; j < value.dimension(1); j++)
{
for (Index k = 0; k < value.dimension(2); k++)
{
using FeltElements::Tensor::Func::all;
using Vec = Vector<value.dimension(3)>;
Vec const & vec = value(i, j, k, all);
ks[k] = join(
boost::make_iterator_range(vec.data(), vec.data() + Vec::size()) |
boost::adaptors::transformed(to_string),
", ");
}
js[j] = join(ks, "}, {");
}
is[i] = join(js, "}},\n\t{{");
}
os << "{\n\t{{" << join(is, "}}\n}, {\n\t{{") << "}}\n}\n";
return os;
}
template <std::size_t dim0, std::size_t dim1, std::size_t dim2>
std::ostream & operator<<(std::ostream & os, FeltElements::Tensor::Multi<dim0, dim1, dim2> value)
{
using boost::algorithm::join;
using FeltElements::Tensor::Index;
using FeltElements::Tensor::Vector;
std::array<std::string, value.dimension(0)> is{};
std::array<std::string, value.dimension(1)> js{};
std::array<std::string, value.dimension(2)> ks{};
for (Index i = 0; i < value.dimension(0); i++)
{
for (Index j = 0; j < value.dimension(1); j++)
{
using FeltElements::Tensor::Func::all;
using Vec = Vector<value.dimension(2)>;
Vec const & vec = value(i, j, all);
js[j] = join(
boost::make_iterator_range(vec.data(), vec.data() + Vec::size()) |
boost::adaptors::transformed(to_string),
", ");
}
is[i] = join(js, "},\n\t{");
}
os << "{\n\t{" << join(is, "}\n}, {\n\t{") << "}\n}\n";
return os;
}
template <std::size_t dim0, std::size_t dim1>
std::ostream & operator<<(std::ostream & os, FeltElements::Tensor::Matrix<dim0, dim1> value)
{
using boost::algorithm::join;
using FeltElements::Tensor::Func::all;
using FeltElements::Tensor::Index;
std::array<std::string, value.dimension(0)> is{};
for (Index i = 0; i < value.dimension(0); i++)
{
using Vec = FeltElements::Tensor::Vector<value.dimension(1)>;
Vec const & vec = value(i, all);
is[i] = join(
boost::make_iterator_range(vec.data(), vec.data() + Vec::size()) |
boost::adaptors::transformed(to_string),
", ");
}
os << "{\n\t{" << join(is, "},\n\t{") << "}\n}";
return os;
}
} // namespace Fastor
inline std::ostream & operator<<(
std::ostream & os, std::vector<OpenVolumeMesh::VertexHandle> const & vtxhs)
{
using boost::adaptors::transformed;
using boost::algorithm::join;
constexpr auto to_idx = [](auto const & vtxh) { return vtxh.idx(); };
os << join(vtxhs | transformed(to_idx) | transformed(to_string), ", ") << "\n";
return os;
}
inline std::ostream & operator<<(std::ostream & os, FeltElements::Vtx const & vtx)
{
os << fmt::format("{{{}, {}, {}}}", vtx[0], vtx[1], vtx[2]);
return os;
}
template <std::size_t N>
inline std::ostream & operator<<(std::ostream & os, FeltElements::Tensor::Vector<N> const & pos)
{
const std::string elems = boost::algorithm::join(
boost::irange(N) |
boost::adaptors::transformed([&pos](auto i) { return fmt::format("{:.5}", pos(i)); }),
", ");
os << fmt::format("{{{}}}", elems);
return os;
}
| 29.867647 | 97 | 0.625062 | [
"vector"
] |
c96b4b83a7bf71dff6c4389fa44002f061d6b808 | 4,959 | cc | C++ | mindspore/lite/tools/benchmark/nnie/src/custom_infer.cc | wsjlovecode/mindspore | 0b5ad5318041172c1e1d825343d496100a4ae2dc | [
"Apache-2.0"
] | null | null | null | mindspore/lite/tools/benchmark/nnie/src/custom_infer.cc | wsjlovecode/mindspore | 0b5ad5318041172c1e1d825343d496100a4ae2dc | [
"Apache-2.0"
] | null | null | null | mindspore/lite/tools/benchmark/nnie/src/custom_infer.cc | wsjlovecode/mindspore | 0b5ad5318041172c1e1d825343d496100a4ae2dc | [
"Apache-2.0"
] | null | null | null | /**
* Copyright 2021 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 "src/custom_infer.h"
#include <string>
#include <iostream>
#include "include/errorcode.h"
#include "src/nnie_print.h"
#include "include/api/format.h"
#include "include/registry/register_kernel_interface.h"
using mindspore::kernel::KernelInterface;
using mindspore::lite::RET_ERROR;
using mindspore::lite::RET_OK;
using mindspore::schema::PrimitiveType_Custom;
namespace mindspore {
namespace nnie {
std::shared_ptr<KernelInterface> CustomInferCreater() {
auto infer = new (std::nothrow) CustomInterface();
if (infer == nullptr) {
LOGE("new custom infer is nullptr");
return nullptr;
}
return std::shared_ptr<KernelInterface>(infer);
}
int GetCustomShape(const mindspore::schema::Custom *op, const std::string &attr,
std::vector<std::vector<int64_t>> *shapes) {
char buf[kMaxSize];
bool has_outputs_shape = false;
for (size_t i = 0; i < op->attr()->size(); i++) {
if (op->attr()->Get(i)->name()->str() == attr) {
auto output_info = op->attr()->Get(i)->data();
int attr_size = static_cast<int>(output_info->size());
if (attr_size >= kMaxSize) {
LOGE("attr size too big");
return RET_ERROR;
}
for (int j = 0; j < attr_size; j++) {
buf[j] = static_cast<char>(output_info->Get(j));
}
buf[attr_size] = 0;
has_outputs_shape = true;
break;
}
}
if (!has_outputs_shape) {
LOGE("Custom op don't have %s attr.", attr.c_str());
return RET_ERROR;
}
char delims[] = ",";
char *res = nullptr;
char *save_ptr = nullptr;
res = strtok_r(buf, delims, &save_ptr);
while (res != nullptr) {
// 待补完
// outputs[id]->format_ = input->format_;
// outputs[id]->data_type_ = kNumberTypeFloat32;
int64_t ndims = strtol(res, &res, kDecimal);
int j = 0;
std::vector<int64_t> shape;
shape.resize(ndims);
for (; j < ndims; j++) {
res = strtok_r(NULL, delims, &save_ptr);
shape[j] = static_cast<int64_t>(strtol(res, &res, kDecimal));
}
shapes->push_back(shape);
res = strtok_r(NULL, delims, &save_ptr);
}
return RET_OK;
}
Status CustomInterface::Infer(std::vector<mindspore::MSTensor> *inputs, std::vector<mindspore::MSTensor> *outputs,
const mindspore::schema::Primitive *primitive) {
if (inputs->empty()) {
LOGE("Inputs size 0");
return kLiteError;
}
if (outputs->empty()) {
LOGE("Outputs size 0");
return kLiteError;
}
if (primitive->value_type() != mindspore::schema::PrimitiveType_Custom) {
LOGE("Primitive type is not PrimitiveType_Custom");
return kLiteError;
}
auto op = primitive->value_as_Custom();
if (op->attr()->size() < 1) {
LOGE("There are at least 1 attribute of Custom");
return kLiteError;
}
std::vector<std::vector<int64_t>> inputs_shape;
if (GetCustomShape(op, "inputs_shape", &inputs_shape) != RET_OK) {
LOGE("parser inputs_shape attribute err.");
return kLiteError;
}
std::vector<std::vector<int64_t>> outputs_shape;
if (GetCustomShape(op, "outputs_shape", &outputs_shape) != RET_OK) {
LOGE("parser outputs_shape attribute err.");
return kLiteError;
}
if (inputs_shape.size() != (inputs->size() - 1)) {
LOGE("inputs num diff inputs_shape num.");
return kLiteError;
}
if (inputs_shape[0].size() != (*inputs)[0].Shape().size()) {
LOGE("shape size err.");
return kLiteError;
}
bool resize_flag = false;
int resize_num = 1;
for (size_t i = 0; i < inputs_shape[0].size(); i++) {
if (inputs_shape[0][i] != (*inputs)[0].Shape()[i]) {
if (i == 0) {
resize_flag = true;
resize_num = (*inputs)[0].Shape()[i];
} else {
LOGE("Custom of NNIE only support batch_num resize.");
return kLiteError;
}
}
}
if (resize_flag) {
for (auto &output_shape : outputs_shape) {
output_shape[0] = resize_num;
}
}
for (size_t i = 0; i < outputs->size(); i++) {
(*outputs)[i].SetShape(outputs_shape[i]);
(*outputs)[i].SetDataType(DataType::kNumberTypeFloat32);
(*outputs)[i].SetFormat(Format::NCHW);
}
return kSuccess;
}
} // namespace nnie
} // namespace mindspore
namespace mindspore {
namespace kernel {
REGISTER_CUSTOM_KERNEL_INTERFACE(NNIE, NNIE, nnie::CustomInferCreater);
} // namespace kernel
} // namespace mindspore
| 30.801242 | 114 | 0.64509 | [
"shape",
"vector"
] |
c981119688cfd11698931df5a4eae655ad90a14c | 1,913 | hpp | C++ | include/codegen/include/GlobalNamespace/OnRenderImageTest.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 1 | 2021-11-12T09:29:31.000Z | 2021-11-12T09:29:31.000Z | include/codegen/include/GlobalNamespace/OnRenderImageTest.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | null | null | null | include/codegen/include/GlobalNamespace/OnRenderImageTest.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 2 | 2021-10-03T02:14:20.000Z | 2021-11-12T09:29:36.000Z | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
#pragma pack(push, 8)
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
// Including type: UnityEngine.MonoBehaviour
#include "UnityEngine/MonoBehaviour.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: UnityEngine
namespace UnityEngine {
// Forward declaring type: RenderTexture
class RenderTexture;
// Forward declaring type: Material
class Material;
}
// Completed forward declares
// Type namespace:
namespace GlobalNamespace {
// Autogenerated type: OnRenderImageTest
class OnRenderImageTest : public UnityEngine::MonoBehaviour {
public:
// private UnityEngine.RenderTexture _rt
// Offset: 0x18
UnityEngine::RenderTexture* rt;
// private UnityEngine.Material _stereoCopyMaterial
// Offset: 0x20
UnityEngine::Material* stereoCopyMaterial;
// private System.Void Start()
// Offset: 0xC3E150
void Start();
// private System.Void OnRenderImage(UnityEngine.RenderTexture source, UnityEngine.RenderTexture destination)
// Offset: 0xC3E234
void OnRenderImage(UnityEngine::RenderTexture* source, UnityEngine::RenderTexture* destination);
// public System.Void .ctor()
// Offset: 0xC3E2D0
// Implemented from: UnityEngine.MonoBehaviour
// Base method: System.Void MonoBehaviour::.ctor()
// Base method: System.Void Behaviour::.ctor()
// Base method: System.Void Component::.ctor()
// Base method: System.Void Object::.ctor()
// Base method: System.Void Object::.ctor()
static OnRenderImageTest* New_ctor();
}; // OnRenderImageTest
}
#include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::OnRenderImageTest*, "", "OnRenderImageTest");
#pragma pack(pop)
| 37.509804 | 113 | 0.711448 | [
"object"
] |
c984aee592d96f7520c945def5be8d458dab800e | 12,758 | cpp | C++ | src/Compiler/Parser/Expr.cpp | BenjaminNavarro/Feral | 579411c36a1cc66f96fcda1b82e3259e22022ac2 | [
"BSD-3-Clause"
] | null | null | null | src/Compiler/Parser/Expr.cpp | BenjaminNavarro/Feral | 579411c36a1cc66f96fcda1b82e3259e22022ac2 | [
"BSD-3-Clause"
] | null | null | null | src/Compiler/Parser/Expr.cpp | BenjaminNavarro/Feral | 579411c36a1cc66f96fcda1b82e3259e22022ac2 | [
"BSD-3-Clause"
] | null | null | null | /*
Copyright (c) 2020, Electrux
All rights reserved.
Using the BSD 3-Clause license for the project,
main LICENSE file resides in project's root directory.
Please read that file and understand the license terms
before using or altering the project.
*/
#include "Internal.hpp"
Errors parse_expr_cols( phelper_t & ph, stmt_base_t * & loc )
{
if( parse_expr( ph, loc ) != E_OK ) {
goto fail;
}
if( !ph.accept( TOK_COLS ) ) {
ph.fail( "expected semicolon at the end of expression, found: '%s'",
TokStrs[ ph.peakt() ] );
goto fail;
}
ph.next();
return E_OK;
fail:
if( loc ) delete loc;
return E_PARSE_FAIL;
}
Errors parse_expr( phelper_t & ph, stmt_base_t * & loc )
{
return parse_expr_16( ph, loc );
}
// Left Associative
// ,
Errors parse_expr_16( phelper_t & ph, stmt_base_t * & loc )
{
stmt_base_t * lhs = nullptr, * rhs = nullptr;
const lex::tok_t * oper = nullptr;
size_t idx = ph.peak()->pos;
size_t commas = 0;
if( parse_expr_15( ph, rhs ) != E_OK ) {
goto fail;
}
while( ph.accept( TOK_COMMA ) ) {
++commas;
idx = ph.peak()->pos;
oper = ph.peak();
ph.next();
if( parse_expr_15( ph, lhs ) != E_OK ) {
goto fail;
}
rhs = new stmt_expr_t( lhs, oper, rhs, idx );
lhs = nullptr;
}
if( rhs->type() == GT_EXPR ) {
static_cast< stmt_expr_t * >( rhs )->commas_set( commas );
}
loc = rhs;
return E_OK;
fail:
if( lhs ) delete lhs;
if( rhs ) delete rhs;
return E_PARSE_FAIL;
}
// Right Associative
// =
Errors parse_expr_15( phelper_t & ph, stmt_base_t * & loc )
{
stmt_base_t * lhs = nullptr, * rhs = nullptr;
const lex::tok_t * oper = nullptr;
size_t idx = ph.peak()->pos;
if( parse_expr_14( ph, rhs ) != E_OK ) {
goto fail;
}
while( ph.accept( TOK_ASSN ) ) {
idx = ph.peak()->pos;
oper = ph.peak();
ph.next();
if( parse_expr_14( ph, lhs ) != E_OK ) {
goto fail;
}
rhs = new stmt_expr_t( lhs, oper, rhs, idx );
lhs = nullptr;
}
loc = rhs;
return E_OK;
fail:
if( lhs ) delete lhs;
if( rhs ) delete rhs;
return E_PARSE_FAIL;
}
// Left Associative
// += -=
// *= /= %=
// <<= >>=
// &= |= ^=
Errors parse_expr_14( phelper_t & ph, stmt_base_t * & loc )
{
stmt_base_t * lhs = nullptr, * rhs = nullptr;
const lex::tok_t * oper = nullptr;
size_t idx = ph.peak()->pos;
if( parse_expr_13( ph, lhs ) != E_OK ) {
goto fail;
}
while( ph.accept( TOK_ADD_ASSN, TOK_SUB_ASSN ) ||
ph.accept( TOK_MUL_ASSN, TOK_DIV_ASSN, TOK_MOD_ASSN ) ||
ph.accept( TOK_LSHIFT_ASSN, TOK_RSHIFT_ASSN, TOK_BAND_ASSN ) ||
ph.accept( TOK_BOR_ASSN, TOK_BXOR_ASSN ) ) {
idx = ph.peak()->pos;
oper = ph.peak();
ph.next();
if( parse_expr_13( ph, rhs ) != E_OK ) {
goto fail;
}
lhs = new stmt_expr_t( lhs, oper, rhs, idx );
rhs = nullptr;
}
loc = lhs;
return E_OK;
fail:
if( lhs ) delete lhs;
if( rhs ) delete rhs;
return E_PARSE_FAIL;
}
// Left Associative
// ||
Errors parse_expr_13( phelper_t & ph, stmt_base_t * & loc )
{
stmt_base_t * lhs = nullptr, * rhs = nullptr;
const lex::tok_t * oper = nullptr;
size_t idx = ph.peak()->pos;
if( parse_expr_12( ph, lhs ) != E_OK ) {
goto fail;
}
while( ph.accept( TOK_OR ) ) {
idx = ph.peak()->pos;
oper = ph.peak();
ph.next();
if( parse_expr_12( ph, rhs ) != E_OK ) {
goto fail;
}
lhs = new stmt_expr_t( lhs, oper, rhs, idx );
rhs = nullptr;
}
loc = lhs;
return E_OK;
fail:
if( lhs ) delete lhs;
if( rhs ) delete rhs;
return E_PARSE_FAIL;
}
// Left Associative
// &&
Errors parse_expr_12( phelper_t & ph, stmt_base_t * & loc )
{
stmt_base_t * lhs = nullptr, * rhs = nullptr;
const lex::tok_t * oper = nullptr;
size_t idx = ph.peak()->pos;
if( parse_expr_11( ph, lhs ) != E_OK ) {
goto fail;
}
while( ph.accept( TOK_AND ) ) {
idx = ph.peak()->pos;
oper = ph.peak();
ph.next();
if( parse_expr_11( ph, rhs ) != E_OK ) {
goto fail;
}
lhs = new stmt_expr_t( lhs, oper, rhs, idx );
rhs = nullptr;
}
loc = lhs;
return E_OK;
fail:
if( lhs ) delete lhs;
if( rhs ) delete rhs;
return E_PARSE_FAIL;
}
// Left Associative
// |
Errors parse_expr_11( phelper_t & ph, stmt_base_t * & loc )
{
stmt_base_t * lhs = nullptr, * rhs = nullptr;
const lex::tok_t * oper = nullptr;
size_t idx = ph.peak()->pos;
if( parse_expr_10( ph, lhs ) != E_OK ) {
goto fail;
}
while( ph.accept( TOK_BOR ) ) {
idx = ph.peak()->pos;
oper = ph.peak();
ph.next();
if( parse_expr_10( ph, rhs ) != E_OK ) {
goto fail;
}
lhs = new stmt_expr_t( lhs, oper, rhs, idx );
rhs = nullptr;
}
loc = lhs;
return E_OK;
fail:
if( lhs ) delete lhs;
if( rhs ) delete rhs;
return E_PARSE_FAIL;
}
// Left Associative
// ^
Errors parse_expr_10( phelper_t & ph, stmt_base_t * & loc )
{
stmt_base_t * lhs = nullptr, * rhs = nullptr;
const lex::tok_t * oper = nullptr;
size_t idx = ph.peak()->pos;
if( parse_expr_09( ph, lhs ) != E_OK ) {
goto fail;
}
while( ph.accept( TOK_BXOR ) ) {
idx = ph.peak()->pos;
oper = ph.peak();
ph.next();
if( parse_expr_09( ph, rhs ) != E_OK ) {
goto fail;
}
lhs = new stmt_expr_t( lhs, oper, rhs, idx );
rhs = nullptr;
}
loc = lhs;
return E_OK;
fail:
if( lhs ) delete lhs;
if( rhs ) delete rhs;
return E_PARSE_FAIL;
}
// Left Associative
// &
Errors parse_expr_09( phelper_t & ph, stmt_base_t * & loc )
{
stmt_base_t * lhs = nullptr, * rhs = nullptr;
const lex::tok_t * oper = nullptr;
size_t idx = ph.peak()->pos;
if( parse_expr_08( ph, lhs ) != E_OK ) {
goto fail;
}
while( ph.accept( TOK_BAND ) ) {
idx = ph.peak()->pos;
oper = ph.peak();
ph.next();
if( parse_expr_08( ph, rhs ) != E_OK ) {
goto fail;
}
lhs = new stmt_expr_t( lhs, oper, rhs, idx );
rhs = nullptr;
}
loc = lhs;
return E_OK;
fail:
if( lhs ) delete lhs;
if( rhs ) delete rhs;
return E_PARSE_FAIL;
}
// Left Associative
// == !=
Errors parse_expr_08( phelper_t & ph, stmt_base_t * & loc )
{
stmt_base_t * lhs = nullptr, * rhs = nullptr;
const lex::tok_t * oper = nullptr;
size_t idx = ph.peak()->pos;
if( parse_expr_07( ph, lhs ) != E_OK ) {
goto fail;
}
while( ph.accept( TOK_EQ, TOK_NE ) ) {
idx = ph.peak()->pos;
oper = ph.peak();
ph.next();
if( parse_expr_07( ph, rhs ) != E_OK ) {
goto fail;
}
lhs = new stmt_expr_t( lhs, oper, rhs, idx );
rhs = nullptr;
}
loc = lhs;
return E_OK;
fail:
if( lhs ) delete lhs;
if( rhs ) delete rhs;
return E_PARSE_FAIL;
}
// Left Associative
// < <=
// > >=
Errors parse_expr_07( phelper_t & ph, stmt_base_t * & loc )
{
stmt_base_t * lhs = nullptr, * rhs = nullptr;
const lex::tok_t * oper = nullptr;
size_t idx = ph.peak()->pos;
if( parse_expr_06( ph, lhs ) != E_OK ) {
goto fail;
}
while( ph.accept( TOK_LT, TOK_LE ) ||
ph.accept( TOK_GT, TOK_GE ) ) {
idx = ph.peak()->pos;
oper = ph.peak();
ph.next();
if( parse_expr_06( ph, rhs ) != E_OK ) {
goto fail;
}
lhs = new stmt_expr_t( lhs, oper, rhs, idx );
rhs = nullptr;
}
loc = lhs;
return E_OK;
fail:
if( lhs ) delete lhs;
if( rhs ) delete rhs;
return E_PARSE_FAIL;
}
// Left Associative
// << >>
Errors parse_expr_06( phelper_t & ph, stmt_base_t * & loc )
{
stmt_base_t * lhs = nullptr, * rhs = nullptr;
const lex::tok_t * oper = nullptr;
size_t idx = ph.peak()->pos;
if( parse_expr_05( ph, lhs ) != E_OK ) {
goto fail;
}
while( ph.accept( TOK_LSHIFT, TOK_RSHIFT ) ) {
idx = ph.peak()->pos;
oper = ph.peak();
ph.next();
if( parse_expr_05( ph, rhs ) != E_OK ) {
goto fail;
}
lhs = new stmt_expr_t( lhs, oper, rhs, idx );
rhs = nullptr;
}
loc = lhs;
return E_OK;
fail:
if( lhs ) delete lhs;
if( rhs ) delete rhs;
return E_PARSE_FAIL;
}
// Left Associative
// + -
Errors parse_expr_05( phelper_t & ph, stmt_base_t * & loc )
{
stmt_base_t * lhs = nullptr, * rhs = nullptr;
const lex::tok_t * oper = nullptr;
size_t idx = ph.peak()->pos;
if( parse_expr_04( ph, lhs ) != E_OK ) {
goto fail;
}
while( ph.accept( TOK_ADD, TOK_SUB ) ) {
idx = ph.peak()->pos;
oper = ph.peak();
ph.next();
if( parse_expr_04( ph, rhs ) != E_OK ) {
goto fail;
}
lhs = new stmt_expr_t( lhs, oper, rhs, idx );
rhs = nullptr;
}
loc = lhs;
return E_OK;
fail:
if( lhs ) delete lhs;
if( rhs ) delete rhs;
return E_PARSE_FAIL;
}
// Left Associative
// / * % **
Errors parse_expr_04( phelper_t & ph, stmt_base_t * & loc )
{
stmt_base_t * lhs = nullptr, * rhs = nullptr;
const lex::tok_t * oper = nullptr;
size_t idx = ph.peak()->pos;
if( parse_expr_03( ph, lhs ) != E_OK ) {
goto fail;
}
while( ph.accept( TOK_DIV, TOK_MUL, TOK_MOD ) ||
ph.accept( TOK_POW ) ) {
idx = ph.peak()->pos;
oper = ph.peak();
ph.next();
if( parse_expr_03( ph, rhs ) != E_OK ) {
goto fail;
}
lhs = new stmt_expr_t( lhs, oper, rhs, idx );
rhs = nullptr;
}
loc = lhs;
return E_OK;
fail:
if( lhs ) delete lhs;
if( rhs ) delete rhs;
return E_PARSE_FAIL;
}
// Right Associative (single operand)
// ++ -- (pre)
// + - (unary)
// ! ~ (log/bit)
Errors parse_expr_03( phelper_t & ph, stmt_base_t * & loc )
{
stmt_base_t * lhs = nullptr;
const lex::tok_t * oper = nullptr;
std::vector< const lex::tok_t * > opers;
size_t idx = ph.peak()->pos;
// add operators in vector in reverse order
while( ph.accept( TOK_XINC, TOK_XDEC ) ||
ph.accept( TOK_ADD, TOK_SUB ) ||
ph.accept( TOK_NOT, TOK_BNOT ) ) {
if( ph.peakt() == TOK_XINC ) ph.sett( TOK_INCX );
else if( ph.peakt() == TOK_XDEC ) ph.sett( TOK_DECX );
else if( ph.peakt() == TOK_ADD ) ph.sett( TOK_UADD );
else if( ph.peakt() == TOK_SUB ) ph.sett( TOK_USUB );
opers.insert( opers.begin(), ph.peak() );
ph.next();
}
if( parse_expr_02( ph, lhs ) != E_OK ) {
goto fail;
}
for( auto & op : opers ) {
lhs = new stmt_expr_t( lhs, op, nullptr, op->pos );
}
loc = lhs;
return E_OK;
fail:
if( lhs ) delete lhs;
return E_PARSE_FAIL;
}
// Left Associative
// ++ -- (post)
Errors parse_expr_02( phelper_t & ph, stmt_base_t * & loc )
{
stmt_base_t * lhs = nullptr;
const lex::tok_t * oper = nullptr;
size_t idx = ph.peak()->pos;
if( parse_expr_01( ph, lhs ) != E_OK ) {
goto fail;
}
if( ph.accept( TOK_XINC, TOK_XDEC ) ) {
idx = ph.peak()->pos;
oper = ph.peak();
ph.next();
loc = new stmt_expr_t( lhs, oper, nullptr, idx );
return E_OK;
}
loc = lhs;
return E_OK;
fail:
if( lhs ) delete lhs;
return E_PARSE_FAIL;
}
// Left Associative
// x(FN_CALL_ARGS) y[EXPR]
// x.y
// '(' EXPR ')'
Errors parse_expr_01( phelper_t & ph, stmt_base_t * & loc )
{
stmt_base_t * lhs = nullptr, * rhs = nullptr;
const lex::tok_t * oper = nullptr;
bool is_mem_fn = false;
size_t idx = ph.peak()->pos;
if( ph.accept( TOK_LPAREN ) ) {
idx = ph.peak()->pos;
ph.next();
if( parse_expr( ph, lhs ) != E_OK ) {
goto fail;
}
if( !ph.accept( TOK_RPAREN ) ) {
ph.fail( idx, "could not find ending parenthesis for expression" );
goto fail;
}
ph.next();
goto begin_loop;
}
if( parse_term( ph, lhs ) != E_OK ) {
goto fail;
}
begin_loop:
while( ph.accept( TOK_LPAREN, TOK_LBRACK ) ||
ph.accept( TOK_DOT ) ) {
idx = ph.peak()->pos;
if( ph.accept( TOK_LPAREN ) ) {
ph.sett( is_mem_fn ? TOK_OPER_MEM_FN : TOK_OPER_FN );
is_mem_fn = false;
oper = ph.peak();
ph.next();
if( !ph.accept( TOK_RPAREN ) && parse_fn_call_args( ph, rhs ) != E_OK ) {
goto fail;
}
if( !ph.accept( TOK_RPAREN ) ) {
ph.fail( idx, "missing closing parenthesis for function call" );
goto fail;
}
ph.next();
} else if( ph.accept( TOK_LBRACK ) ) {
ph.sett( TOK_OPER_SUBS );
oper = ph.peak();
ph.next();
if( !ph.accept( TOK_RBRACK ) && parse_expr( ph, rhs ) != E_OK ) {
goto fail;
}
if( !ph.accept( TOK_RBRACK ) ) {
ph.fail( idx, "missing closing bracket for subscript expression" );
goto fail;
}
ph.next();
} else if( ph.accept( TOK_DOT ) ) {
oper = ph.peak();
ph.next();
// member function
if( ph.acceptd() && ph.peakt( 1 ) == TOK_LPAREN ) {
ph.prev();
ph.sett( TOK_OPER_MEM_FN_ATTR );
ph.next();
is_mem_fn = true;
}
if( parse_term( ph, rhs, true ) != E_OK ) {
goto fail;
}
}
lhs = new stmt_expr_t( lhs, oper, rhs, idx );
rhs = nullptr;
}
done:
loc = lhs;
return E_OK;
fail:
if( lhs ) delete lhs;
if( rhs ) delete rhs;
return E_PARSE_FAIL;
}
// Data
Errors parse_term( phelper_t & ph, stmt_base_t * & loc, const bool make_const )
{
if( ph.acceptd() ) {
if( make_const && ph.peakt() == TOK_IDEN ) ph.sett( TOK_STR );
loc = new stmt_simple_t( ph.peak() );
ph.next();
} else if( !make_const && ph.accept( TOK_FN ) ) {
if( parse_fn_decl( ph, loc ) != E_OK ) goto fail;
} else {
ph.fail( "invalid or extraneous token type '%s' received in expression", TokStrs[ ph.peakt() ] );
goto fail;
}
return E_OK;
fail:
return E_PARSE_FAIL;
}
| 20.644013 | 99 | 0.603543 | [
"vector"
] |
c98cb40871ece6c08ceec3fc5a1bebe4237013a7 | 1,068 | cpp | C++ | SearchingAndSorting/find_common_elements_in_three_sorted_arrays.cpp | xiaorancs/xr-Algorithm | 4b522b2936b986f7891756fc610917b99864c534 | [
"MIT"
] | 7 | 2017-12-11T12:42:39.000Z | 2019-11-17T15:10:26.000Z | SearchingAndSorting/find_common_elements_in_three_sorted_arrays.cpp | xiaorancs/xr-Algorithm | 4b522b2936b986f7891756fc610917b99864c534 | [
"MIT"
] | 1 | 2018-08-29T12:29:51.000Z | 2018-08-29T12:29:51.000Z | SearchingAndSorting/find_common_elements_in_three_sorted_arrays.cpp | xiaorancs/xr-Algorithm | 4b522b2936b986f7891756fc610917b99864c534 | [
"MIT"
] | 2 | 2018-01-29T08:26:30.000Z | 2018-08-10T01:30:44.000Z | /**
*Author: xiaoran
*Time: 2017-12-07 23:28
*Problem: 在三个排序数组中找到公共元素.
*
*分析:
* 合并排序中的一个比较合并,O(n1+n2+n3)
*/
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
template <class Type>
vector<Type> findCommonElements(vector<Type> a,vector<Type> b,vector<Type> c){
int n1,n2,n3,i=0,j=0,k=0;
n1 = a.size();
n2 = b.size();
n3 = c.size();
vector<Type> result;
while(i<n1 && j<n2 && k<n3){
if(a[i] == b[j] && a[i] == c[k]){
result.push_back(a[i]);
i++;
j++;
k++;
}
else if(a[i] < b[j] && a[i] < c[k]){
i++;
}
else if(b[j] < a[i] && b[j] < c[k]){
j++;
}
else if(c[k] < a[i] && c[k] < b[j]){
k++;
}
}
return result;
}
int main()
{
vector<int> a,b,c;
a.push_back(1);
a.push_back(5);
a.push_back(5);
b.push_back(3);
b.push_back(4);
b.push_back(5);
b.push_back(5);
b.push_back(10);
c.push_back(5);
c.push_back(5);
c.push_back(10);
c.push_back(20);
vector<int> ans = findCommonElements(a,b,c);
for(int i=0;i<ans.size();i++){
cout<<ans[i]<<" ";
}
cout<<endl;
return 0;
}
| 15.257143 | 78 | 0.552434 | [
"vector"
] |
c997042e964c19a4a226b100d1a3e6ff9c8d097c | 4,540 | cpp | C++ | src/utils.cpp | spolitov/cassandra-cpp-driver | 697c783f83e03cec8cd1881169d334dab42d311b | [
"Apache-2.0"
] | 4 | 2020-02-21T00:15:30.000Z | 2022-01-20T22:56:42.000Z | src/utils.cpp | spolitov/cassandra-cpp-driver | 697c783f83e03cec8cd1881169d334dab42d311b | [
"Apache-2.0"
] | 5 | 2020-10-22T16:53:03.000Z | 2021-05-19T17:29:33.000Z | src/utils.cpp | spolitov/cassandra-cpp-driver | 697c783f83e03cec8cd1881169d334dab42d311b | [
"Apache-2.0"
] | 5 | 2019-11-12T07:40:24.000Z | 2021-01-15T11:29:41.000Z | /*
Copyright (c) DataStax, 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 "utils.hpp"
#include "constants.hpp"
#include <algorithm>
#include <assert.h>
#include <functional>
#include <sstream>
#if (defined(WIN32) || defined(_WIN32))
#include <windows.h>
#else
#include <unistd.h>
#endif
namespace cass {
std::string opcode_to_string(int opcode) {
switch (opcode) {
case CQL_OPCODE_ERROR:
return "CQL_OPCODE_ERROR";
case CQL_OPCODE_STARTUP:
return "CQL_OPCODE_STARTUP";
case CQL_OPCODE_READY:
return "CQL_OPCODE_READY";
case CQL_OPCODE_AUTHENTICATE:
return "CQL_OPCODE_AUTHENTICATE";
case CQL_OPCODE_CREDENTIALS:
return "CQL_OPCODE_CREDENTIALS";
case CQL_OPCODE_OPTIONS:
return "CQL_OPCODE_OPTIONS";
case CQL_OPCODE_SUPPORTED:
return "CQL_OPCODE_SUPPORTED";
case CQL_OPCODE_QUERY:
return "CQL_OPCODE_QUERY";
case CQL_OPCODE_RESULT:
return "CQL_OPCODE_RESULT";
case CQL_OPCODE_PREPARE:
return "CQL_OPCODE_PREPARE";
case CQL_OPCODE_EXECUTE:
return "CQL_OPCODE_EXECUTE";
case CQL_OPCODE_REGISTER:
return "CQL_OPCODE_REGISTER";
case CQL_OPCODE_EVENT:
return "CQL_OPCODE_EVENT";
case CQL_OPCODE_BATCH:
return "CQL_OPCODE_BATCH";
case CQL_OPCODE_AUTH_CHALLENGE:
return "CQL_OPCODE_AUTH_CHALLENGE";
case CQL_OPCODE_AUTH_RESPONSE:
return "CQL_OPCODE_AUTH_RESPONSE";
case CQL_OPCODE_AUTH_SUCCESS:
return "CQL_OPCODE_AUTH_SUCCESS";
};
assert(false);
return "";
}
void explode(const std::string& str, std::vector<std::string>& vec, const char delimiter /* = ',' */) {
std::istringstream stream(str);
while (!stream.eof()) {
std::string token;
std::getline(stream, token, delimiter);
if (!trim(token).empty()) {
vec.push_back(token);
}
}
}
std::string& trim(std::string& str) {
// Trim front
str.erase(str.begin(),
std::find_if(str.begin(), str.end(),
std::not1(std::ptr_fun<int, int>(::isspace))));
// Trim back
str.erase(std::find_if(str.rbegin(), str.rend(),
std::not1(std::ptr_fun<int, int>(::isspace))).base(),
str.end());
return str;
}
static bool is_word_char(int c) {
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
(c >= '0' && c <= '9') || c == '_';
}
static bool is_lower_word_char(int c) {
return (c >= 'a' && c <= 'z') ||
(c >= '0' && c <= '9') || c == '_';
}
bool is_valid_cql_id(const std::string& str) {
for (std::string::const_iterator i = str.begin(),
end = str.end(); i != end; ++i) {
if (!is_word_char(*i)) {
return false;
}
}
return true;
}
bool is_valid_lower_cql_id(const std::string& str) {
if (str.empty() || !is_lower_word_char(str[0])) {
return false;
}
if (str.size() > 1) {
for (std::string::const_iterator i = str.begin() + 1,
end = str.end(); i != end; ++i) {
if (!is_lower_word_char(*i)) {
return false;
}
}
}
return true;
}
std::string& quote_id(std::string& str) {
std::string temp(str);
str.clear();
str.push_back('"');
for (std::string::const_iterator i = temp.begin(),
end = temp.end(); i != end; ++i) {
if (*i == '"') {
str.push_back('"');
str.push_back('"');
} else {
str.push_back(*i);
}
}
str.push_back('"');
return str;
}
std::string& escape_id(std::string& str) {
return is_valid_lower_cql_id(str) ? str : quote_id(str);
}
std::string& to_cql_id(std::string& str) {
if (is_valid_cql_id(str)) {
std::transform(str.begin(), str.end(), str.begin(), tolower);
return str;
}
if (str.length() > 2 && str[0] == '"' && str[str.length() - 1] == '"') {
return str.erase(str.length() - 1, 1).erase(0, 1);
}
return str;
}
int32_t get_pid()
{
#if (defined(WIN32) || defined(_WIN32))
return static_cast<int32_t>(GetCurrentProcessId());
#else
return static_cast<int32_t>(getpid());
#endif
}
} // namespace cass
| 25.795455 | 103 | 0.624229 | [
"vector",
"transform"
] |
c997df903aecc75ddf4e1b56a8f4a6958bc042bd | 3,513 | cpp | C++ | hardware-control/TDD/transducers.cpp | julian-becker/hardware-control | 183844c4807c4360c467bf10c2e2ed47f8d7aa75 | [
"MIT"
] | null | null | null | hardware-control/TDD/transducers.cpp | julian-becker/hardware-control | 183844c4807c4360c467bf10c2e2ed47f8d7aa75 | [
"MIT"
] | null | null | null | hardware-control/TDD/transducers.cpp | julian-becker/hardware-control | 183844c4807c4360c467bf10c2e2ed47f8d7aa75 | [
"MIT"
] | null | null | null | //
// transducers.cpp
// hardware-control
//
// Created by Julian Becker on 19.01.16.
// Copyright (c) 2016 Julian Becker. All rights reserved.
//
#include "transducers.h"
#include <catch.h>
#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
#include <streambuf>
#include <sstream>
#include <map>
struct state {
std::vector<int> stack;
std::map<std::string,std::function<void(state&,std::istream&)>> dict;
};
template <typename T>
void tryParse(state& s, std::istream& istr, std::function<T(std::istream&)> parse, std::function<void(state&,T)> action);
template <>
void tryParse(state& s, std::istream& istr, std::function<int(std::istream&)> parse, std::function<void(state&,int)> action) {
auto pos = istr.tellg();
try {
auto val = parse(istr);
action(s,val);
}
catch(...) {
istr.clear();
istr.seekg(pos);
}
}
std::vector<int> forth(state& s, std::istream& istr) {
auto pos = istr.tellg();
std::string token;
if(istr >> token) {
std::istringstream str(token);
int num;
if(str >> num) {
s.stack.push_back(num);
return forth(s,istr);
}
if(s.dict.count(token)) {
s.dict.at(token)(s,istr);
return forth(s,istr);
}
}
return s.stack;
}
TEST_CASE("transducers") {
state s{};
s.dict["+"] = [](state& s, std::istream& istr) {
auto a = s.stack.back(); s.stack.pop_back();
auto b = s.stack.back(); s.stack.pop_back();
s.stack.push_back(a+b);
};
s.dict["-"] = [](state& s, std::istream& istr) {
auto a = s.stack.back(); s.stack.pop_back();
auto b = s.stack.back(); s.stack.pop_back();
s.stack.push_back(b-a);
};
s.dict[":"] = [](state& s, std::istream& istr) {
std::string wordname;
auto pos = istr.tellg();
try {
if(istr >> wordname) {
struct mybuf : public std::streambuf {};
char buf[100u];
istr.get(buf,sizeof(buf),';');
char _;
istr.get(_);
std::string def(buf);
s.dict[wordname] = [def](state& s, std::istream& istr1) {
std::istringstream defstr(def);
forth(s,defstr);
};
}
}
catch(...) {
istr.seekg(pos);
throw;
}
};
SECTION("0") {
std::istringstream stream("0");
CHECK(forth(s, stream) == std::vector<int>{0});
}
SECTION("1") {
std::istringstream stream("1");
CHECK(forth(s, stream) == std::vector<int>{1});
}
SECTION("1 2") {
std::istringstream stream("1 2");
CHECK(forth(s, stream) == std::vector<int>({1, 2}));
}
SECTION("1 2 +") {
std::istringstream stream("1 2 +");
CHECK(forth(s, stream) == std::vector<int>({3}));
}
SECTION("10 2 - 100 +") {
std::istringstream stream("10 2 - 100 +");
CHECK(forth(s, stream) == std::vector<int>({108}));
}
SECTION(": plus6 1 + 5 + ; 3 plus6") {
std::istringstream stream(": plus6 1 + 5 + ; 3 plus6");
CHECK(forth(s, stream) == std::vector<int>({9}));
}
auto enumerate = [](auto step) {
return [step,n=0](auto s, auto...ins) mutable {
return step(s, n++, ins...);
};
};
} | 25.830882 | 126 | 0.498434 | [
"vector"
] |
c99b6c2b0a9dc7094dcec79cf39d02eae68d0854 | 8,905 | cpp | C++ | src/test_example/safeactionselectortestclass.cpp | bbouvrie/jenkins-experimentation | ea64d8401b2cdcbfa4baa9fc67bf62f4a6862e72 | [
"MIT"
] | null | null | null | src/test_example/safeactionselectortestclass.cpp | bbouvrie/jenkins-experimentation | ea64d8401b2cdcbfa4baa9fc67bf62f4a6862e72 | [
"MIT"
] | null | null | null | src/test_example/safeactionselectortestclass.cpp | bbouvrie/jenkins-experimentation | ea64d8401b2cdcbfa4baa9fc67bf62f4a6862e72 | [
"MIT"
] | null | null | null | #include "safeactionselectortestclass.h"
#include "goofgamestate.h"
#include "public_define.h"
#include "DecisionMaker/safeactionselector.h"
#include <vector>
void SafeActionSelectorTestClass::GivenEmptyFieldWhenCallingGetActionVectorThenShouldGetAllActions()
{
// Given
FieldLayout layout = {3,3};
GoofGameState myGameState = GoofGameState(layout); // initialize playing field
Location myLoc = {1,1}; myGameState.addMe(myLoc, 1);
// When
SafeActionSelector SA = SafeActionSelector();
std::vector<ActionType> selectedActions = SA.GetActionVector(myGameState);
std::vector<ActionType> controlVector = {ActionType::Up, ActionType::Down, ActionType::Left,ActionType::Right,ActionType::Hold, ActionType::Bomb};
// Then
bool correctVectorReturned = selectedActions == controlVector;
QVERIFY2(correctVectorReturned, "Not all actions returned at empty field");
}
void SafeActionSelectorTestClass::GivenMiniFieldWhenCallingGetActionVectorThenShouldGetHold()
{
// Given
FieldLayout layout = {1,1};
GoofGameState myGameState = GoofGameState(layout); // initialize playing field
Location myLoc = {0,0}; myGameState.addMe(myLoc, 1);
// When
SafeActionSelector SA = SafeActionSelector();
std::vector<ActionType> selectedActions = SA.GetActionVector(myGameState);
std::vector<ActionType> controlVector = {ActionType::Hold};
// Then
bool correctVectorReturned = selectedActions == controlVector;
QVERIFY2(correctVectorReturned, "Not only hold returned at 1 by 1 field");
}
void SafeActionSelectorTestClass::GivenMiniFieldWithWallsWhenCallingGetActionVectorThenShouldGetDownHoldBomb()
{
// Given
FieldLayout layout = {3,3};
GoofGameState myGameState = GoofGameState(layout); // initialize playing field
Location myLoc = {1,1}; myGameState.addMe(myLoc, 1);
Location wallLoc1 = {0,0}; myGameState.addWall(wallLoc1);
Location wallLoc2 = {1,0}; myGameState.addWall(wallLoc2);
Location wallLoc3 = {2,0}; myGameState.addWall(wallLoc3);
Location wallLoc4 = {0,1}; myGameState.addWall(wallLoc4);
Location wallLoc5 = {2,1}; myGameState.addWall(wallLoc5);
Location wallLoc6 = {0,2}; myGameState.addWall(wallLoc6);
// When
SafeActionSelector SA = SafeActionSelector();
std::vector<ActionType> selectedActions = SA.GetActionVector(myGameState);
std::vector<ActionType> controlVector = {ActionType::Down,ActionType::Hold, ActionType::Bomb};
// Then
bool correctVectorReturned = selectedActions == controlVector;
QVERIFY2(correctVectorReturned, "Not down, hold, bomb, returned at small field with walls");
}
void SafeActionSelectorTestClass::GivenFieldWithBombsWhenCallingGetActionVectorThenCheckAction()
{
// Given
FieldLayout layout = {4,2};
GoofGameState myGameState = GoofGameState(layout); // initialize playing field
Location myLoc = {2,1}; myGameState.addMe(myLoc, 1);
Location bombLoc1 = {1,0}; myGameState.addBomb(bombLoc1, 1);
Location bombLoc2 = {3,1}; myGameState.addBomb(bombLoc2, 3);
Location wallLoc1 = {0,0}; myGameState.addWall(wallLoc1);
Location wallLoc2 = {2,0}; myGameState.addWall(wallLoc2);
Location wallLoc3 = {3,0}; myGameState.addWall(wallLoc3);
// When
SafeActionSelector SA = SafeActionSelector();
std::vector<ActionType> selectedActions = SA.GetActionVector(myGameState);
std::vector<ActionType> controlVector = {ActionType::Hold, ActionType::Bomb};
// Then
bool correctVectorReturned = selectedActions == controlVector;
QVERIFY2(correctVectorReturned, "Not hold, bomb, returned at small field with bombs");
}
void SafeActionSelectorTestClass::GivenFieldWithBombsAndNoSafetyWhenCallingGetActionVectorThenCheckAction()
{
// Given
FieldLayout layout = {4,2};
GoofGameState myGameState = GoofGameState(layout); // initialize playing field
Location myLoc = {2,1}; myGameState.addMe(myLoc, 1);
Location bombLoc1 = {1,0}; myGameState.addBomb(bombLoc1, 1);
Location bombLoc2 = {3,1}; myGameState.addBomb(bombLoc2, 2);
Location wallLoc1 = {0,0}; myGameState.addWall(wallLoc1);
Location wallLoc2 = {2,0}; myGameState.addWall(wallLoc2);
Location wallLoc3 = {3,0}; myGameState.addWall(wallLoc3);
// When
SafeActionSelector SA = SafeActionSelector();
std::vector<ActionType> selectedActions = SA.GetActionVector(myGameState);
std::vector<ActionType> controlVector = { };
// Then
bool correctVectorReturned = selectedActions == controlVector;
QVERIFY2(correctVectorReturned, "Not empty vector returned when there is no safety");
}
void SafeActionSelectorTestClass::GivenSmallFieldWithOpponentWhenCallingGetActionVectorLockInSafeThenCheckAction()
{
// Given
FieldLayout layout = {4,3};
GoofGameState myGameState = GoofGameState(layout); // initialize playing field
Location myLoc = {1,1}; myGameState.addMe(myLoc, 1);
Location OppLoc = {1,2}; myGameState.addOpponent(OppLoc, 1);
Location wallLoc1 = {0,0}; myGameState.addWall(wallLoc1);
Location wallLoc2 = {2,0}; myGameState.addWall(wallLoc2);
Location wallLoc3 = {0,2}; myGameState.addWall(wallLoc3);
Location wallLoc4 = {2,2}; myGameState.addWall(wallLoc4);
Location wallLoc5 = {3,2}; myGameState.addWall(wallLoc5);
// When
SafeActionSelector SA = SafeActionSelector();
std::vector<ActionType> selectedActions = SA.GetActionVectorLockInSafe(myGameState);
std::vector<ActionType> controlVector = {ActionType::Up, ActionType::Down, ActionType::Left,ActionType::Right,ActionType::Hold};
// in this case, placing a bomb is not safe (the opponent is able to put a bomb at 3,1 so that both will die
// Then
bool correctVectorReturned = selectedActions == controlVector;
QVERIFY2(correctVectorReturned, "Not empty vector returned when there is no safety");
}
void SafeActionSelectorTestClass::GivenSmallFieldWithOpponentAndSolidifierWhenCallingGetActionVectorLockInSafeThenCheckAction()
{
// Given
FieldLayout layout = {3,2};
GoofGameState myGameState = GoofGameState(layout); // initialize playing field
Location myLoc = {2,1}; myGameState.addMe(myLoc, 1);
Location OppLoc = {1,1}; myGameState.addOpponent(OppLoc, 1);
Location wallLoc1 = {0,0}; myGameState.addWall(wallLoc1);
Location wallLoc2 = {2,0}; myGameState.addWall(wallLoc2);
Location solLoc1 = {2,0}; myGameState.addSolidifier(solLoc1,2);
// When
SafeActionSelector SA = SafeActionSelector();
std::vector<ActionType> selectedActions = SA.GetActionVectorLockInSafe(myGameState);
std::vector<ActionType> controlVector = { };
// in this case, there is no safety w.r.t. lock in)
bool correctVectorReturned = selectedActions == controlVector;
QVERIFY2(correctVectorReturned, "Not empty vector returned when there is no lock-in safety");
}
void SafeActionSelectorTestClass::GivenSmallFieldWithTwoOpponentWhenCallingGetActionVectorLockInSafeThenCheckAction()
{
// Given
FieldLayout layout = {5,5};
GoofGameState myGameState = GoofGameState(layout); // initialize playing field
Location myLoc = {2,3}; myGameState.addMe(myLoc, 1);
Location OppLoc = {2,3}; myGameState.addOpponent(OppLoc, 1);
Location OppLoc2 = {2,1}; myGameState.addOpponent(OppLoc2, 1);
Location wallLoc1 = {1,2}; myGameState.addWall(wallLoc1);
Location wallLoc2 = {3,2}; myGameState.addWall(wallLoc2);
// When
SafeActionSelector SA = SafeActionSelector();
std::vector<ActionType> selectedActions = SA.GetActionVectorLockInSafe(myGameState);
std::vector<ActionType> controlVector = {ActionType::Down, ActionType::Left, ActionType::Right, ActionType::Hold, ActionType::Bomb};
// in this case, placing a bomb is not safe (the opponent is able to put a bomb at 3,1 so that both will die
// Then
bool correctVectorReturned = selectedActions == controlVector;
QVERIFY2(correctVectorReturned, "Bot does not consider two bots cooperating or the possiblity that two bots can place bombs");
}
void SafeActionSelectorTestClass::GivenSmallFieldWithSolidifierWhenCallingGetActionVectorLockInSafeThenCheckIfNotHold() const
{
// Given
FieldLayout layout = {2,1};
GoofGameState myGameState = GoofGameState(layout); // initialize playing field
Location myLoc = {0,0}; myGameState.addMe(myLoc, 1);
Location solLoc1 = {0,0}; myGameState.addSolidifier(solLoc1,1);
// When
SafeActionSelector SA = SafeActionSelector();
std::vector<ActionType> selectedActions = SA.GetActionVectorLockInSafe(myGameState);
std::vector<ActionType> controlVector = { ActionType::Right};
// in this case, there is no safety w.r.t. lock in)
bool correctVectorReturned = selectedActions == controlVector;
QVERIFY2(correctVectorReturned, "The safeActionsLockIn does not return right when standing on a solidfier");
}
| 49.748603 | 150 | 0.739023 | [
"vector"
] |
c99e4939f70a05b06ef35177bb10571f4dfc95ba | 2,376 | cpp | C++ | codeforces/B - 0-1 MST/Accepted.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | 1 | 2022-02-11T16:55:36.000Z | 2022-02-11T16:55:36.000Z | codeforces/B - 0-1 MST/Accepted.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | null | null | null | codeforces/B - 0-1 MST/Accepted.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | null | null | null | /****************************************************************************************
* @author: kzvd4729 created: Aug/01/2020 21:01
* solution_verdict: Accepted language: GNU C++14
* run_time: 124 ms memory_used: 75900 KB
* problem: https://codeforces.com/contest/1242/problem/B
****************************************************************************************/
#include<iostream>
#include<vector>
#include<cstring>
#include<map>
#include<bitset>
#include<assert.h>
#include<algorithm>
#include<iomanip>
#include<cmath>
#include<set>
#include<queue>
#include<unordered_map>
#include<random>
#include<chrono>
#include<stack>
#include<deque>
#define long long long
using namespace std;
const int N=1e6;
int vs[3000+2][3000+2],par[N+2];
int find(int x)
{
if(x==par[x])return x;
return par[x]=find(par[x]);
}
void solve1(int n,int m)
{
for(int i=1;i<=m;i++)
{
int u,v;cin>>u>>v;if(u>v)swap(u,v);
vs[u][v]=1;
}
for(int i=1;i<=n;i++)par[i]=i;
for(int i=1;i<=n;i++)
{
for(int j=i+1;j<=n;j++)
{
if(vs[i][j])continue;
int a=find(i),b=find(j);
if(a==b)continue;
par[a]=b;
}
}
set<int>st;
for(int i=1;i<=n;i++)st.insert(find(i));
cout<<st.size()-1<<endl;
}
set<int>st[N+2];
void solve2(int n,int m)
{
for(int i=1;i<=m;i++)
{
int u,v;cin>>u>>v;
st[u].insert(v);st[v].insert(u);
}
int mn=n,nd;
for(int i=1;i<=n;i++)
{
if(st[i].size()<mn)mn=st[i].size(),nd=i;
}
set<int>rm;
for(int i=1;i<=n;i++)rm.insert(i);
rm.erase(nd);
for(int i=1;i<=n;i++)if(st[nd].find(i)==st[nd].end())rm.erase(i);
for(int x=1;x<=n;x++)
{
if(st[nd].find(x)!=st[nd].end())continue;
vector<int>dl;
for(auto z:rm)
{
if(st[x].find(z)==st[x].end())dl.push_back(z);
}
for(auto z:dl)rm.erase(z);
}
int ans=0;
while(rm.size())
{
int b=*rm.begin();rm.erase(b);ans++;
vector<int>dl;
for(auto x:rm)
{
if(st[b].find(x)==st[b].end())dl.push_back(x);
}
for(auto x:dl)rm.erase(x);
}
cout<<ans<<endl;
}
int main()
{
ios_base::sync_with_stdio(0);cin.tie(0);
int n,m;cin>>n>>m;
if(n<=3000)solve1(n,m);
else solve2(n,m);
return 0;
} | 23.524752 | 111 | 0.481902 | [
"vector"
] |
c9a0968aced81f530884c9bbff0affd39ed38f4c | 21,392 | cpp | C++ | src/R3Graphics/p5d.cpp | ReillyBova/Global-Illumination | 9657d34bbde926e8364337020e6d28016310ee45 | [
"MIT"
] | 33 | 2019-02-24T18:57:08.000Z | 2022-02-28T09:43:19.000Z | src/R3Graphics/p5d.cpp | ReillyBova/Global-Illumination | 9657d34bbde926e8364337020e6d28016310ee45 | [
"MIT"
] | null | null | null | src/R3Graphics/p5d.cpp | ReillyBova/Global-Illumination | 9657d34bbde926e8364337020e6d28016310ee45 | [
"MIT"
] | 5 | 2020-06-09T13:56:14.000Z | 2021-12-21T09:17:39.000Z | ////////////////////////////////////////////////////////////////////////
// Include files
////////////////////////////////////////////////////////////////////////
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
#include <limits.h>
#include "p5d.h"
////////////////////////////////////////////////////////////////////////
// Material functions
////////////////////////////////////////////////////////////////////////
P5DMaterial::
P5DMaterial(P5DObject *object)
: object(object),
object_index(-1),
name(NULL),
texture_name(NULL),
color(NULL),
tcolor(NULL),
data(NULL)
{
// Insert material into object
if (object) {
this->object_index = object->NMaterials();
object->materials.push_back(this);
}
}
P5DMaterial::
~P5DMaterial(void)
{
// Delete string
if (name) free(name);
if (texture_name) free(texture_name);
if (color) free(color);
if (tcolor) free(tcolor);
}
////////////////////////////////////////////////////////////////////////
// Wall functions
////////////////////////////////////////////////////////////////////////
P5DWall::
P5DWall(P5DRoom *room)
: room(room),
room_index(-1),
x1(0),
y1(0),
x2(0),
y2(0),
w(0),
hidden(false),
idx_index(-1),
data(NULL)
{
// Insert wall into room
if (room) {
this->room_index = room->NWalls();
room->walls.push_back(this);
}
}
P5DWall::
~P5DWall(void)
{
}
void P5DWall::
Print(FILE *fp) const
{
// Resolve output file
if (!fp) fp = stdout;
// Print attributes
fprintf(fp, " Wall\n");
fprintf(fp, " w = %g\n", w);
fprintf(fp, " x1 = %g\n", x1);
fprintf(fp, " y1 = %g\n", y1);
fprintf(fp, " x2 = %g\n", x2);
fprintf(fp, " y2 = %g\n", y2);
fprintf(fp, "\n");
}
////////////////////////////////////////////////////////////////////////
// Object functions
////////////////////////////////////////////////////////////////////////
P5DObject::
P5DObject(P5DFloor *floor)
: floor(floor),
floor_index(-1),
room(NULL),
room_index(-1),
materials(),
className(NULL),
id(NULL),
x(0), y(0), z(0),
sX(1), sY(1), sZ(1),
a(0),
aframe(0),
fX(0), fY(0),
otf(0),
idx_index(-1),
data(NULL)
{
// Insert object into floor
if (floor) {
this->floor_index = floor->NObjects();
floor->objects.push_back(this);
}
}
P5DObject::
~P5DObject(void)
{
}
void P5DObject::
Print(FILE *fp) const
{
// Resolve output file
if (!fp) fp = stdout;
// Print attributes
fprintf(fp, " Object\n");
fprintf(fp, " className = %s\n", (className) ? className : "None");
fprintf(fp, " id = %s\n", (id) ? id : "None");
fprintf(fp, " x = %g\n", x);
fprintf(fp, " y = %g\n", y);
fprintf(fp, " z = %g\n", z);
fprintf(fp, " sX = %g\n", sX);
fprintf(fp, " sY = %g\n", sY);
fprintf(fp, " sZ = %g\n", sZ);
fprintf(fp, " a = %g\n", a);
fprintf(fp, " fX = %d\n", fX);
fprintf(fp, " fY = %d\n", fY);
fprintf(fp, " otf = %d\n", otf);
fprintf(fp, "\n");
}
////////////////////////////////////////////////////////////////////////
// Room functions
////////////////////////////////////////////////////////////////////////
P5DRoom::
P5DRoom(P5DFloor *floor)
: floor(floor),
floor_index(-1),
walls(),
objects(),
className(NULL),
h(0),
x(0), y(0),
sX(0), sY(0),
rtype(NULL),
texture(NULL),
otexture(NULL),
rtexture(NULL),
wtexture(NULL),
idx_index(-1),
data(NULL)
{
// Insert room into floor
if (floor) {
this->floor_index = floor->NRooms();
floor->rooms.push_back(this);
}
}
P5DRoom::
~P5DRoom(void)
{
}
void P5DRoom::
Print(FILE *fp) const
{
// Resolve output file
if (!fp) fp = stdout;
// Print attributes
fprintf(fp, " Room\n");
fprintf(fp, " className = %s\n", (className) ? className : "None");
fprintf(fp, " h = %g\n", h);
fprintf(fp, " x = %g\n", x);
fprintf(fp, " y = %g\n", y);
fprintf(fp, " sX = %g\n", sX);
fprintf(fp, " sY = %g\n", sY);
fprintf(fp, "\n");
// Print walls
for (int i = 0; i < NWalls(); i++) {
P5DWall *wall = Wall(i);
wall->Print(fp);
}
}
////////////////////////////////////////////////////////////////////////
// Floor functions
////////////////////////////////////////////////////////////////////////
P5DFloor::
P5DFloor(P5DProject *project)
: project(project),
project_index(-1),
rooms(),
objects(),
h(0),
idx_index(-1),
data(NULL)
{
// Insert floor into project
if (project) {
this->project_index = project->NFloors();
project->floors.push_back(this);
}
}
P5DFloor::
~P5DFloor(void)
{
}
void P5DFloor::
Print(FILE *fp) const
{
// Resolve output file
if (!fp) fp = stdout;
// Print attributes
fprintf(fp, " Floor\n");
fprintf(fp, " h = %g\n", h);
// Print rooms
for (int i = 0; i < NRooms(); i++) {
P5DRoom *room = Room(i);
room->Print(fp);
}
// Print objects
for (int i = 0; i < NObjects(); i++) {
P5DObject *object = Object(i);
object->Print(fp);
}
}
///////////////////////////////////////////////////////////////////////
// Project functions
////////////////////////////////////////////////////////////////////////
P5DProject::
P5DProject(void)
: name(NULL),
floors(),
data(NULL)
{
}
P5DProject::
~P5DProject(void)
{
// Delete name
if (name) free(name);
}
void P5DProject::
Print(FILE *fp) const
{
// Resolve output file
if (!fp) fp = stdout;
// Print attributes
fprintf(fp, "Project %s\n", (name) ? name : "");
// Print floors
for (int i = 0; i < NFloors(); i++) {
P5DFloor *floor = Floor(i);
floor->Print(fp);
}
}
////////////////////////////////////////////////////////////////////////
// PARSING FUNCTIONS
////////////////////////////////////////////////////////////////////////
#include "json.h"
static int
GetJsonObjectMember(Json::Value *&result, Json::Value *object, const char *str, int expected_type = 0)
{
// Check object type
if (object->type() != Json::objectValue) {
// fprintf(stderr, "P5D: not an object\n");
return 0;
}
// Check object member
if (!object->isMember(str)) {
// fprintf(stderr, "P5D object has no member named %s\n", str);
return 0;
}
// Get object member
result = &((*object)[str]);
if (result->type() == Json::nullValue) {
// fprintf(stderr, "P5D object has null member named %s\n", str);
return 0;
}
// Check member type
if (expected_type > 0) {
if (result->type() != expected_type) {
// fprintf(stderr, "P5D object member %s has unexpected type %d (rather than %d)\n", str, result->type(), expected_type);
return 0;
}
}
// Check for empty strings
if (result->type() == Json::stringValue) {
if (result->asString().length() == 0) {
// fprintf(stderr, "P5D object has zero length string named %s\n", str);
return 0;
}
}
// Return success
return 1;
}
static int
GetJsonArrayEntry(Json::Value *&result, Json::Value *array, unsigned int k, int expected_type = -1)
{
// Check array type
if (array->type() != Json::arrayValue) {
fprintf(stderr, "P5D: not an array\n");
return 0;
}
// Check array size
if (array->size() <= k) {
// fprintf(stderr, "P5D array has no member %d\n", k);
return 0;
}
// Get entry
result = &((*array)[k]);
if (result->type() == Json::nullValue) {
// fprintf(stderr, "P5D array has null member %d\n", k);
return 0;
}
// Check entry type
if (expected_type > 0) {
if (result->type() != expected_type) {
// fprintf(stderr, "P5D array entry %d has unexpected type %d (rather than %d)\n", k, result->type(), expected_type);
return 0;
}
}
// Return success
return 1;
}
static int
ParseObject(P5DObject *object, Json::Value *json_object, int idx_index)
{
// Parse attributes
Json::Value *json_value;
if (GetJsonObjectMember(json_value, json_object, "className", Json::stringValue))
object->className = strdup(json_value->asString().c_str());
if (GetJsonObjectMember(json_value, json_object, "id", Json::stringValue))
object->id = strdup(json_value->asString().c_str());
if (GetJsonObjectMember(json_value, json_object, "x"))
object->x = 0.01 * json_value->asDouble();
if (GetJsonObjectMember(json_value, json_object, "y"))
object->y = 0.01 * json_value->asDouble();
if (GetJsonObjectMember(json_value, json_object, "z"))
object->z = 0.01 * json_value->asDouble();
if (GetJsonObjectMember(json_value, json_object, "sX"))
object->sX = 0.01 * json_value->asDouble();
if (GetJsonObjectMember(json_value, json_object, "sY"))
object->sY = 0.01 * json_value->asDouble();
if (GetJsonObjectMember(json_value, json_object, "sZ"))
object->sZ = 0.01 * json_value->asDouble();
if (GetJsonObjectMember(json_value, json_object, "a"))
object->a = 3.14159265358979323846 * json_value->asDouble() / 180.0;
if (GetJsonObjectMember(json_value, json_object, "aframe", Json::intValue))
object->aframe = json_value->asInt();
if (GetJsonObjectMember(json_value, json_object, "fX", Json::intValue))
object->fX = json_value->asInt();
if (GetJsonObjectMember(json_value, json_object, "fY", Json::intValue))
object->fY = json_value->asInt();
// if (GetJsonObjectMember(json_value, json_object, "otf", Json::intValue))
// object->otf = json_value->asInt();
object->idx_index = idx_index;
// Fix id
if (object->id) {
if (strchr(object->id, '/') != NULL) {
char *copy = strdup(object->id);
free(object->id);
object->id = (char *) malloc(2*strlen(copy));
char *idp = object->id;
char *copyp = copy;
while (*copyp) {
if (*copyp == '/') {
*idp++ = '_';
*idp++ = '_';
}
else {
*idp++ = *copyp;
}
copyp++;
}
*idp = '\0';
free(copy);
}
}
// Parse materials
Json::Value *json_materials, *json_material;
if (GetJsonObjectMember(json_materials, json_object, "materials", Json::arrayValue)) {
for (Json::ArrayIndex index = 0; index < json_materials->size(); index++) {
if (!GetJsonArrayEntry(json_material, json_materials, index)) continue;
if (json_material->type() != Json::objectValue) continue;
P5DMaterial *material = new P5DMaterial(object);
if (GetJsonObjectMember(json_value, json_material, "name", Json::stringValue))
material->name = strdup(json_value->asString().c_str());
if (GetJsonObjectMember(json_value, json_material, "texture", Json::stringValue))
material->texture_name = strdup(json_value->asString().c_str());
if (GetJsonObjectMember(json_value, json_material, "color"))
material->color = strdup(json_value->asString().c_str());
if (GetJsonObjectMember(json_value, json_material, "tcolor"))
material->tcolor = strdup(json_value->asString().c_str());
}
}
// Return success
return 1;
}
static int
ParseWall(P5DWall *wall, Json::Value *json_wall, int idx_index)
{
// Parse attributes
Json::Value *json_value;
if (GetJsonObjectMember(json_value, json_wall, "w"))
wall->w = 0.01 * json_value->asDouble();
if (GetJsonObjectMember(json_value, json_wall, "hidden"))
wall->hidden = json_value->asBool();
wall->idx_index = idx_index;
// Check/fix stuff
if (wall->w <= 0) wall->w = 0.1;
// Parse points
Json::Value *json_items, *json_item, *json_className, *json_x, *json_y;
if (!GetJsonObjectMember(json_items, json_wall, "items", Json::arrayValue)) return 0;
for (Json::ArrayIndex index = 0; index < json_items->size(); index++) {
if (!GetJsonArrayEntry(json_item, json_items, index)) continue; // return 0;
if (json_item->type() != Json::objectValue) continue;
if (!GetJsonObjectMember(json_className, json_item, "className", Json::stringValue)) continue; // return 0;
if (json_className->asString().compare(std::string("Point"))) continue;
if (!GetJsonObjectMember(json_x, json_item, "x")) continue; // return 0;
if (!GetJsonObjectMember(json_y, json_item, "y")) continue; // return 0;
if (index == 0) { wall->x1 = 0.01 * json_x->asDouble(); wall->y1 = 0.01 * json_y->asDouble(); }
else if (index == 1) { wall->x2 = 0.01 * json_x->asDouble(); wall->y2 = 0.01 * json_y->asDouble(); }
}
// Return success
return 1;
}
static int
ParseRoom(P5DRoom *room, Json::Value *json_room, int idx_index)
{
// Parse attributes
Json::Value *json_value;
if (GetJsonObjectMember(json_value, json_room, "className", Json::stringValue))
room->className = strdup(json_value->asString().c_str());
if (GetJsonObjectMember(json_value, json_room, "h"))
room->h = 0.01 * json_value->asDouble();
if (GetJsonObjectMember(json_value, json_room, "x"))
room->x = 0.01 * json_value->asDouble();
if (GetJsonObjectMember(json_value, json_room, "y"))
room->y = 0.01 * json_value->asDouble();
if (GetJsonObjectMember(json_value, json_room, "sX"))
room->sX = 0.01 * json_value->asDouble();
if (GetJsonObjectMember(json_value, json_room, "sY"))
room->sY = 0.01 * json_value->asDouble();
if (GetJsonObjectMember(json_value, json_room, "rtype"))
room->rtype = strdup(json_value->asString().c_str());
if (GetJsonObjectMember(json_value, json_room, "texture", Json::stringValue))
room->texture = strdup(json_value->asString().c_str());
if (GetJsonObjectMember(json_value, json_room, "otexture", Json::stringValue))
room->otexture = strdup(json_value->asString().c_str());
if (GetJsonObjectMember(json_value, json_room, "rtexture", Json::stringValue))
room->rtexture = strdup(json_value->asString().c_str());
if (GetJsonObjectMember(json_value, json_room, "wtexture", Json::stringValue))
room->wtexture = strdup(json_value->asString().c_str());
room->idx_index = idx_index;
// Check/fix stuff
if (room->h <= 0) room->h = 2.7;
// Parse walls
Json::Value *json_items, *json_item, *json_className;
if (!GetJsonObjectMember(json_items, json_room, "items", Json::arrayValue)) return 0;
for (Json::ArrayIndex index = 0; index < json_items->size(); index++) {
if (!GetJsonArrayEntry(json_item, json_items, index)) continue; // return 0;
if (json_item->type() != Json::objectValue) continue;
if (!GetJsonObjectMember(json_className, json_item, "className", Json::stringValue)) continue; // return 0;
if (!json_className->asString().compare(std::string("Wall"))) {
P5DWall *wall = new P5DWall(room);
if (!ParseWall(wall, json_item, index)) continue; // return 0;
}
}
// Return success
return 1;
}
static int
ParseFloor(P5DFloor *floor, Json::Value *json_floor, int idx_index)
{
// Parse attributes
Json::Value *json_value;
if (GetJsonObjectMember(json_value, json_floor, "h"))
floor->h = 0.01 * json_value->asDouble();
floor->idx_index = idx_index;
// Check/fix stuff
if (floor->h <= 0) floor->h = 2.7;
// Parse rooms
std::vector<P5DRoom *> tmp_rooms;
std::vector<P5DObject *> tmp_objects;
Json::Value *json_items, *json_item, *json_className;
if (!GetJsonObjectMember(json_items, json_floor, "items", Json::arrayValue)) return 0;
for (Json::ArrayIndex index = 0; index < json_items->size(); index++) {
if (!GetJsonArrayEntry(json_item, json_items, index)) continue; // return 0;
if (json_item->type() != Json::objectValue) continue;
if (!GetJsonObjectMember(json_className, json_item, "className", Json::stringValue)) continue; // return 0;
if (!json_className->asString().compare(std::string("Ground"))) {
P5DRoom *room = new P5DRoom(floor);
if (ParseRoom(room, json_item, index)) tmp_rooms.push_back(room);
tmp_objects.push_back(NULL);
}
else if (!json_className->asString().compare(std::string("Room"))) {
P5DRoom *room = new P5DRoom(floor);
if (ParseRoom(room, json_item, index)) tmp_rooms.push_back(room);
tmp_objects.push_back(NULL);
}
else if (!json_className->asString().compare(std::string("Door"))) {
P5DObject *object = new P5DObject(floor);
if (ParseObject(object, json_item, index)) tmp_objects.push_back(object);
else tmp_objects.push_back(NULL);
}
else if (!json_className->asString().compare(std::string("Window"))) {
P5DObject *object = new P5DObject(floor);
if (ParseObject(object, json_item, index)) tmp_objects.push_back(object);
else tmp_objects.push_back(NULL);
}
else if (!json_className->asString().compare(std::string("Ns"))) {
P5DObject *object = new P5DObject(floor);
if (ParseObject(object, json_item, index)) tmp_objects.push_back(object);
else tmp_objects.push_back(NULL);
}
}
// Parse which objects are in which rooms
Json::Value *array_items = NULL, *array_item = NULL;
if (GetJsonObjectMember(json_items, json_floor, "roomObjectMapping", Json::arrayValue)) {
for (Json::ArrayIndex room_index = 0; room_index < json_items->size(); room_index++) {
if (room_index >= tmp_rooms.size()) break;
GetJsonArrayEntry(array_items, json_items, room_index, Json::arrayValue);
if (array_items->isArray()) {
for (Json::ArrayIndex array_index = 0; array_index < array_items->size(); array_index++) {
GetJsonArrayEntry(array_item, array_items, array_index);
if (array_item->isNumeric()) {
int object_index = array_item->asInt() - 1;
if ((object_index >= 0) && ((unsigned int) object_index < tmp_objects.size())) {
P5DRoom *room = tmp_rooms[room_index];
P5DObject *object = tmp_objects[object_index];
if (object && !object->room) {
object->room = room;
object->room_index = room->objects.size();
room->objects.push_back(object);
}
}
}
}
}
}
}
// Return success
return 1;
}
static int
ParseProject(P5DProject *project, Json::Value *json_project)
{
// Parse
Json::Value *json_items, *json_item, *json_className;
if (!GetJsonObjectMember(json_items, json_project, "items", Json::arrayValue)) return 0;
for (Json::ArrayIndex index = 0; index < json_items->size(); index++) {
if (!GetJsonArrayEntry(json_item, json_items, index)) continue; // return 0;
if (json_item->type() != Json::objectValue) continue;
if (!GetJsonObjectMember(json_className, json_item, "className", Json::stringValue)) continue; // return 0;
if (json_className->asString().compare(std::string("Floor"))) continue;
P5DFloor *floor = new P5DFloor(project);
if (!ParseFloor(floor, json_item, index)) continue; // return 0;
}
// Return success
return 1;
}
int P5DProject::
ReadFile(const char *filename)
{
// Open file
FILE* fp = fopen(filename, "rb");
if (!fp) {
fprintf(stderr, "Unable to open Planner5D file %s\n", filename);
return 0;
}
// Read file
std::string text;
fseek(fp, 0, SEEK_END);
long const size = ftell(fp);
fseek(fp, 0, SEEK_SET);
char* buffer = new char[size + 1];
unsigned long const usize = static_cast<unsigned long const>(size);
if (fread(buffer, 1, usize, fp) != usize) { fprintf(stderr, "Unable to read %s\n", filename); return 0; }
else { buffer[size] = 0; text = buffer; }
delete[] buffer;
// Close file
fclose(fp);
// Parse file
Json::Value json_root;
Json::Reader json_reader;
if (!json_reader.parse(text, json_root, false)) {
fprintf(stderr, "Unable to parse %s\n", filename);
return 0;
}
// Interpret file
Json::Value *json_items, *json_item, *json_data, *json_className;
if (!GetJsonObjectMember(json_items, &json_root, "items", Json::arrayValue)) return 0;
for (Json::ArrayIndex index = 0; index < json_items->size(); index++) {
if (!GetJsonArrayEntry(json_item, json_items, index)) return 0;
if (json_item->type() != Json::objectValue) continue;
if (!GetJsonObjectMember(json_data, json_item, "data", Json::objectValue)) continue;
if (!GetJsonObjectMember(json_className, json_data, "className", Json::stringValue)) return 0;
if (json_className->asString().compare(std::string("Project"))) continue;
// Parse project
if (!ParseProject(this, json_data)) {
fprintf(stderr, "Unable to read planner5d project %s\n", filename);
return 0;
}
// Return success after reading one project
return 1;
}
// No project in file
fprintf(stderr, "Planner5d project %s has no projects\n", filename);
return 0;
}
| 29.224044 | 128 | 0.571896 | [
"object",
"vector"
] |
c9a40b86e662bc77564445ff9b60a7c080cf5398 | 838 | cpp | C++ | 404.sum_of_left_leaves.cpp | liangwt/leetcode | 8f279343e975666a63ee531228c6836f20f199ca | [
"Apache-2.0"
] | 5 | 2019-09-12T05:23:44.000Z | 2021-11-15T11:19:39.000Z | 404.sum_of_left_leaves.cpp | liangwt/leetcode | 8f279343e975666a63ee531228c6836f20f199ca | [
"Apache-2.0"
] | 18 | 2019-09-23T13:11:06.000Z | 2019-11-09T11:20:17.000Z | 404.sum_of_left_leaves.cpp | liangwt/leetcode | 8f279343e975666a63ee531228c6836f20f199ca | [
"Apache-2.0"
] | null | null | null | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
#include "include/header/tree.hpp"
using namespace std;
class Solution
{
public:
int sumOfLeftLeaves(TreeNode *root)
{
if (!root)
{
return 0;
}
int total = 0;
if (root->left && root->left->left == nullptr && root->left->right == nullptr)
{
total += root->left->val;
}
total += sumOfLeftLeaves(root->left);
total += sumOfLeftLeaves(root->right);
return total;
}
};
int main()
{
Solution s;
vector<int> arr = {3, 9, 20, INT_MAX, INT_MAX, 15, 7};
assert(s.sumOfLeftLeaves(TreeNode::deserialize(arr)) == 24);
} | 19.045455 | 86 | 0.5358 | [
"vector"
] |
c9ac3581c13e9a1a74d7e617329a8f953c8679d6 | 8,476 | hpp | C++ | include/VROSC/LightUpRenderersOnHover.hpp | v0idp/virtuoso-codegen | 6f560f04822c67f092d438a3f484249072c1d21d | [
"Unlicense"
] | null | null | null | include/VROSC/LightUpRenderersOnHover.hpp | v0idp/virtuoso-codegen | 6f560f04822c67f092d438a3f484249072c1d21d | [
"Unlicense"
] | null | null | null | include/VROSC/LightUpRenderersOnHover.hpp | v0idp/virtuoso-codegen | 6f560f04822c67f092d438a3f484249072c1d21d | [
"Unlicense"
] | 1 | 2022-03-30T21:07:35.000Z | 2022-03-30T21:07:35.000Z | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
// Including type: UnityEngine.MonoBehaviour
#include "UnityEngine/MonoBehaviour.hpp"
// Including type: UnityEngine.Color
#include "UnityEngine/Color.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
#include "beatsaber-hook/shared/utils/typedefs-array.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: VROSC
namespace VROSC {
// Forward declaring type: Interactable
class Interactable;
}
// Forward declaring namespace: UnityEngine
namespace UnityEngine {
// Forward declaring type: Renderer
class Renderer;
// Forward declaring type: MaterialPropertyBlock
class MaterialPropertyBlock;
}
// Forward declaring namespace: System::Collections
namespace System::Collections {
// Forward declaring type: IEnumerator
class IEnumerator;
}
// Completed forward declares
// Type namespace: VROSC
namespace VROSC {
// Forward declaring type: LightUpRenderersOnHover
class LightUpRenderersOnHover;
}
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(::VROSC::LightUpRenderersOnHover);
DEFINE_IL2CPP_ARG_TYPE(::VROSC::LightUpRenderersOnHover*, "VROSC", "LightUpRenderersOnHover");
// Type namespace: VROSC
namespace VROSC {
// Size: 0x58
#pragma pack(push, 1)
// Autogenerated type: VROSC.LightUpRenderersOnHover
// [TokenAttribute] Offset: FFFFFFFF
class LightUpRenderersOnHover : public ::UnityEngine::MonoBehaviour {
public:
// Nested type: ::VROSC::LightUpRenderersOnHover::$HoverFlow$d__9
class $HoverFlow$d__9;
public:
// private UnityEngine.Renderer[] _renderers
// Size: 0x8
// Offset: 0x18
::ArrayW<::UnityEngine::Renderer*> renderers;
// Field size check
static_assert(sizeof(::ArrayW<::UnityEngine::Renderer*>) == 0x8);
// private VROSC.Interactable _interactable
// Size: 0x8
// Offset: 0x20
::VROSC::Interactable* interactable;
// Field size check
static_assert(sizeof(::VROSC::Interactable*) == 0x8);
// private UnityEngine.Color _lightUp
// Size: 0x10
// Offset: 0x28
::UnityEngine::Color lightUp;
// Field size check
static_assert(sizeof(::UnityEngine::Color) == 0x10);
// private System.Single _fallSpeed
// Size: 0x4
// Offset: 0x38
float fallSpeed;
// Field size check
static_assert(sizeof(float) == 0x4);
// Padding between fields: fallSpeed and: materialBlocks
char __padding3[0x4] = {};
// private UnityEngine.MaterialPropertyBlock[] _materialBlocks
// Size: 0x8
// Offset: 0x40
::ArrayW<::UnityEngine::MaterialPropertyBlock*> materialBlocks;
// Field size check
static_assert(sizeof(::ArrayW<::UnityEngine::MaterialPropertyBlock*>) == 0x8);
// private System.Boolean _hovering
// Size: 0x1
// Offset: 0x48
bool hovering;
// Field size check
static_assert(sizeof(bool) == 0x1);
// Padding between fields: hovering and: startColor
char __padding5[0x7] = {};
// private UnityEngine.Color[] _startColor
// Size: 0x8
// Offset: 0x50
::ArrayW<::UnityEngine::Color> startColor;
// Field size check
static_assert(sizeof(::ArrayW<::UnityEngine::Color>) == 0x8);
public:
// Deleting conversion operator: operator ::System::IntPtr
constexpr operator ::System::IntPtr() const noexcept = delete;
// Get instance field reference: private UnityEngine.Renderer[] _renderers
[[deprecated("Use field access instead!")]] ::ArrayW<::UnityEngine::Renderer*>& dyn__renderers();
// Get instance field reference: private VROSC.Interactable _interactable
[[deprecated("Use field access instead!")]] ::VROSC::Interactable*& dyn__interactable();
// Get instance field reference: private UnityEngine.Color _lightUp
[[deprecated("Use field access instead!")]] ::UnityEngine::Color& dyn__lightUp();
// Get instance field reference: private System.Single _fallSpeed
[[deprecated("Use field access instead!")]] float& dyn__fallSpeed();
// Get instance field reference: private UnityEngine.MaterialPropertyBlock[] _materialBlocks
[[deprecated("Use field access instead!")]] ::ArrayW<::UnityEngine::MaterialPropertyBlock*>& dyn__materialBlocks();
// Get instance field reference: private System.Boolean _hovering
[[deprecated("Use field access instead!")]] bool& dyn__hovering();
// Get instance field reference: private UnityEngine.Color[] _startColor
[[deprecated("Use field access instead!")]] ::ArrayW<::UnityEngine::Color>& dyn__startColor();
// public System.Void .ctor()
// Offset: 0x1950FCC
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static LightUpRenderersOnHover* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("::VROSC::LightUpRenderersOnHover::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<LightUpRenderersOnHover*, creationType>()));
}
// private System.Void Awake()
// Offset: 0x1950BD0
void Awake();
// private System.Void LightUp(System.Boolean hovering)
// Offset: 0x1950DD0
void LightUp(bool hovering);
// private System.Collections.IEnumerator HoverFlow()
// Offset: 0x1950E20
::System::Collections::IEnumerator* HoverFlow();
// private System.Void SetColor(System.Single amount)
// Offset: 0x1950E8C
void SetColor(float amount);
}; // VROSC.LightUpRenderersOnHover
#pragma pack(pop)
static check_size<sizeof(LightUpRenderersOnHover), 80 + sizeof(::ArrayW<::UnityEngine::Color>)> __VROSC_LightUpRenderersOnHoverSizeCheck;
static_assert(sizeof(LightUpRenderersOnHover) == 0x58);
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: VROSC::LightUpRenderersOnHover::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
// Writing MetadataGetter for method: VROSC::LightUpRenderersOnHover::Awake
// Il2CppName: Awake
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::LightUpRenderersOnHover::*)()>(&VROSC::LightUpRenderersOnHover::Awake)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(VROSC::LightUpRenderersOnHover*), "Awake", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: VROSC::LightUpRenderersOnHover::LightUp
// Il2CppName: LightUp
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::LightUpRenderersOnHover::*)(bool)>(&VROSC::LightUpRenderersOnHover::LightUp)> {
static const MethodInfo* get() {
static auto* hovering = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(VROSC::LightUpRenderersOnHover*), "LightUp", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{hovering});
}
};
// Writing MetadataGetter for method: VROSC::LightUpRenderersOnHover::HoverFlow
// Il2CppName: HoverFlow
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Collections::IEnumerator* (VROSC::LightUpRenderersOnHover::*)()>(&VROSC::LightUpRenderersOnHover::HoverFlow)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(VROSC::LightUpRenderersOnHover*), "HoverFlow", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: VROSC::LightUpRenderersOnHover::SetColor
// Il2CppName: SetColor
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::LightUpRenderersOnHover::*)(float)>(&VROSC::LightUpRenderersOnHover::SetColor)> {
static const MethodInfo* get() {
static auto* amount = &::il2cpp_utils::GetClassFromName("System", "Single")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(VROSC::LightUpRenderersOnHover*), "SetColor", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{amount});
}
};
| 46.571429 | 190 | 0.727584 | [
"vector"
] |
c9ae0db5c3aa5974a418ea6502701abab37a1236 | 6,339 | cpp | C++ | Modules/Segmentation/src/HoughTransformation2DFilter.cpp | SarahGrimm/MctAnalyzer | c2e8fe62304ff4357a66aca6f65aa10f8ce1c20e | [
"BSD-3-Clause"
] | null | null | null | Modules/Segmentation/src/HoughTransformation2DFilter.cpp | SarahGrimm/MctAnalyzer | c2e8fe62304ff4357a66aca6f65aa10f8ce1c20e | [
"BSD-3-Clause"
] | null | null | null | Modules/Segmentation/src/HoughTransformation2DFilter.cpp | SarahGrimm/MctAnalyzer | c2e8fe62304ff4357a66aca6f65aa10f8ce1c20e | [
"BSD-3-Clause"
] | null | null | null |
#include "HoughTransformation2DFilter.h"
HoughTransformation2DFilter::HoughTransformation2DFilter(){
initParams = HoughTransform2DInitParameters();
}
HoughTransformation2DFilter::~HoughTransformation2DFilter(){
}
void HoughTransformation2DFilter::InitFilter(HoughTransform2DInitParameters parameterList){
this->initParams = parameterList;
}
HoughTransform2DStatistics HoughTransformation2DFilter::getStatistics(){
return statistics;
}
std::vector<mitk::Surface::Pointer> HoughTransformation2DFilter::getCircleObjects(){
std::vector<mitk::Surface::Pointer> circles;
int numSpheres = statistics.circles.size();
for (int i = 0; i < numSpheres; ++i){
mitk::Point2D origin = statistics.circles.at(i).origin;
double radius = statistics.circles.at(i).radius;
vtkSmartPointer<vtkRegularPolygonSource> polygonSource =
vtkSmartPointer<vtkRegularPolygonSource>::New();
polygonSource->GeneratePolygonOff();
polygonSource->SetNumberOfSides(50);
polygonSource->SetRadius(radius);
polygonSource->SetCenter(origin[0], origin[1], 0);
polygonSource->Update();
mitk::Surface::Pointer sphereSurface = mitk::Surface::New();
sphereSurface->SetVtkPolyData(polygonSource->GetOutput());
circles.push_back(sphereSurface);
}
return circles;
}
void HoughTransformation2DFilter::GenerateData() {
mitk::Image::Pointer inputImage = this->GetInput(0);
mitk::Image::Pointer outputImage = this->GetOutput();
geometry = inputImage->GetGeometry();
try
{
AccessFixedDimensionByItk_n(inputImage, TrafoPipeline, 2, (outputImage));
}
catch (const mitk::AccessByItkException& e)
{
MITK_ERROR << "Unsupported pixel type or image dimension: " << e.what();
}
}
template<typename TPixel, unsigned int VImageDimension>
void HoughTransformation2DFilter::TrafoPipeline(const itk::Image<TPixel, VImageDimension>* inputImage, mitk::Image::Pointer outputImage)
{
// typedefs...
typedef float InternalPixelType;
typedef unsigned char OutputPixelType;
typedef itk::Image<TPixel, VImageDimension> ImageType;
typedef itk::Image< InternalPixelType, ImageType::ImageDimension > InternalImageType;
typedef itk::Image< OutputPixelType, ImageType::ImageDimension > OutputImageType;
ImageType::IndexType localIndex;
ImageType::SpacingType spacing;
spacing = inputImage->GetSpacing();
// calc HoughTransform...
typedef itk::HoughTransformRadialVotingImageFilter< ImageType,
InternalImageType > HoughTransformFilterType;
HoughTransformFilterType::Pointer houghFilter = HoughTransformFilterType::New();
houghFilter->SetInput(inputImage);
houghFilter->SetNumberOfSpheres(initParams.numSpheres);
houghFilter->SetMinimumRadius(initParams.minRadius);
houghFilter->SetMaximumRadius(initParams.maxRadius);
houghFilter->SetSigmaGradient(initParams.sigmaGradient);
houghFilter->SetVariance(initParams.variance);
houghFilter->SetSphereRadiusRatio(initParams.sphereRadiusRatio);
houghFilter->SetVotingRadiusRatio(initParams.votingRadiusRatio);
houghFilter->SetThreshold(initParams.threshold);
houghFilter->SetOutputThreshold(initParams.outputThreshold);
houghFilter->SetGradientThreshold(initParams.gradientThreshold);
houghFilter->SetNbOfThreads(initParams.NbOfThreads);
houghFilter->SetSamplingRatio(initParams.samplingRatio);
houghFilter->Update();
// Accumulator Image...
//InternalImageType::Pointer localAccumulator = houghFilter->GetOutput();
// get Circles...
HoughTransformFilterType::SpheresListType circles;
circles = houghFilter->GetSpheres();
// Computing circles output...
OutputImageType::Pointer localOutputImage = OutputImageType::New();
OutputImageType::RegionType region;
region.SetSize(inputImage->GetLargestPossibleRegion().GetSize());
region.SetIndex(inputImage->GetLargestPossibleRegion().GetIndex());
localOutputImage->SetRegions(region);
localOutputImage->SetOrigin(inputImage->GetOrigin());
localOutputImage->SetSpacing(inputImage->GetSpacing());
localOutputImage->Allocate();
localOutputImage->FillBuffer(0);
typedef HoughTransformFilterType::SpheresListType SpheresListType;
SpheresListType::const_iterator itSpheres = circles.begin();
unsigned int count = 1;
while (itSpheres != circles.end())
{
mitk::Point3D pIndex;
pIndex[0] = (*itSpheres)->GetObjectToParentTransform()->GetOffset()[0];
pIndex[1] = (*itSpheres)->GetObjectToParentTransform()->GetOffset()[1];
pIndex[2] = 0;
mitk::Point3D pWorld;
geometry->IndexToWorld(pIndex, pWorld);
double r = (*itSpheres)->GetRadius()[0];
CircleStatistics stat; stat.origin[0] = pWorld[0]; stat.origin[1] = pWorld[1]; stat.radius = r;
statistics.circles.push_back(stat);
for (double angle = 0; angle <= 2 * vnl_math::pi; angle += vnl_math::pi / 60.0)
{
localIndex[0] =
(long int)((*itSpheres)->GetObjectToParentTransform()->GetOffset()[0]
+ ((*itSpheres)->GetRadius()[0] * vcl_cos(angle)) / spacing[0]);
localIndex[1] =
(long int)((*itSpheres)->GetObjectToParentTransform()->GetOffset()[1]
+ ((*itSpheres)->GetRadius()[1] * vcl_sin(angle)) / spacing[1]);
OutputImageType::RegionType outputRegion =
localOutputImage->GetLargestPossibleRegion();
if (outputRegion.IsInside(localIndex))
{
localOutputImage->SetPixel(localIndex, count);
}
}
itSpheres++;
count++;
}
int radius = 2;
typedef itk::BinaryBallStructuringElement< OutputPixelType, ImageType::ImageDimension >
SEType;
SEType sE;
sE.SetRadius(radius);
sE.CreateStructuringElement();
typedef itk::GrayscaleDilateImageFilter< OutputImageType, OutputImageType, SEType >
DilateFilterType;
DilateFilterType::Pointer grayscaleDilate = DilateFilterType::New();
grayscaleDilate->SetKernel(sE);
grayscaleDilate->SetInput(localOutputImage);
grayscaleDilate->Update();
typedef itk::RGBPixel< unsigned char > RGBPixelType;
typedef itk::Image< RGBPixelType, ImageType::ImageDimension > RGBImageType;
typedef itk::LabelOverlayImageFilter< ImageType, OutputImageType, RGBImageType > OverlayType;
OverlayType::Pointer overlay = OverlayType::New();
overlay->SetInput(inputImage);
overlay->SetLabelImage(grayscaleDilate->GetOutput());
overlay->Update();
statistics.circleImage = mitk::ImportItkImage(overlay->GetOutput());
// save Output Image...
mitk::GrabItkImageMemory(overlay->GetOutput(), outputImage);
MITK_INFO << "filter pipeline was applied!";
} | 34.080645 | 136 | 0.76826 | [
"geometry",
"vector"
] |
c9b56eb2c6cc43d596f59d37b4ae5d2e24bf0014 | 4,399 | cpp | C++ | explore.cpp | hi7/explore | 67829444422eba2efb25c5476adbdaa5aeab752a | [
"MIT"
] | null | null | null | explore.cpp | hi7/explore | 67829444422eba2efb25c5476adbdaa5aeab752a | [
"MIT"
] | null | null | null | explore.cpp | hi7/explore | 67829444422eba2efb25c5476adbdaa5aeab752a | [
"MIT"
] | null | null | null | #include "explore.hpp"
#include "assets.hpp"
using namespace blit;
const Point center(160, 120);
Point bones_position = center;
int32_t anim_x = 0;
int32_t anim_y = 0;
enum Direction { NE = 0, SE = 1, SW = 2, NW = 3 };
void init() {
set_screen_mode(ScreenMode::hires);
screen.sprites = Surface::load(bones_sheet);
}
bool isNorth(const Direction d) {
return d == NE || d == NW;
}
bool isEast(const Direction d) {
return d == NE || d == SE;
}
bool isSouth(const Direction d) {
return d == SE || d == SW;
}
bool isWest(const Direction d) {
return d == NW || d == SW;
}
/**
* Draw text to surface using the specified font and the current pen.
*
* \param message Text to draw
* \param p Point to align text to
* \param d Direction of speech bubble
*/
void say(std::string_view message, const Point &p, const Direction d = NE) {
int32_t width = screen.measure_text(message, minimal_font).w + 11;
int32_t height = 15;
screen.pen = Pen(255, 255, 255);
screen.rectangle(Rect(p.x + (isEast(d) ? +2 : -width -2), p.y + (isNorth(d) ? -16 : +2) , width, height));
screen.rectangle(Rect(p.x + (isEast(d) ? +2 : -3), p.y + (isNorth(d) ? -2 : +1), 2, 2));
screen.rectangle(Rect(p.x + (isEast(d) ? +1 : -1), p.y + (isNorth(d) ? -1 : 0), 1, 2));
screen.pixel(Point(p.x, p.y));
screen.pen = Pen(0, 0, 0);
screen.pixel(Point(p.x +(isEast(d) ? width +1 : -width -2), p.y + (isNorth(d) ? -2 : +2)));
screen.pixel(Point(p.x + (isEast(d) ? width+1 : -3), p.y + (isNorth(d) ? -16 : +16)));
screen.pixel(Point(p.x + (isEast(d) ? +2 : -width-2), p.y + (isNorth(d) ? -16 : +16)));
screen.text(message, minimal_font, Point(p.x + (isEast(d) ? +8 : -width +3), p.y + (isNorth(d) ? -12 : +6)));
}
///////////////////////////////////////////////////////////////////////////
//
// render(time)
//
// This function is called to perform rendering of the game. time is the
// amount if milliseconds elapsed since the start of your game
//
void render(uint32_t time) {
// clear the screen -- screen is a reference to the frame buffer and can be used to draw all things with the 32blit
screen.clear();
// draw some text at the top of the screen
screen.alpha = 255;
screen.mask = nullptr;
Point origin(8, 23);
if(time > 1000 && time < 3000) {
say("hello mortal", Point(bones_position.x + 6, bones_position.y - 24), NE);
}
if(time > 2000) {
screen.sprite(Rect(anim_x, anim_y, 2, 3), bones_position, origin);
}
if(time > 7000 && time < 9000) {
say("move along", Point(bones_position.x + 6, bones_position.y - 24), NE);
}
// set background color
if(time < 5000) {
screen.pen = Pen(0, 0, 0);
} else if(time < 15000) {
uint8_t value = (uint8_t) ((time - 5000) / 100);
screen.pen = Pen(value, value, value);
} else {
screen.pen = Pen(100, 100, 100);
}
}
///////////////////////////////////////////////////////////////////////////
//
// update(time)
//
// This is called to update your game state. time is the
// amount if milliseconds elapsed since the start of your game
//
const Point border(60, 40);
const uint32_t movement = 20;
uint32_t rest = 0;
uint32_t last_update = 0;
uint32_t delta = 0;
void update(uint32_t time) {
delta = time - last_update;
rest += delta;
if(rest > movement) {
anim_x = 0;
}
if(rest > 8000) {
anim_x = (time / 100 % 2) * 2;
}
if (buttons.state & Button::A) {
anim_x = 8;
rest = 0;
}
if ((time % movement == 0) && (buttons.state & Button::DPAD_LEFT) && (bones_position.x > 8 + border.x)) {
bones_position.x -= 8;
anim_x = (anim_x == 4 ? 6 : 4);
rest = 0;
}
if ((time % movement == 0) && (buttons.state & Button::DPAD_RIGHT) && (bones_position.x < 312 - border.x)) {
bones_position.x += 8;
anim_x = (anim_x == 4 ? 6 : 4);
rest = 0;
}
if ((time % movement == 0) && (buttons.state & Button::DPAD_UP) && (bones_position.y > 32 + border.y)) {
bones_position.y -= 8;
anim_x = (anim_x == 4 ? 6 : 4);
rest = 0;
}
if ((time % movement == 0) && (buttons.state & Button::DPAD_DOWN) && (bones_position.y < 232 - border.y)) {
bones_position.y += 8;
anim_x = (anim_x == 4 ? 6 : 4);
rest = 0;
}
last_update = time;
} | 31.876812 | 119 | 0.55308 | [
"render"
] |
c9b59694f08b9341443d96beddfe1563df234d14 | 8,680 | cpp | C++ | samples/LoginCpp-UWP/LoginCpp/App.xaml.cpp | omer-ispl/winsdkfb1 | e3bcd1d1e49e5ff94e6a9c971e4d8a9c82fad93b | [
"MIT"
] | 197 | 2015-07-14T22:33:14.000Z | 2019-05-05T15:26:15.000Z | samples/LoginCpp-UWP/LoginCpp/App.xaml.cpp | omer-ispl/winsdkfb1 | e3bcd1d1e49e5ff94e6a9c971e4d8a9c82fad93b | [
"MIT"
] | 209 | 2015-07-15T14:49:48.000Z | 2019-02-15T14:39:48.000Z | samples/LoginCpp-UWP/LoginCpp/App.xaml.cpp | omer-ispl/winsdkfb1 | e3bcd1d1e49e5ff94e6a9c971e4d8a9c82fad93b | [
"MIT"
] | 115 | 2015-07-15T06:57:34.000Z | 2019-01-12T08:55:15.000Z | //******************************************************************************
//
// Copyright (c) 2015 Microsoft Corporation. All rights reserved.
//
// This code is licensed under the MIT License (MIT).
//
// 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.
//
//******************************************************************************
//
// App.xaml.cpp
// Implementation of the App class.
//
#include "pch.h"
#include "MainPage.xaml.h"
#include "UserInfo.xaml.h"
using namespace LoginCpp;
using namespace concurrency;
using namespace Platform;
using namespace Windows::ApplicationModel;
using namespace Windows::ApplicationModel::Activation;
using namespace Windows::ApplicationModel::Core;
using namespace Windows::Foundation;
using namespace Windows::Foundation::Collections;
using namespace Windows::UI::Core;
using namespace Windows::UI::Xaml::Media::Animation;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Controls::Primitives;
using namespace Windows::UI::Xaml::Data;
using namespace Windows::UI::Xaml::Input;
using namespace Windows::UI::Xaml::Interop;
using namespace Windows::UI::Xaml::Media;
using namespace Windows::UI::Xaml::Navigation;
using namespace winsdkfb;
// The Blank Application template is documented at http://go.microsoft.com/fwlink/?LinkId=234227
/// <summary>
/// Initializes the singleton application object. This is the first line of authored code
/// executed, and as such is the logical equivalent of main() or WinMain().
/// </summary>
App::App()
{
InitializeComponent();
Suspending += ref new SuspendingEventHandler(this, &App::OnSuspending);
}
Frame^ App::CreateRootFrame()
{
Frame^ rootFrame = dynamic_cast<Frame^>(Window::Current->Content);
if (rootFrame == nullptr)
{
// Create a Frame to act as the navigation context
rootFrame = ref new Frame();
// Set the default language
rootFrame->Language = Windows::Globalization::ApplicationLanguages::Languages->GetAt(0);
// Place the frame in the current Window
Window::Current->Content = rootFrame;
}
return rootFrame;
}
/// <summary>
/// Invoked when the application is launched normally by the end user. Other entry points
/// will be used when the application is launched to open a specific file, to display
/// search results, and so forth.
/// </summary>
/// <param name="e">Details about the launch request and process.</param>
void App::OnLaunched(LaunchActivatedEventArgs^ e)
{
#if _DEBUG
if (IsDebuggerPresent())
{
DebugSettings->EnableFrameRateCounter = true;
}
#endif
auto rootFrame = dynamic_cast<Frame^>(Window::Current->Content);
// Do not repeat app initialization when the Window already has content,
// just ensure that the window is active.
if (rootFrame == nullptr)
{
// Create a Frame to act as the navigation context and associate it with
// a SuspensionManager key
rootFrame = ref new Frame();
// TODO: Change this value to a cache size that is appropriate for your application.
rootFrame->CacheSize = 1;
if (e->PreviousExecutionState == ApplicationExecutionState::Terminated)
{
// TODO: Restore the saved session state only when appropriate, scheduling the
// final launch steps after the restore is complete.
}
// Place the frame in the current Window
Window::Current->Content = rootFrame;
SystemNavigationManager::GetForCurrentView()->BackRequested += ref new Windows::Foundation::EventHandler<Windows::UI::Core::BackRequestedEventArgs ^>(this, &LoginCpp::App::OnBackRequested);
rootFrame->Navigated += ref new Windows::UI::Xaml::Navigation::NavigatedEventHandler(this, &LoginCpp::App::OnNavigated);
}
if (rootFrame->Content == nullptr)
{
#if WINAPI_FAMILY==WINAPI_FAMILY_PHONE_APP
// Removes the turnstile navigation for startup.
if (rootFrame->ContentTransitions != nullptr)
{
_transitions = ref new TransitionCollection();
for (auto transition : rootFrame->ContentTransitions)
{
_transitions->Append(transition);
}
}
rootFrame->ContentTransitions = nullptr;
_firstNavigatedToken = rootFrame->Navigated += ref new NavigatedEventHandler(this, &App::RootFrame_FirstNavigated);
#endif
// When the navigation stack isn't restored navigate to the first page,
// configuring the new page by passing required information as a navigation
// parameter.
if (!rootFrame->Navigate(MainPage::typeid, e->Arguments))
{
throw ref new FailureException("Failed to create initial page");
}
}
// Ensure the current window is active
Window::Current->Activate();
}
#if WINAPI_FAMILY==WINAPI_FAMILY_PHONE_APP
/// <summary>
/// Restores the content transitions after the app has launched.
/// </summary>
void App::RootFrame_FirstNavigated(Object^ sender, NavigationEventArgs^ e)
{
auto rootFrame = safe_cast<Frame^>(sender);
TransitionCollection^ newTransitions;
if (_transitions == nullptr)
{
newTransitions = ref new TransitionCollection();
newTransitions->Append(ref new NavigationThemeTransition());
}
else
{
newTransitions = _transitions;
}
rootFrame->ContentTransitions = newTransitions;
rootFrame->Navigated -= _firstNavigatedToken;
}
void App::OnActivated(IActivatedEventArgs^ e)
{
// Check for activation via protocol. This code assumes the only protocol
// supported by our app is the Facebook redirect protocol (msft-<GUID>).
// If your app supports multiple protocols, you'll have to filter here.
if (e->Kind == Windows::ApplicationModel::Activation::ActivationKind::Protocol)
{
ProtocolActivatedEventArgs^ p = safe_cast<ProtocolActivatedEventArgs^>(e);
FBSession^ sess = FBSession::ActiveSession;
// FinishOpenViaFBApp retrieves basic user info via Facebook graph API,
// storing it in the Session::User property. After this async
// action completes, the user info will be valid (assuming login
// success).
create_task(sess->ContinueAction(p))
.then([this](task<FBResult^> resultTask)
{
try
{
FBResult^ result = resultTask.get();
if (result)
{
if (result->Succeeded)
{
// We're redirecting to a page that shows simple user info, so
// have to dispatch back to the UI thread.
CoreWindow^ wind = CoreApplication::MainView->CoreWindow;
if (wind)
{
CoreDispatcher^ disp = wind->Dispatcher;
if (disp)
{
disp->RunAsync(
Windows::UI::Core::CoreDispatcherPriority::Normal,
ref new Windows::UI::Core::DispatchedHandler([this]()
{
this->CreateRootFrame()->Navigate(UserInfo::typeid);
}));
}
}
}
else
{
String^ msg = "ERROR: code " +
result->ErrorInfo->Code.ToString() + ", Reason '" +
result->ErrorInfo->Type + "', Message '" +
result->ErrorInfo->Message + "'";
OutputDebugString(msg->Data());
}
}
}
catch (COMException^ ex)
{
//TODO: Handle errors here
OutputDebugString(L"Exception in continuation of login");
}
});
}
}
#endif
/// <summary>
/// Invoked when application execution is being suspended. Application state is saved
/// without knowing whether the application will be terminated or resumed with the contents
/// of memory still intact.
/// </summary>
void App::OnSuspending(Object^ sender, SuspendingEventArgs^ e)
{
(void)sender; // Unused parameter
(void)e; // Unused parameter
// TODO: Save application state and stop any background activity
}
void LoginCpp::App::OnBackRequested(Platform::Object^ sender, Windows::UI::Core::BackRequestedEventArgs ^args)
{
Frame^ rootFrame = dynamic_cast<Frame^>(Window::Current->Content);
if (rootFrame->CanGoBack)
{
args->Handled = true;
rootFrame->GoBack();
}
}
void LoginCpp::App::OnNavigated(Platform::Object^ sender, Windows::UI::Xaml::Navigation::NavigationEventArgs^ args)
{
Frame^ rootFrame = dynamic_cast<Frame^>(Window::Current->Content);
if (rootFrame->CanGoBack)
{
SystemNavigationManager::GetForCurrentView()->AppViewBackButtonVisibility = AppViewBackButtonVisibility::Visible;
}
else
{
SystemNavigationManager::GetForCurrentView()->AppViewBackButtonVisibility = AppViewBackButtonVisibility::Collapsed;
}
}
| 31.911765 | 197 | 0.704147 | [
"object"
] |
c9c2415badea623ebba48dd5feb615669dee8515 | 779 | cpp | C++ | C++/binary-subarrays-with-sum.cpp | black-shadows/LeetCode-Solutions | b1692583f7b710943ffb19b392b8bf64845b5d7a | [
"Fair",
"Unlicense"
] | 1 | 2020-04-16T08:38:14.000Z | 2020-04-16T08:38:14.000Z | binary-subarrays-with-sum.cpp | Jeevan-kumar-Raj/LeetCode-Solutions-Topicwise | f1111b4edd401a3fc47111993bd7250cf4dc76da | [
"MIT"
] | null | null | null | binary-subarrays-with-sum.cpp | Jeevan-kumar-Raj/LeetCode-Solutions-Topicwise | f1111b4edd401a3fc47111993bd7250cf4dc76da | [
"MIT"
] | 1 | 2021-12-25T14:48:56.000Z | 2021-12-25T14:48:56.000Z | // Time: O(n)
// Space: O(1)
// Two pointers solution.
class Solution {
public:
int numSubarraysWithSum(vector<int>& A, int S) {
int result = 0;
int left = 0, right = 0, sum_left = 0, sum_right = 0;
for (int i = 0; i < A.size(); ++i) {
for (sum_left += A[i];
left < i && sum_left > S;
++left) {
sum_left -= A[left];
}
for (sum_right += A[i];
right < i && (sum_right > S || (sum_right == S && !A[right]));
++right) {
sum_right -= A[right];
}
if (sum_left == S) {
result += right - left + 1;
}
}
return result;
}
};
| 27.821429 | 80 | 0.377407 | [
"vector"
] |
c9c2a3a4fdfad0e54f28e4a3fa2e98e20314d067 | 8,694 | cpp | C++ | src/TempoDetectCmd/TempoDetectCmd.cpp | madmaxoft/SkauTan | 941ea86e35d101cc3694b478689cd269ea371eac | [
"Unlicense"
] | 1 | 2018-05-02T11:51:35.000Z | 2018-05-02T11:51:35.000Z | src/TempoDetectCmd/TempoDetectCmd.cpp | madmaxoft/SkauTan | 941ea86e35d101cc3694b478689cd269ea371eac | [
"Unlicense"
] | 181 | 2018-01-06T08:39:30.000Z | 2019-12-02T09:25:24.000Z | src/TempoDetectCmd/TempoDetectCmd.cpp | madmaxoft/SkauTan | 941ea86e35d101cc3694b478689cd269ea371eac | [
"Unlicense"
] | 1 | 2022-03-10T05:25:04.000Z | 2022-03-10T05:25:04.000Z | #include <iostream>
#include <thread>
#include <vector>
#include <string>
#include <mutex>
#include <QString>
#include <QFile>
#include "../SongTempoDetector.hpp"
#include "../Song.hpp"
#include "../MetadataScanner.hpp"
using namespace std;
struct Results
{
/** The detected tempo. */
double mTempo;
/** The raw ID3 tag as read from the file. */
MetadataScanner::Tag mRawTag;
/** The processed ID3 tag. */
Song::Tag mParsedTag;
};
/** Specifies whether ID3 information should be parsed from the files and included in the output.
Settable through the "-i" cmdline param. */
static bool g_ShouldIncludeID3 = false;
/** The global instance of the tempo detector. */
static SongTempoDetector g_TempoDetector;
/** FileNames to process.
After a filename is sent to processing, it is removed from this vector.
Protected against multithreaded access by mMtx. */
static vector<QString> g_FileNames;
/** Map of FileName -> Results of all successfully detected songs.
Protected against multithreaded access by mMtx. */
static map<QString, unique_ptr<Results>> g_Results;
/** The mutex protecting g_FileNames and g_Results against multithreaded access. */
static mutex g_Mtx;
/** Outputs the specified value to the stream, in utf-8. */
static std::ostream & operator <<(std::ostream & aStream, const QString & aValue)
{
aStream << aValue.toStdString();
return aStream;
}
/** Returns the input string, escaped so that it can be embedded in Lua code in a doublequote. */
static std::string luaEscapeString(const QString & aInput)
{
static QLatin1String singleBackslash("\\");
static QLatin1String doubleBackslash("\\\\");
static QLatin1String doubleQuote("\"");
static QLatin1String escapedDoubleQuote("\\\"");
return QString(aInput)
.replace(singleBackslash, doubleBackslash)
.replace(doubleQuote, escapedDoubleQuote)
.replace("\r\n", "\n")
.replace("\n", "\\n")
.toStdString();
}
static void printUsage()
{
cerr << "TempoDetectCmd" << endl;
cerr << "-------------" << endl;
cerr << "Detects tempo in audio files, using the algorithms and options currently used in SkauTan." << endl;
cerr << "Part of SkauTan player, https://github.com/madmaxoft/SkauTan" << endl;
cerr << endl;
cerr << "Usage:" << endl;
cerr << "TempoDetectCmd [options] [filename] [filename] ..." << endl;
cerr << endl;
cerr << "Available options:" << endl;
cerr << " -i ... Include the ID3 information from the file in the output" << endl;
}
/** Reads the ID3 tag from the file and returns the raw data and the parsed data.
If the tag cannot be read from the file, returns empty tags. */
pair<MetadataScanner::Tag, Song::Tag> readTag(const QString & aFileName)
{
auto rawTag = MetadataScanner::readTagFromFile(aFileName);
if (!rawTag.first)
{
// No tag could be read from the file, bail out
return {};
}
return {rawTag.second, MetadataScanner::parseId3Tag(rawTag.second)};
}
static unique_ptr<Results> runDetectionOnFile(const QString & aFileName)
{
if (!QFile::exists(aFileName))
{
cerr << "File doesn't exist: " << aFileName << endl;
return nullptr;
}
// Extract the tags:
auto res = make_unique<Results>();
tie(res->mRawTag, res->mParsedTag) = readTag(aFileName);
auto genre = res->mParsedTag.mGenre.valueOrDefault();
auto songSD = std::make_shared<Song::SharedData>(QByteArray(), 0); // Dummy SharedData
songSD->mTagManual = res->mParsedTag; // Use the ID3 tag for detection
SongPtr song = std::make_shared<Song>(aFileName, songSD);
song->setFileNameTag(MetadataScanner::parseFileNameIntoMetadata(aFileName));
if (!res->mParsedTag.mMeasuresPerMinute.isPresent())
{
// If ID3 doesn't have the MPM, copy from filename-based tag:
res->mParsedTag.mMeasuresPerMinute = song->tagFileName().mMeasuresPerMinute;
}
// Run the tempo detection:
if (!g_TempoDetector.detect(songSD))
{
cerr << "Detection failed: " << aFileName << endl;
return nullptr;
}
res->mTempo = song->detectedTempo().valueOr(-1);
return res;
}
/** Implementation of a single worker thread.
Takes a file from g_FileNames and runs the tempo detection on it; loops until there are no more filenames.
Stores the detection results in g_Results. */
static void runDetection()
{
unique_lock<mutex> lock(g_Mtx);
while (!g_FileNames.empty())
{
auto fileName = g_FileNames.back();
g_FileNames.pop_back();
lock.unlock();
auto results = runDetectionOnFile(fileName);
lock.lock();
if (results != nullptr)
{
g_Results[fileName] = std::move(results);
}
}
}
/** Spins up threads for the file processing, processes each file. */
static void processFiles()
{
// Start the processing threads:
vector<thread> threads;
for (auto i = thread::hardware_concurrency(); i > 0; --i)
{
threads.push_back(thread(runDetection));
}
// Wait for the threads to finish:
for (auto & thr: threads)
{
thr.join();
}
}
/** Adds the contents of the list file into the file list to be processed. */
static void addListFile(const QString & aFileName)
{
QFile f(aFileName);
if (!f.open(QFile::ReadOnly | QFile::Text))
{
cerr << "Cannot open list file " << aFileName << ": " << f.errorString() << endl;
return;
}
auto contents = f.readAll();
auto files = contents.split('\n');
for (const auto & file: files)
{
if (!file.isEmpty())
{
g_FileNames.push_back(file);
}
}
}
#define NEED_ARGS(N) \
if (i + N >= argc) \
{ \
cerr << "Bad argument " << i << " (" << aArgs[i] << "): needs " << N << " parameters" << endl; \
return false; \
} \
/** Processes all command-line arguments. */
static bool processArgs(const vector<string> & aArgs)
{
size_t argc = aArgs.size();
vector<QString> files;
for (size_t i = 0; i < argc; ++i)
{
if (aArgs[i][0] == '-')
{
switch (aArgs[i][1])
{
case '?':
case 'h':
case 'H':
{
printUsage();
break;
}
case 'i':
case 'I':
{
g_ShouldIncludeID3 = true;
break;
}
case 'l':
case 'L':
{
NEED_ARGS(1);
addListFile(QString::fromStdString(aArgs[i + 1]));
i += 1;
break;
}
} // switch (arg)
continue;
} // if ('-')
g_FileNames.push_back(QString::fromStdString(aArgs[i]));
}
return true;
}
/** Outputs the raw and processed ID3 tags to stdout, formatted as Lua source. */
static void outputId3Tag(const Results & aResults)
{
cout << "\t\trawID3Tag =" << endl;
cout << "\t\t{" << endl;
if (aResults.mRawTag.mAuthor.isPresent())
{
cout << "\t\t\tauthor = \"" << luaEscapeString(aResults.mRawTag.mAuthor.value()) << "\"," << endl;
}
if (aResults.mRawTag.mTitle.isPresent())
{
cout << "\t\t\ttitle = \"" << luaEscapeString(aResults.mRawTag.mTitle.value()) << "\"," << endl;
}
if (aResults.mRawTag.mGenre.isPresent())
{
cout << "\t\t\tgenre = \"" << luaEscapeString(aResults.mRawTag.mGenre.value()) << "\"," << endl;
}
if (aResults.mRawTag.mMeasuresPerMinute.isPresent())
{
cout << "\t\t\tmpm = " << aResults.mRawTag.mMeasuresPerMinute.value() << "," << endl;
}
if (aResults.mRawTag.mComment.isPresent())
{
cout << "\t\t\tcomment = \"" << luaEscapeString(aResults.mRawTag.mComment.value()) << "\"," << endl;
}
cout << "\t\t}," << endl;
cout << "\t\tparsedID3Tag =" << endl;
cout << "\t\t{" << endl;
const auto & parsedTag = aResults.mParsedTag;
if (parsedTag.mAuthor.isPresent())
{
cout << "\t\t\tauthor = \"" << luaEscapeString(parsedTag.mAuthor.value()) << "\"," << endl;
}
if (parsedTag.mTitle.isPresent())
{
cout << "\t\t\ttitle = \"" << luaEscapeString(parsedTag.mTitle.value()) << "\"," << endl;
}
if (parsedTag.mGenre.isPresent())
{
cout << "\t\t\tgenre = \"" << luaEscapeString(parsedTag.mGenre.value()) << "\"," << endl;
}
if (parsedTag.mMeasuresPerMinute.isPresent())
{
cout << "\t\t\tmpm = " << parsedTag.mMeasuresPerMinute.value() << "," << endl;
}
cout << "\t\t}," << endl;
}
/** Outputs all the results to stdout, as a Lua source file. */
static void outputResults()
{
cout << "return" << endl << "{" << endl;
for (const auto & res: g_Results)
{
const auto & fileName = res.first;
const auto & results = res.second;
cout << "\t[\"" << luaEscapeString(fileName) << "\"] =" << endl;
cout << "\t{" << endl;
cout << "\t\tfileName = \"" << luaEscapeString(fileName) << "\"," << endl;
cout << "\t\ttempo = " << results->mTempo << "," << endl;
if (g_ShouldIncludeID3)
{
outputId3Tag(*results);
}
cout << "\t}," << endl;
}
cout << "}" << endl;
}
int main(int argc, char *argv[])
{
vector<string> args;
for (int i = 1; i < argc; ++i)
{
args.emplace_back(argv[i]);
}
if (!processArgs(args))
{
return 1;
}
processFiles();
outputResults();
return 0;
}
| 23 | 109 | 0.646538 | [
"vector"
] |
c9c576ba292035fd05206d5aaf993d49b122c8ed | 829 | cpp | C++ | class/screen/screen.cpp | leimingyu/notes-cpp | 496ea31bb733eee50914b7c2ae5a3cef4bfadc15 | [
"MIT"
] | null | null | null | class/screen/screen.cpp | leimingyu/notes-cpp | 496ea31bb733eee50914b7c2ae5a3cef4bfadc15 | [
"MIT"
] | null | null | null | class/screen/screen.cpp | leimingyu/notes-cpp | 496ea31bb733eee50914b7c2ae5a3cef4bfadc15 | [
"MIT"
] | null | null | null | #include <iostream>
#include <cmath>
#include <vector>
#include <string>
using namespace std;
// size_type need to go with containers
// it is like size_t, but more dynamic and tolerable on the data size
class Screen
{
public:
typedef string::size_type pos;
Screen() = default;
Screen(pos ht, pos wd, char c) : height(ht), width(wd), contents(ht*wd, c) {}
char get() const { return contents[cursor]; } // implicit inline
inline char get(pos ht, pos wd) const; // explicit inline
Screen &move(pos r, pos c);
private:
pos cursor = 0;
pos height = 0;
pos width = 0;
string contents;
};
char Screen::get(pos ht, pos wd) const
{
pos row = ht * width;
return contents[row + wd];
}
inline
Screen& Screen::move(pos r, pos c)
{
pos row = r * width;
cursor = row + c;
return *this;
}
int main()
{
return 0;
}
| 16.918367 | 78 | 0.66345 | [
"vector"
] |
c9c7c4f9fb0970d3bda73641b516eeba79fc7e91 | 1,573 | cpp | C++ | Conch/source/webglPlus/v8/JCWebGLPlusV8.cpp | waitingchange/ModifyLayanative2.0 | 05370d79a14f5b85367251c8ea846da4316f60f3 | [
"Apache-2.0"
] | null | null | null | Conch/source/webglPlus/v8/JCWebGLPlusV8.cpp | waitingchange/ModifyLayanative2.0 | 05370d79a14f5b85367251c8ea846da4316f60f3 | [
"Apache-2.0"
] | null | null | null | Conch/source/webglPlus/v8/JCWebGLPlusV8.cpp | waitingchange/ModifyLayanative2.0 | 05370d79a14f5b85367251c8ea846da4316f60f3 | [
"Apache-2.0"
] | null | null | null | /**
@file JCWebGLPlus.cpp
@brief
@author James
@version 1.0
@date 2019_8_24
*/
#include "../JCWebGLPlus.h"
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "../Log.h"
#include "JSWebGLPlus.h"
#include "JSArrayBufferRef.h"
#include "JSKeyframeNode.h"
#include "JSFloatKeyframe.h"
#include "JSKeyframeNodeList.h"
namespace laya
{
void JCWebGLPlus::exportJS(void* ctx, void* object)
{
JSWebGLPlus::getInstance()->exportJS(*(v8::Local<v8::Object>*)object);
JSArrayBufferRef::exportJS(*(v8::Local<v8::Object>*)object);
JSFloatKeyframe::exportJS(*(v8::Local<v8::Object>*)object);
JSFloatArrayKeyframe::exportJS(*(v8::Local<v8::Object>*)object);
JSKeyframeNode::exportJS(*(v8::Local<v8::Object>*)object);
JSKeyframeNodeList::exportJS(*(v8::Local<v8::Object>*)object);
}
void JCWebGLPlus::clean()
{
}
void JCWebGLPlus::clearAll()
{
if (JSWebGLPlus::s_pWebGLPlus != NULL)
{
JSWebGLPlus::s_pWebGLPlus->persistentObject.Reset();
}
JSArrayBufferRef::persistentObjectTemplate.Reset();
JSFloatKeyframe::persistentObjectTemplate.Reset();
JSFloatArrayKeyframe::persistentObjectTemplate.Reset();
JSKeyframeNode::persistentObjectTemplate.Reset();
JSKeyframeNodeList::persistentObjectTemplate.Reset();
m_pJSArrayBufferManager->clearAll();
m_pJSABManagerSyncToRender->clearAll();
m_pRArrayBufferManager->clearAll();
clean();
}
}
//-----------------------------END FILE--------------------------------
| 29.12963 | 78 | 0.650985 | [
"object"
] |
c9c9e170649f130e5b6f76e4406593c607934b22 | 7,922 | cc | C++ | net/dns/host_resolver_impl_fuzzer.cc | Wzzzx/chromium-crosswalk | 768dde8efa71169f1c1113ca6ef322f1e8c9e7de | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2019-01-28T08:09:58.000Z | 2021-11-15T15:32:10.000Z | net/dns/host_resolver_impl_fuzzer.cc | Wzzzx/chromium-crosswalk | 768dde8efa71169f1c1113ca6ef322f1e8c9e7de | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | net/dns/host_resolver_impl_fuzzer.cc | Wzzzx/chromium-crosswalk | 768dde8efa71169f1c1113ca6ef322f1e8c9e7de | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 6 | 2020-09-23T08:56:12.000Z | 2021-11-18T03:40:49.000Z | // Copyright 2016 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 <stddef.h>
#include <stdint.h>
#include <memory>
#include <vector>
#include "base/bind.h"
#include "base/logging.h"
#include "base/run_loop.h"
#include "net/base/address_family.h"
#include "net/base/address_list.h"
#include "net/base/fuzzed_data_provider.h"
#include "net/base/net_errors.h"
#include "net/base/request_priority.h"
#include "net/dns/fuzzed_host_resolver.h"
#include "net/dns/host_resolver.h"
#include "net/log/test_net_log.h"
namespace {
const char* kHostNames[] = {"foo", "foo.com", "a.foo.com",
"bar", "localhost", "localhost6"};
net::AddressFamily kAddressFamilies[] = {
net::ADDRESS_FAMILY_UNSPECIFIED, net::ADDRESS_FAMILY_IPV4,
net::ADDRESS_FAMILY_IPV6,
};
class DnsRequest {
public:
DnsRequest(net::HostResolver* host_resolver,
net::FuzzedDataProvider* data_provider,
std::vector<std::unique_ptr<DnsRequest>>* dns_requests)
: host_resolver_(host_resolver),
data_provider_(data_provider),
dns_requests_(dns_requests),
handle_(nullptr),
is_running_(false) {}
~DnsRequest() {
if (is_running_)
Cancel();
}
// Creates and starts a DNS request using fuzzed parameters. If the request
// doesn't complete synchronously, adds it to |dns_requests|.
static void CreateRequest(
net::HostResolver* host_resolver,
net::FuzzedDataProvider* data_provider,
std::vector<std::unique_ptr<DnsRequest>>* dns_requests) {
std::unique_ptr<DnsRequest> dns_request(
new DnsRequest(host_resolver, data_provider, dns_requests));
if (dns_request->Start() == net::ERR_IO_PENDING)
dns_requests->push_back(std::move(dns_request));
}
// If |dns_requests| is non-empty, waits for a randomly chosen one of the
// requests to complete and removes it from |dns_requests|.
static void WaitForRequestComplete(
net::FuzzedDataProvider* data_provider,
std::vector<std::unique_ptr<DnsRequest>>* dns_requests) {
if (dns_requests->empty())
return;
uint32_t index =
data_provider->ConsumeUint32InRange(0, dns_requests->size() - 1);
// Remove the request from the list before waiting on it - this prevents one
// of the other callbacks from deleting the callback being waited on.
std::unique_ptr<DnsRequest> request = std::move((*dns_requests)[index]);
dns_requests->erase(dns_requests->begin() + index);
request->WaitUntilDone();
}
// If |dns_requests| is non-empty, attempts to cancel a randomly chosen one of
// them and removes it from |dns_requests|. If the one it picks is already
// complete, just removes it from the list.
static void CancelRequest(
net::HostResolver* host_resolver,
net::FuzzedDataProvider* data_provider,
std::vector<std::unique_ptr<DnsRequest>>* dns_requests) {
if (dns_requests->empty())
return;
uint32_t index =
data_provider->ConsumeUint32InRange(0, dns_requests->size() - 1);
auto request = dns_requests->begin() + index;
(*request)->Cancel();
dns_requests->erase(request);
}
private:
void OnCallback(int result) {
CHECK_NE(net::ERR_IO_PENDING, result);
is_running_ = false;
// Remove |this| from |dns_requests| and take ownership of it, if it wasn't
// already removed from the vector. It may have been removed if this is in a
// WaitForRequest call, in which case, do nothing.
std::unique_ptr<DnsRequest> self;
for (auto request = dns_requests_->begin(); request != dns_requests_->end();
++request) {
if (request->get() != this)
continue;
self = std::move(*request);
dns_requests_->erase(request);
break;
}
while (true) {
bool done = false;
switch (data_provider_->ConsumeInt32InRange(0, 2)) {
case 0:
// Quit on 0, or when no data is left.
done = true;
break;
case 1:
CreateRequest(host_resolver_, data_provider_, dns_requests_);
break;
case 2:
CancelRequest(host_resolver_, data_provider_, dns_requests_);
break;
}
if (done)
break;
}
if (run_loop_)
run_loop_->Quit();
}
// Starts the DNS request, using a fuzzed set of parameters.
int Start() {
const char* hostname = data_provider_->PickValueInArray(kHostNames);
net::HostResolver::RequestInfo info(net::HostPortPair(hostname, 80));
info.set_address_family(data_provider_->PickValueInArray(kAddressFamilies));
if (data_provider_->ConsumeBool())
info.set_host_resolver_flags(net::HOST_RESOLVER_CANONNAME);
net::RequestPriority priority =
static_cast<net::RequestPriority>(data_provider_->ConsumeInt32InRange(
net::MINIMUM_PRIORITY, net::MAXIMUM_PRIORITY));
// Decide if should be a cache-only resolution.
if (data_provider_->ConsumeBool()) {
return host_resolver_->ResolveFromCache(info, &address_list_,
net::BoundNetLog());
}
info.set_allow_cached_response(data_provider_->ConsumeBool());
return host_resolver_->Resolve(
info, priority, &address_list_,
base::Bind(&DnsRequest::OnCallback, base::Unretained(this)), &handle_,
net::BoundNetLog());
}
// Waits until the request is done, if it isn't done already.
void WaitUntilDone() {
CHECK(!run_loop_);
if (is_running_) {
run_loop_.reset(new base::RunLoop());
run_loop_->Run();
run_loop_.reset();
CHECK(!is_running_);
}
}
// Cancel the request, if not already completed. Otherwise, does nothing.
void Cancel() {
if (is_running_)
host_resolver_->CancelRequest(handle_);
is_running_ = false;
}
net::HostResolver* host_resolver_;
net::FuzzedDataProvider* data_provider_;
std::vector<std::unique_ptr<DnsRequest>>* dns_requests_;
net::HostResolver::RequestHandle handle_;
net::AddressList address_list_;
bool is_running_;
std::unique_ptr<base::RunLoop> run_loop_;
DISALLOW_COPY_AND_ASSIGN(DnsRequest);
};
} // namespace
// Fuzzer for HostResolverImpl. Fuzzes using both the system resolver and
// built-in DNS client paths.
//
// TODO(mmenke): Add coverage for things this does not cover:
// * Out of order completion, particularly for the platform resolver path.
// * Simulate network changes, including both enabling and disabling the
// async resolver while lookups are active as a result of the change.
extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
{
net::FuzzedDataProvider data_provider(data, size);
net::TestNetLog net_log;
net::HostResolver::Options options;
options.max_concurrent_resolves = data_provider.ConsumeUint32InRange(1, 8);
options.enable_caching = data_provider.ConsumeBool();
net::FuzzedHostResolver host_resolver(options, &net_log, &data_provider);
host_resolver.SetDnsClientEnabled(data_provider.ConsumeBool());
std::vector<std::unique_ptr<DnsRequest>> dns_requests;
while (true) {
switch (data_provider.ConsumeInt32InRange(0, 3)) {
case 0:
// Quit on 0, or when no data is left.
return 0;
case 1:
DnsRequest::CreateRequest(&host_resolver, &data_provider,
&dns_requests);
break;
case 2:
DnsRequest::WaitForRequestComplete(&data_provider, &dns_requests);
break;
case 3:
DnsRequest::CancelRequest(&host_resolver, &data_provider,
&dns_requests);
break;
}
}
}
// Clean up any pending tasks, after deleting everything.
base::RunLoop().RunUntilIdle();
return 0;
}
| 33.008333 | 80 | 0.670412 | [
"vector"
] |
c9d63ace98b03ffe74b982b7e77c4a441eb19a2a | 57,086 | hpp | C++ | mtl/string.hpp | MichaelTrikergiotis/mtl | a761cc28cac50438d2e225c032ab51bdfc6a2e5c | [
"MIT"
] | 5 | 2020-10-29T19:45:34.000Z | 2021-09-02T17:07:46.000Z | examples/mtl/string.hpp | MichaelTrikergiotis/mtl-examples | ac95c85a7d73847a2331da8b54e382b23d8f0a05 | [
"MIT"
] | 1 | 2021-09-19T09:26:55.000Z | 2021-09-19T09:26:55.000Z | examples/mtl/string.hpp | MichaelTrikergiotis/mtl-examples | ac95c85a7d73847a2331da8b54e382b23d8f0a05 | [
"MIT"
] | null | null | null | #pragma once
// string header by Michael Trikergiotis
// 13/10/2017
//
//
// This header contains algorithms used for manipulating strings.
//
//
// Copyright (c) Michael Trikergiotis. All Rights Reserved.
// Licensed under the MIT license. See LICENSE in the project root for license information.
// See ThirdPartyNotices.txt in the project root for third party licenses information.
#include "definitions.hpp" // various definitions
#include <algorithm> // std::copy, std::fill
#include <string> // std::string, std::string::npos
#include <string_view> // std::string_view
#include <cstring> // std::strlen, std::strstr, std::strchr
#include <iterator> // std::iterator_traits, std::next, std::advance, std::distance
#include <utility> // std::pair, std::forward
#include <cmath> // std::floor, std::ceil
#include <vector> // std::vector
#include <array> // std::array
#include <stdexcept> // std::invalid_argument, std::logic_error
#include <cstddef> // std::ptrdiff_t
#include <type_traits> // std::enable_if_t, std::is_same_v, std::remove_cv_t
#include "type_traits.hpp" // mtl::is_std_string_v
#include "container.hpp" // mtl::emplace_back
#include "fmt_include.hpp" // fmt::format, fmt::format_int, fmt::to_string
#include "utility.hpp" // MTL_ASSERT_MSG
namespace mtl
{
namespace string
{
// ================================================================================================
// IS_UPPER - Returns if a character is an uppercase ASCII character.
// IS_UPPER - Returns if all characters in an std::string are uppercase ASCII characters.
// IS_LOWER - Returns if a character is a lowercase ASCII character.
// IS_LOWER - Returns if all characters in an std::string are lowercase ASCII characters.
// ================================================================================================
/// Returns if a character is an uppercase ASCII character.
/// @param[in] character A character to check.
/// @return If the character is an uppercase ASCII character.
[[nodiscard]]
inline bool is_upper(const char character) noexcept
{
int value = static_cast<int>(static_cast<unsigned char>(character));
if ((value >= 65) && (value <= 90))
{
return true;
}
return false;
}
/// Returns if all characters in an std::string are uppercase ASCII characters.
/// @param[in] value An std::string to check.
/// @return If all the characters are uppercase ASCII characters.
[[nodiscard]]
inline bool is_upper(const std::string& value) noexcept
{
for (const char character : value)
{
if (is_upper(character) == false)
{
return false;
}
}
return true;
}
/// Returns if a character is a lowercase ASCII character.
/// @param[in] character A character to check.
/// @return If the character is a lowercase ASCII character.
[[nodiscard]]
inline bool is_lower(const char character) noexcept
{
int value = static_cast<int>(static_cast<unsigned char>(character));
if ((value >= 97) && (value <= 122))
{
return true;
}
return false;
}
/// Returns if all characters in an std::string are lowercase ASCII characters.
/// @param[in] value An std::string to check.
/// @return If all the characters are lowercase ASCII characters.
[[nodiscard]]
inline bool is_lower(const std::string& value) noexcept
{
for (const char character : value)
{
if (is_lower(character) == false)
{
return false;
}
}
return true;
}
// ================================================================================================
// TO_UPPER - Converts a lowercase ASCII character to uppercase.
// TO_UPPER - Converts all lowercase ASCII characters of an std::string to uppercase.
// TO_LOWER - Converts an uppercase ASCII character to lowercase.
// TO_LOWER - Converts all uppercase ASCII characters of an std::string to lowercase.
// ================================================================================================
/// Converts a lowercase ASCII character to uppercase.
/// @param[in, out] character A character to convert to uppercase.
inline void to_upper(char& character) noexcept
{
if (is_lower(character))
{
int value = static_cast<int>(static_cast<unsigned char>(character));
// it so happens that in an ASCII table the uppercase characters are 32 positions before
// lowercase characters
value = value - 32;
character = static_cast<char>(value);
}
}
/// Converts all lowercase ASCII characters in an std::string to uppercase.
/// @param[in, out] value An std::string to convert all it's characters to uppercase.
inline void to_upper(std::string& value) noexcept
{
for (char& character : value)
{
to_upper(character);
}
}
/// Converts an uppercase ASCII character to lowercase.
/// @param[in, out] character A character to convert to lowercase.
inline void to_lower(char& character) noexcept
{
if (is_upper(character))
{
int value = static_cast<int>(static_cast<unsigned char>(character));
// it so happens that in an ASCII table the lowercase characters are 32 positions after
// uppercase characters
value = value + 32;
character = static_cast<char>(value);
}
}
/// Converts all uppercase ASCII characters of an std::string to lowercase characters.
/// @param[in, out] value An std::string to convert all it's characters to lowercase.
inline void to_lower(std::string& value) noexcept
{
for (char& character : value)
{
to_lower(character);
}
}
// ================================================================================================
// IS_ASCII - Returns if char is an ASCII character.
// IS_ASCII - Returns if all characters in an std::string are ASCII characters.
// ================================================================================================
/// Returns if the character is an ASCII character.
/// @param[in] character A character to check.
/// @return If the character is an ASCII character.
[[nodiscard]]
inline bool is_ascii(const char character) noexcept
{
int value = static_cast<int>(static_cast<unsigned char>(character));
// is the value within the ASCII range of characters
if ((value >= 0) && (value <= 127)) // GCOVR_EXCL_LINE
{
return true;
}
return false;
}
/// Returns if all the characters in an std::string are ASCII characters.
/// @param[in] value An std::string to check.
/// @return If all characters of the std::string are ASCII characters.
[[nodiscard]]
inline bool is_ascii(const std::string& value) noexcept
{
for (const char character : value)
{
// check if there are any non-ASCII characters
if (is_ascii(character) == false)
{
return false;
}
}
return true;
}
// ================================================================================================
// IS_ALPHABETIC - Returns if a character / all characters in std::string are ASCII alphabetic
// characters or not.
// IS_NUMERIC - Returns if a character / all characters in std::string are ASCII numbers or not.
// IS_ALPHANUM - Returns if a character / all characters in std::string are ASCII alphanumeric
// characters or not.
// ================================================================================================
/// Returns if a character is an ASCII alphabetic character.
/// @param[in] character A character to check.
/// @return If the character is an ASCII alphabetic character.
[[nodiscard]]
inline bool is_alphabetic(const char character) noexcept
{
int value = static_cast<int>(static_cast<unsigned char>(character));
if (((value >= 65) && (value <= 90)) || ((value >= 97) && (value <= 122)))
{
return true;
}
return false;
}
/// Returns if all characters in an std::string are ASCII alphabetic characters.
/// @param[in] value An std::string to check.
/// @return If all the characters of an std::string are ASCII alphabetic characters.
[[nodiscard]]
inline bool is_alphabetic(const std::string& value) noexcept
{
for (const char character : value)
{
// if the character isn't alphanumeric
if (is_alphabetic(character) == false)
{
return false;
}
}
return true;
}
/// Returns if a character is an ASCII number.
/// @param[in] character A character to check.
/// @return If the character is an ASCII number.
[[nodiscard]]
inline bool is_numeric(const char character) noexcept
{
int value = static_cast<int>(static_cast<unsigned char>(character));
if ((value >= 48) && (value <= 57))
{
return true;
}
return false;
}
/// Returns if all characters in an std::string are ASCII numbers.
/// @param[in] value An std::string to check.
/// @return If all the characters of an std::string are ASCII numeric characters.
[[nodiscard]]
inline bool is_numeric(const std::string& value) noexcept
{
for (const char character : value)
{
// if the character isn't alphanumeric
if (is_numeric(character) == false)
{
return false;
}
}
return true;
}
/// Returns if a character is an ASCII alphabetic or numeric character.
/// @param[in] character A character to check.
/// @return If the character is an ASCII alphanumeric character.
[[nodiscard]]
inline bool is_alphanum(const char character) noexcept
{
if ((is_alphabetic(character)) || (is_numeric(character)))
{
return true;
}
return false;
}
/// Returns if all characters in an std::string are ASCII alphabetic or numeric characters.
/// @param[in] value An std::string to check.
/// @return If all the characters of an std::string are ASCII alphanumeric characters.
[[nodiscard]]
inline bool is_alphanum(const std::string& value) noexcept
{
for (const char character : value)
{
// if the character isn't alphanumeric
if (is_alphanum(character) == false)
{
return false;
}
}
return true;
}
// ================================================================================================
// CONTAINS - Returns if a substring exists within a string.
// ================================================================================================
/// Returns if a substring is found inside the input string or not.
/// @param[in] value An std::string to check for a match.
/// @param[in] match A match to search in the input.
/// @return If the match was found.
[[nodiscard]]
inline bool contains(const std::string& value, const std::string& match)
{
if (value.find(match) != std::string::npos)
{
return true;
}
return false;
}
/// Returns if a substring is found inside the input string or not.
/// @param[in] value An std::string to check for a match.
/// @param[in] match A match to search in the input.
/// @return If the match was found.
[[nodiscard]]
inline bool contains(const std::string& value, const char* match)
{
// handle the case when const char* is nullptr
if(match == nullptr)
{
return false;
}
// search for match
size_t pos = value.find(match);
if (pos != std::string::npos)
{
return true;
}
return false;
}
/// Returns if a char is found inside the input string or not.
/// @param[in] value An std::string to check for a match.
/// @param[in] match A match to search in the input.
/// @return If the match was found.
[[nodiscard]]
inline bool contains(const std::string& value, const char match)
{
if (value.find(match) != std::string::npos)
{
return true;
}
return false;
}
/// Returns if a substring is found inside the input string or not.
/// @param[in] value A const char* to check for a match.
/// @param[in] match A match to search in the input.
/// @return If the match was found.
[[nodiscard]]
inline bool contains(const char* value, const std::string& match)
{
// handle the case when const char* is nullptr
if(value == nullptr)
{
return false;
}
// search for match
const auto pos = std::strstr(value, match.c_str());
if(pos != nullptr)
{
return true;
}
return false;
}
/// Returns if a substring is found inside the input string or not.
/// @param[in] value A const char* to check for a match.
/// @param[in] match A match to search in the input.
/// @return If the match was found.
[[nodiscard]]
inline bool contains(const char* value, const char* match)
{
// handle the case when const char* is nullptr
if((value == nullptr) || (match == nullptr))
{
return false;
}
// search for match
const auto pos = std::strstr(value, match);
if(pos != nullptr)
{
return true;
}
return false;
}
/// Returns if a char is found inside the input string or not.
/// @param[in] value An std::string to check for a match.
/// @param[in] match A match to search in the input.
/// @return If the match was found.
[[nodiscard]]
inline bool contains(const char* value, const char match)
{
// handle the case when const char* is nullptr
if(value == nullptr)
{
return false;
}
if(std::strchr(value, static_cast<int>(match)) != nullptr)
{
return true;
}
return false;
}
// ===============================================================================================
// STRIP_FRONT - Strips all matching characters from the front.
// STRIP_BACK - Strips all matching characters from the back.
// STRIP - Strips all matching characters from the front and back.
// ===============================================================================================
/// Strips all matching characters from the front side of the string. Performs no heap
/// allocation.
/// @param[in, out] value An std::string to strip from the front.
/// @param[in] match An optional character to remove if it matches.
inline void strip_front(std::string& value, const char match = ' ')
{
// count how many characters match
size_t count = 0;
for (const char character : value)
{
if (character != match) { break; }
++count;
}
// if there are no matches leave
if(count == 0)
{
return;
}
// if the number of characters matching are less that the length of the string
if (count < value.size())
{
// remove unwanted characters from the start
value.erase(0, count);
}
// else if the number of characters matching are equal to the length of the string
else
{
value.resize(0);
}
}
/// Strips all matching characters from the back side of the string. Performs no heap
/// allocation.
/// @param[in, out] value An std::string to strip from the back.
/// @param[in] match An optional character to remove if it matches.
inline void strip_back(std::string& value, const char match = ' ')
{
size_t count = 0;
// count how many character match from the end using reverse iterator
for (auto it = value.rbegin(); it != value.rend(); ++it)
{
if (*it != match) { break; }
++count;
}
// remove as many characters as there are matches
value.resize(value.size() - count);
}
/// Strips all matching characters from the front and back side of the string. Performs
/// no heap allocation.
/// @param[in, out] value An std::string to strip from the front and back.
/// @param[in] match An optional character to remove if it matches.
inline void strip(std::string& value, const char match = ' ')
{
// strip the back first so the strip_front has to copy fewer characters
strip_back(value, match);
strip_front(value, match);
}
// ================================================================================================
// PAD_FRONT - Pads a string's front side with a given character for a number of times.
// PAD_FRONT - Pads a string's front side with a given character until it matches another
// string's size.
// PAD_BACK - Pads a string's back side with a given character for a number of times.
// PAD_BACK - Pads a string's back side with a given character until it matches another
// string's size.
// PAD - Pads a string's front and back side with a given character for a number of times
// so it is centered in the middle.
// PAD - Pads a string's front and back side with a given character for a number of times
// until it matches another string's size and is also centered in the middle.
// ================================================================================================
/// Pads a string's front side with a given character for a number of times.
/// @param[in, out] value An std::string to pad to the front.
/// @param[in] times The number of times to perform the pad.
/// @param[in] character An optional character to pad with.
inline void pad_front(std::string& value, const size_t times, const char character = ' ')
{
// keep the original size
const auto old_size = value.size();
// resize the string to fit new characters
value.resize(value.size() + times);
// perform work on the string only if it is of a certain length and larger
if (value.size() > 1)
{
// GCOVR_EXCL_START
using std_string_diff_type = std::string::difference_type;
// iterator to the destination we want
auto dest = std::next(value.begin(), static_cast<std_string_diff_type>(times));
// iterator to the position where the old string ended
auto it_end = std::next(value.begin(), static_cast<std_string_diff_type>(old_size));
// copy the string to the correct position
std::copy(value.begin(), it_end, dest);
// fill the given character to the correct positions
std::fill(value.begin(), dest, character);
// GCOVR_EXCL_STOP
}
}
/// Pads a string's front side with a given character as many number of times is needed
/// to match another string's size.
/// @param[in, out] value An std::string to pad to the front.
/// @param[in] match an std::string to match the size of.
/// @param[in] character An optional character to pad with.
inline void pad_front(std::string& value, const std::string& match, const char character = ' ')
{
// we only want to resize if the target string's size is larger that the size of the string we
// want to match
if (match.size() > value.size())
{
// calculate the difference between the two strings size
const auto difference = match.size() - value.size();
pad_front(value, difference, character);
}
}
/// Pads a string's back side with a given character for a number of times.
/// @param[in, out] value An std::string to pad to the back.
/// @param[in] times The number of times to perform the pad.
/// @param[in] match An optional character to pad with.
/// @param[in] character An optional character to pad with.
inline void pad_back(std::string& value, const size_t times, const char character = ' ')
{
// resizes a string and fills it with a given character, if the string's capacity is large
// enough it may even avoid copying memory
value.resize(value.size() + times, character);
}
/// Pads a string's back side with a given character as many number of times is
/// needed to match another string's size.
/// @param[in, out] value An std::string to pad to the back.
/// @param[in] match an std::string to match the size of.
/// @param[in] character An optional character to pad with.
inline void pad_back(std::string& value, const std::string& match, const char character = ' ')
{
// we only want to perform work if the size of the string we are matching is bigger than the
// input string
if (match.size() > value.size())
{
// calculate the difference between the two strings size
const auto difference = match.size() - value.size();
pad_back(value, difference, character);
}
}
/// Pads a string's front and back side with a given character for a number of times so the string
/// is centered in the middle. The variable times represents how many times it will be padded in
/// total both on the front and on the back side. If more_back is set to true it will prefer to
/// pad the back side more if the times that padding needs to be applied is an odd number.
/// @param[in, out] value An std::string to pad to the front and back.
/// @param[in] times The number of times to perform the pad.
/// @param[in] character An optional character to pad with.
/// @param[in] more_back If there should be more padding to the back side.
inline void pad(std::string& value, const size_t times, const char character = ' ',
bool more_back = false)
{
// if we are padding an empty string for more than 0 times then just use mtl::string::pad_back
if((value.empty()) && (times > 0))
{
mtl::string::pad_back(value, times, character);
return;
}
// perform work only if the string has any character and if the times to pad is larger than 0
if ((value.empty() == false) && (times > 0))
{
// convert to floating point for improved division quality
float back_pad_d = static_cast<float>(times);
// find the middle, we need to divide by 2 but because division is slower than
// multiplication we instead perform division by a constant number using multiplication
back_pad_d = back_pad_d * 0.5f;
// keeps track how many times to pad the back side
size_t back_pad = 0;
// if the more_back is false the padding will be centered but in the in case the padding
// isn't even it will have more padding to the front
if(more_back == false)
{
// round the result and convert it back to an integral number type
back_pad = static_cast<size_t>(std::floor(back_pad_d));
}
// if the more_back is true the padding will be centered but in the in case the padding
// isn't even it will have more padding to the back
else
{
// round the result and convert it back to an integral number type
back_pad = static_cast<size_t>(std::ceil(back_pad_d));
}
// find the times to pad the front
size_t front_pad = times - back_pad;
// pad the front side first because it is slower as it is most likely to copy memory, and
// the string is a smaller size here than it will be in the end
pad_front(value, front_pad, character);
// pad the back
pad_back(value, back_pad, character);
}
}
/// Pads a string to it's front and back with a given character as many number of times is
/// needed to match another string's size and is also centered in the middle. If more_back is set
/// to true it will prefer to pad the back side more if the times that padding needs to be applied
/// is an odd number.
/// @param[in, out] value An std::string to pad to the front and back.
/// @param[in] match an std::string to match the size of.
/// @param[in] character An optional character to pad with.
/// @param[in] more_back If there should be more padding to the back side.
inline void pad(std::string& value, const std::string& match, const char character = ' ',
bool more_back = false)
{
// we only want to perform work if the size of the string we are matching is bigger than the
// input string
if (match.size() > value.size())
{
// calculate the difference between the two strings size
const auto difference = match.size() - value.size();
// pad the string
pad(value, difference, character, more_back);
}
}
// ================================================================================================
// TO_STRING - convert various types to string
// ================================================================================================
/// Converts bool, char, char*, std::string, std::pair and all numeric types to std::string. Also
/// supports user defined types that have the operator<< overloaded for std::ostream.
/// @param[in] value Any type that can be converted to std::string.
/// @return An std::string.
template<typename T>
[[nodiscard]]
inline std::enable_if_t<!mtl::is_number_v<T>, std::string>
to_string(const T& value)
{
return fmt::to_string(value);
}
/// Converts bool, char, char*, std::string, std::pair and all numeric types to std::string. Also
/// supports user defined types that have the operator<< overloaded for std::ostream.
/// @param[in] value Any type that can be converted to std::string.
/// @return An std::string.
template<typename T>
[[nodiscard]]
inline std::enable_if_t<mtl::is_int_v<T>, std::string>
to_string(const T& value)
{
return fmt::format_int(value).str(); // GCOVR_EXCL_LINE
}
/// Converts bool, char, char*, std::string, std::pair and all numeric types to std::string. Also
/// supports user defined types that have the operator<< overloaded for std::ostream.
/// @param[in] value Any type that can be converted to std::string.
/// @return An std::string.
template<typename T>
[[nodiscard]]
inline std::enable_if_t<mtl::is_float_v<T>, std::string>
to_string(const T& value)
{
return fmt::to_string(value);
}
/// Converts bool, char, char*, std::string, std::pair and all numeric types to std::string. Also
/// supports user defined types that have the operator<< overloaded for std::ostream.
/// @param[in] value Any type that can be converted to std::string.
/// @return An std::string.
[[nodiscard]]
inline std::string to_string(const bool value)
{
if(value)
{
return std::string("true"); // GCOVR_EXCL_LINE
}
return std::string("false"); // GCOVR_EXCL_LINE
}
/// Converts bool, char, char*, std::string, std::pair and all numeric types to std::string. Also
/// supports user defined types that have the operator<< overloaded for std::ostream.
/// @param[in] value Any type that can be converted to std::string.
/// @return An std::string.
[[nodiscard]]
inline std::string to_string(const std::string& value)
{
return value;
}
/// Converts bool, char, char*, std::string, std::pair and all numeric types to std::string. Also
/// supports user defined types that have the operator<< overloaded for std::ostream.
/// @param[in] value Any type that can be converted to std::string.
/// @return An std::string.
[[nodiscard]]
inline std::string to_string(const char* value)
{
// if the const char* is nullptr throw because the conversion can't continue
if(value == nullptr)
{
throw std::logic_error("The const char* is nullptr."); // GCOVR_EXCL_LINE
}
return std::string(value); // GCOVR_EXCL_LINE
}
/// Converts bool, char, char*, std::string, std::pair and all numeric types to std::string. Also
/// supports user defined types that have the operator<< overloaded for std::ostream.
/// @param[in] value Any type that can be converted to std::string.
/// @return An std::string.
[[nodiscard]]
inline std::string to_string(const char value)
{
std::string result;
result.push_back(value); // GCOVR_EXCL_LINE
return result;
}
/// Converts bool, char, char*, std::string, std::pair and all numeric types to std::string. Also
/// supports user defined types that have the operator<< overloaded for std::ostream.
/// Specialization for std::pair with extra option that allows to define a delimiter between the
/// two items of the std::pair.
/// @param[in] value Any type that can be converted to std::string.
/// @param[in] delimiter A delimiter that will be used between the pair.
/// @return An std::string.
template<typename T1, typename T2>
[[nodiscard]]
inline std::string to_string(const std::pair<T1, T2>& value, const std::string& delimiter = ", ")
{
// convert the first item of the pair into a string
std::string first_part = mtl::string::to_string(value.first);
// convert the second part of the item into a string
std::string second_part = mtl::string::to_string(value.second);
// create a string to add the two parts together
std::string result;
result.reserve(first_part.size() + second_part.size() + delimiter.size());
// add all the parts together with a delimiter in between them
result += first_part;
result += delimiter;
result += second_part;
return result;
}
// ===============================================================================================
// JOIN_ALL - Join all items from a range (first, last) and return an std::string.
// ===============================================================================================
/// Join all items of a range from first to last with a delimiter. Allows you to specify the
/// output string.
/// @param[in] first Iterator to the start of the range.
/// @param[in] last Iterator to the end of the range.
/// @param[out] result Where the result will be placed.
/// @param[in] delimiter Delimiter to use when joining the elements.
template<typename Iter>
inline std::enable_if_t
<std::is_same_v<std::remove_cv_t<typename std::iterator_traits<Iter>::value_type>, std::string>,
void>
join_all(Iter first, Iter last, std::string& result, const std::string& delimiter)
{
// if there is nothing to join leave the function
if (first == last) { return; } // excluding live from gcovr code coverage, GCOVR_EXCL_LINE
// the size of the delimiter
const size_t delim_size = delimiter.size();
// count total size of all strings in the container plus the delimiter size
size_t total_size = 0;
for (auto it = first; it != last; ++it)
{
total_size += it->size() + delim_size;
}
result.reserve(total_size);
// join the string with a delimiter
if (delim_size > 0)
{
for (auto it = first; it != last; ++it)
{
// GCOVR_EXCL_START
result += *it;
result += delimiter;
// GCOVR_EXCL_STOP
}
// remove as many characters as the delimiter's size because we added one unwanted
// delimiter at the end
result.resize(result.size() - delimiter.size());
}
// join the string without adding the delimiter
else
{
for (auto it = first; it != last; ++it)
{
result += *it; // GCOVR_EXCL_LINE
}
}
}
/// Join all items of a range from first to last with a delimiter. Allows you to specify the output
/// string.
/// @param[in] first Iterator to the start of the range.
/// @param[in] last Iterator to the end of the range.
/// @param[out] result Where the result will be placed.
/// @param[in] delimiter Delimiter to use when joining the elements.
template<typename Iter>
inline std::enable_if_t
<!std::is_same_v<std::remove_cv_t<typename std::iterator_traits<Iter>::value_type>, std::string>,
void>
join_all(Iter first, Iter last, std::string& result, const std::string& delimiter)
{
// if there is nothing to join leave the function
if (first == last) { return; } // excluding live from gcovr code coverage, GCOVR_EXCL_LINE
// the size of the delimiter
const size_t delim_size = delimiter.size();
// GCOVR_EXCL_START
// join the string with a delimiter
if (delim_size > 0)
{
for (auto it = first; it != last; ++it)
{
// convert the element to string and add it
result += mtl::string::to_string(*it);
result += delimiter;
}
// remove as many characters as the delimiter's size because we added one unwanted
// delimiter at the end
result.resize(result.size() - delimiter.size());
}
// join the string without adding the delimiter
else
{
for (auto it = first; it != last; ++it)
{
result += mtl::string::to_string(*it);
}
}
// GCOVR_EXCL_STOP
}
/// Join all items of a range from first to last with a delimiter. Allows you to specify the output
/// string.
/// @param[in] first Iterator to the start of the range.
/// @param[in] last Iterator to the end of the range.
/// @param[out] result Where the result will be placed.
/// @param[in] delimiter Delimiter to use when joining the elements.
template<typename Iter>
inline void join_all(Iter first, Iter last, std::string& result, const char delimiter)
{
// GCOVR_EXCL_START
mtl::string::join_all(first, last, result, mtl::string::to_string(delimiter));
// GCOVR_EXCL_STOP
}
/// Join all items of a range from first to last with a delimiter. Allows you to specify the output
/// string.
/// @param[in] first Iterator to the start of the range.
/// @param[in] last Iterator to the end of the range.
/// @param[out] result Where the result will be placed.
/// @param[in] delimiter Delimiter to use when joining the elements.
template<typename Iter>
inline void join_all(Iter first, Iter last, std::string& result, const char* delimiter)
{
mtl::string::join_all(first, last, result, mtl::string::to_string(delimiter));
}
/// Join all items of a range from first to last with optional delimiter and return an std::string.
/// @param[in] first Iterator to the start of the range.
/// @param[in] last Iterator to the end of the range.
/// @param[in] delimiter Delimiter to use when joining the elements.
/// @return An std::string with all the elements joined together.
template<typename Iter>
[[nodiscard]]
inline std::string join_all(Iter first, Iter last, const std::string& delimiter = "")
{
std::string result;
// use the mtl::string::join_all version where you select the container
mtl::string::join_all(first, last, result, delimiter);
return result;
}
/// Join all items of a range from first to last with a delimiter and return an std::string.
/// @param[in] first Iterator to the start of the range.
/// @param[in] last Iterator to the end of the range.
/// @param[in] delimiter Delimiter to use when joining the elements.
/// @return An std::string with all the elements joined together.
template<typename Iter>
[[nodiscard]]
inline std::string join_all(Iter first, Iter last, const char delimiter)
{
return mtl::string::join_all(first, last, mtl::string::to_string(delimiter));
}
/// Join all items of a range from first to last with a delimiter and return an std::string.
/// @param[in] first Iterator to the start of the range.
/// @param[in] last Iterator to the end of the range.
/// @param[in] delimiter Delimiter to use when joining the elements.
/// @return An std::string with all the elements joined together.
template<typename Iter>
[[nodiscard]]
inline std::string join_all(Iter first, Iter last, const char* delimiter)
{
return mtl::string::join_all(first, last, mtl::string::to_string(delimiter));
}
// ===============================================================================================
// JOIN - Joins one or more items of various types and return an std::string
// ===============================================================================================
namespace detail
{
// Actual implementation for variadic template join.
template<typename Type>
inline void join_impl(std::string& value, const Type& type)
{
value += mtl::string::to_string(type); // GCOVR_EXCL_LINE
}
// Actual implementation for variadic template join.
template<typename Type, typename... Args>
inline void join_impl(std::string& value, const Type& type, Args&&... args)
{
join_impl(value, type);
join_impl(value, std::forward<Args>(args)...);
}
// Count size for std::string.
inline void count_size_impl(size_t& size, const std::string& type)
{
size += type.size();
}
// Count size for const char*.
inline void count_size_impl(size_t& size, const char* type)
{
// make sure the const char* is not nullptr before trying to find the length
if(type != nullptr)
{
// std::strlen doesn't count the null terminator \0 which is what we want since it will
// not be included in the resulting string when const char* is concatenated
size += std::strlen(type);
}
}
// Count size for bool.
inline void count_size_impl(size_t& size, const bool type)
{
if(type)
{
size += 4;
}
else
{
size += 5;
}
}
// Count size for int. This is intentionally empty and also declared so integer are not implicitly
// converted to chars and to stop warnings about integer conversion.
inline void count_size_impl(size_t&, const int)
{
}
// Count size for char.
inline void count_size_impl(size_t& size, const char)
{
size += 1;
}
// Count size for std::pair.
template<typename Type1, typename Type2>
inline void count_size_impl(size_t& size, const std::pair<Type1, Type2>& type)
{
count_size_impl(size, type.first);
count_size_impl(size, type.second);
// add 2 characters because when std::pair is converted to string with mtl::string::to_string
// there is a two character delimiter added between the items by default
size += 2;
}
// Count size for all non-specialize types. Do not remove.
template<typename Type>
inline void count_size_impl(size_t&, const Type&)
{
// For non-specialized types the count is 0. All modern compilers with high optimization
// settings will turn this function into a NOOP.
}
// Variadic template that counts the number of characters for std::string, const char*, char and
// std::pair found in the arguments. All other types are not counted.
template<typename Type, typename... Args>
inline void count_size_impl(size_t& size, const Type& type, Args&&... args)
{
count_size_impl(size, type);
count_size_impl(size, std::forward<Args>(args)...);
}
// Variadic join implementation with the ability to reserve space to avoid allocations.
template<typename Type, typename... Args>
[[nodiscard]]
inline std::string join_select_impl(const Type& type, Args&&... args)
{
size_t size = 0;
// count the number of characters of types that can be counted like std::string, const char*
// and char so we can reserve the std::string's size
count_size_impl(size, type, args...);
std::string result;
result.reserve(size);
join_impl(result, type, std::forward<Args>(args)...);
return result;
}
} // namespace detail end
/// Join one or more elements of any type to an std::string.
/// @param[in] type An item to join.
/// @return An std::string with all the items joined together.
template<typename Type>
[[nodiscard]]
inline std::string join(const Type& type)
{
return mtl::string::to_string(type);
}
/// Join one or more elements of any type to an std::string.
/// @param[in] type An item to join.
/// @param[in] args Any number of items to join.
/// @return An std::string with all the items joined together.
template<typename Type, typename... Args>
[[nodiscard]]
inline std::string join(const Type& type, Args&&... args)
{
return mtl::string::detail::join_select_impl(type, std::forward<Args>(args)...);
}
// ===============================================================================================
// SPLIT - Splits a string into tokens with a given delimiter.
// ===============================================================================================
/// Splits a string into tokens with a delimiter. Gives the ability to select the type of container
/// to be used as output and even allows you to reserve memory for it, if it supports reserve.
/// The element type of the container has to be std::string.
/// @param[in] value The std::string to split.
/// @param[out] result The container where all the parts will be placed. The element for the
/// container has to be std::string. You can use reserve.
/// @param[in] delimiter A delimiter that will be used to identify where to split.
template<typename Container>
inline void split(const std::string& value, Container& result, const std::string& delimiter)
{
// if the input string is empty do nothing and return
if (value.empty())
{
return;
}
// if the delimiter is empty add the entire input to the container and return
if(delimiter.empty())
{
mtl::emplace_back(result, value);
return;
}
// the size of the container before we start modifying it
const auto original_size = result.size();
// remember the starting position
size_t start = 0;
// position of the first match
size_t match_pos = value.find(delimiter);
// keep the position for the last item
size_t last_pos = 0;
// add all tokens to the container except the last one
while (match_pos != std::string::npos)
{
last_pos = match_pos;
// everything is fine add the token to the container
const std::string_view token(value.data() + start, match_pos - start);
mtl::emplace_back(result, token);
// set the a new starting position
start = match_pos + delimiter.size();
// find a new position in the input string if there are any matches left
match_pos = value.find(delimiter, start);
}
// how much we added to the container
const auto size_difference = result.size() - original_size;
// if container changed size it means there are tokens in the output
if(size_difference > 0)
{
// add the last item using the last position
const std::string_view token(value.data() + (last_pos + delimiter.size()));
mtl::emplace_back(result, token);
}
// if the container's size didn't change at all then add the entire input string because it
// means there are no places that it needs to be split
if (size_difference == 0) { mtl::emplace_back(result, value); }
}
/// Splits a string into tokens with a delimiter. Gives the ability to select the type of container
/// to be used as output and even allows you to reserve memory for it, if it supports reserve.
/// The element type of the container has to be std::string.
/// @param[in] value The std::string to split.
/// @param[out] result The container where all the parts will be placed. The element of the
/// container has to be std::string. You can use reserve.
/// @param[in] delimiter A delimiter that will be used to identify where to split.
template<typename Container>
inline void split(const std::string& value, Container& result, const char delimiter)
{
mtl::string::split(value, result, mtl::string::to_string(delimiter)); // GCOVR_EXCL_LINE
}
/// Splits a string into tokens with a delimiter. Gives the ability to select the type of container
/// to be used as output and even allows you to reserve memory for it, if it supports reserve.
/// The element type of the container has to be std::string.
/// @param[in] value The std::string to split.
/// @param[out] result The container where all the parts will be placed. The element of the
/// container has to be std::string. You can use reserve.
/// @param[in] delimiter A delimiter that will be used to identify where to split.
template<typename Container>
inline void split(const std::string& value, Container& result, const char* delimiter)
{
mtl::string::split(value, result, mtl::string::to_string(delimiter));
}
/// Splits a string into tokens with an optional delimiter.
/// @param[in] value The std::string to split.
/// @param[in] delimiter An optional delimiter that will be used to identify where to split.
/// @return An std::vector of std::string that holds all the parts.
[[nodiscard]]
inline std::vector<std::string> split(const std::string& value, const std::string& delimiter = " ")
{
std::vector<std::string> result;
// use the split version where you select the container type to avoid code duplication
mtl::string::split(value, result, delimiter);
return result;
}
/// Splits a string into tokens with a delimiter.
/// @param[in] value The std::string to split.
/// @param[in] delimiter A delimiter that will be used to identify where to split.
/// @return An std::vector of std::string that holds all the parts.
[[nodiscard]]
inline std::vector<std::string> split(const std::string& value, const char delimiter)
{
return mtl::string::split(value, mtl::string::to_string(delimiter));
}
/// Splits a string into tokens with a delimiter.
/// @param[in] value The std::string to split.
/// @param[in] delimiter A delimiter that will be used to identify where to split.
/// @return An std::vector of std::string that holds all the parts.
[[nodiscard]]
inline std::vector<std::string> split(const std::string& value, const char* delimiter)
{
return mtl::string::split(value, mtl::string::to_string(delimiter));
}
// ================================================================================================
// REPLACE - Replaces all places in the input string where a match is found with
// the replacement std::string / char* / char.
// ================================================================================================
namespace detail
{
// Replaces all places in the input std::string where a match is found with the replacement
// std::string. Version specialized for handling short strings much faster.
inline void replace_short(std::string& value, const std::string& match,
const std::string& replacement)
{
size_t pos = 0;
while ((pos = value.find(match, pos)) != std::string::npos)
{
value.replace(pos, match.size(), replacement);
pos += replacement.size();
}
}
// Replaces all places in the input std::string where a match is found with the replacement
// std::string. Version specialized for handling long strings faster but is even more specialized
// than mtl::string::replace_long to be called only after the stack array is full and we have to
// start using heap allocations for keeping track of the positions where matches were found.
inline void replace_long_heap(std::string& value, const std::string& match,
const std::string& replacement,
const std::array<size_t, 20>& found_positions,
const size_t starting_position)
{
// GCOVR_EXCL_START
std::vector<size_t> positions(found_positions.begin(), found_positions.end());
// GCOVR_EXCL_STOP
size_t pos = starting_position;
// find all matches and keep their index
while ((pos = value.find(match, pos)) != std::string::npos)
{
positions.emplace_back(pos); // GCOVR_EXCL_LINE
// move the position forward enough so we don't match the same thing again
pos += match.size();
}
std::string result;
size_t difference = 0;
// if what we replace is larger than the match then it is easy
if (replacement.size() >= match.size())
{
difference = value.size() + (positions.size() * (replacement.size() - match.size()));
}
// if what we replace is smaller than the match then we have to convert numbers to a
// signed integer type so we can accept negative numbers
else
{
// turn size_t to int64_t
int64_t positions_size = static_cast<int64_t>(positions.size());
int64_t replacement_size = static_cast<int64_t>(replacement.size());
int64_t match_size = static_cast<int64_t>(match.size());
// this value will never be negative
int64_t diff = positions_size * (match_size - replacement_size);
// after this calculation the number can never be negative as the input string size is
// always larger as we have checked for this before
diff = static_cast<int64_t>(value.size()) - diff;
#ifndef MTL_DISABLE_SOME_ASSERTS
MTL_ASSERT_MSG(diff >= 0,
"The number can't be negative. mtl::string::detail::replace_long contains errors.");
#endif // MTL_DISABLE_SOME_ASSERTS end
// convert to size_t with no problems as this can't be negative
difference = static_cast<size_t>(diff);
}
// resize to avoid unnecessary allocations
result.resize(difference); // GCOVR_EXCL_LINE
// create various iterators
const auto beginning = value.begin();
auto it_begin = value.begin();
auto it_end = value.begin();
auto it_output = result.begin();
for (const auto position : positions)
{
// GCOVR_EXCL_START
// copies parts to output string and moves the iterators along
it_end = std::next(beginning, static_cast<std::ptrdiff_t>(position));
std::copy(it_begin, it_end, it_output);
std::advance(it_output, std::distance(it_begin, it_end));
std::copy(replacement.begin(), replacement.end(), it_output);
std::advance(it_output, static_cast<std::ptrdiff_t>(replacement.size()));
it_begin = std::next(it_end, static_cast<std::ptrdiff_t>(match.size()));
// GCOVR_EXCL_STOP
}
// copy from the last match to the end
std::copy(it_begin, value.end(), it_output); // GCOVR_EXCL_LINE
// copy the result to the input string
value = result; // GCOVR_EXCL_LINE
}
// Replaces all places in the input std::string where a match is found with the replacement
// std::string. Version specialized for handling long strings much faster.
inline void replace_long(std::string& value, const std::string& match,
const std::string& replacement)
{
// if input size is smaller than match then do nothing, this covers the cases where input size
// is 0
if (value.size() < match.size())
{
return;
}
// set the maximum size of items for our stack array
constexpr size_t max_size = 20;
// create an array on the stack to avoid heap allocations, the array will usually be larger
// than the amount of positions found, if the positions fill the array we call an algorithm
// where we use the heap and can track more positions
std::array<size_t, max_size> positions {};
// this number keeps track of the number of positions found to match
size_t num_matches = 0;
size_t pos = 0;
// find all matches and keep their index
while ((pos = value.find(match, pos)) != std::string::npos)
{
// if the array can't hold more items start using the heap instead of the stack
if (num_matches == max_size)
{
replace_long_heap(value, match, replacement, positions, pos); // GCOVR_EXCL_LINE
return;
}
// store the position where a match was found
positions[num_matches] = pos;
++num_matches;
// move the position forward enough so we don't match the same thing again
pos += match.size();
}
// if nothing is found leave
if (num_matches == 0) { return; }
std::string result;
size_t difference = 0;
// if what we replace is larger than the match then it is easy
if (replacement.size() >= match.size())
{
difference = value.size() + (num_matches * (replacement.size() - match.size()));
}
// if what we replace is smaller than the match then we have to convert numbers to a
// signed integer type so we can accept negative numbers
else
{
// turn size_t to int64_t
int64_t positions_size = static_cast<int64_t>(num_matches);
int64_t replacement_size = static_cast<int64_t>(replacement.size());
int64_t match_size = static_cast<int64_t>(match.size());
// this value will never be negative
int64_t diff = positions_size * (match_size - replacement_size);
// after this calculation the number can never be negative as the input size is always
// larger, we have checked for this before
diff = static_cast<int64_t>(value.size()) - diff;
#ifndef MTL_DISABLE_SOME_ASSERTS
MTL_ASSERT_MSG(diff >= 0,
"The number can't be negative. mtl::string::detail::replace_long contains errors.");
#endif // MTL_DISABLE_SOME_ASSERTS end
// convert to size_t with no problems as this can't be negative
difference = static_cast<size_t>(diff);
}
// resize to avoid unnecessary allocations
result.resize(difference); // GCOVR_EXCL_LINE
// create various iterators
const auto beginning = value.begin();
auto it_begin = value.begin();
auto it_end = value.begin();
auto it_output = result.begin();
// loop over the actual number of positions found and not the size of the array
for (size_t i = 0; i < num_matches; ++i)
{
// GCOVR_EXCL_START
// copies parts to output string and moves the iterators along
it_end = std::next(beginning, static_cast<std::ptrdiff_t>(positions[i]));
std::copy(it_begin, it_end, it_output);
std::advance(it_output, std::distance(it_begin, it_end));
std::copy(replacement.begin(), replacement.end(), it_output);
std::advance(it_output, static_cast<std::ptrdiff_t>(replacement.size()));
it_begin = std::next(it_end, static_cast<std::ptrdiff_t>(match.size()));
// GCOVR_EXCL_STOP
}
// copy from the last match to the end
std::copy(it_begin, value.end(), it_output); // GCOVR_EXCL_LINE
// copy the result to the input string
value = result; // GCOVR_EXCL_LINE
}
} // namespace detail end
/// Replaces all places in the input where a match is found with the replacement.
/// @param[in, out] value An std::string to replace parts that match with a replacement.
/// @param[in] match A match to search for.
/// @param[in] replacement A replacement to replace the matches with.
inline void replace(std::string& value, const std::string& match, const std::string& replacement)
{
// if the string is relatively short use the algorithm for short strings
if (value.size() < 350)
{
mtl::string::detail::replace_short(value, match, replacement);
}
// for longer strings there is another algorithm that is benchmarked and proven faster
else
{
mtl::string::detail::replace_long(value, match, replacement);
}
}
/// Replaces all places in the input where a match is found with the replacement.
/// @param[in, out] value An std::string to replace parts that match with a replacement.
/// @param[in] match A match to search for.
/// @param[in] replacement A replacement to replace the matches with.
inline void replace(std::string& value, const std::string& match, const char replacement)
{
replace(value, match, mtl::string::to_string(replacement));
}
/// Replaces all places in the input where a match is found with the replacement.
/// @param[in, out] value An std::string to replace parts that match with a replacement.
/// @param[in] match A match to search for.
/// @param[in] replacement A replacement to replace the matches with.
inline void replace(std::string& value, const std::string& match, const char* replacement)
{
replace(value, match, mtl::string::to_string(replacement));
}
/// Replaces all places in the input where a match is found with the replacement.
/// @param[in, out] value An std::string to replace parts that match with a replacement.
/// @param[in] match A match to search for.
/// @param[in] replacement A replacement to replace the matches with.
inline void replace(std::string& value, const char match, const std::string& replacement)
{
replace(value, mtl::string::to_string(match), replacement);
}
/// Replaces all places in the input where a match is found with the replacement.
/// @param[in, out] value An std::string to replace parts that match with a replacement.
/// @param[in] match A match to search for.
/// @param[in] replacement A replacement to replace the matches with.
inline void replace(std::string& value, const char match, const char replacement)
{
for(char& character : value)
{
if(character == match)
{
character = replacement;
}
}
}
/// Replaces all places in the input where a match is found with the replacement.
/// @param[in, out] value An std::string to replace parts that match with a replacement.
/// @param[in] match A match to search for.
/// @param[in] replacement A replacement to replace the matches with.
inline void replace(std::string& value, const char match, const char* replacement)
{
replace(value, mtl::string::to_string(match), mtl::string::to_string(replacement));
}
/// Replaces all places in the input where a match is found with the replacement.
/// @param[in, out] value An std::string to replace parts that match with a replacement.
/// @param[in] match A match to search for.
/// @param[in] replacement A replacement to replace the matches with.
inline void replace(std::string& value, const char* match, const std::string& replacement)
{
replace(value, mtl::string::to_string(match), replacement);
}
/// Replaces all places in the input where a match is found with the replacement.
/// @param[in, out] value An std::string to replace parts that match with a replacement.
/// @param[in] match A match to search for.
/// @param[in] replacement A replacement to replace the matches with.
inline void replace(std::string& value, const char* match, const char replacement)
{
// GCOVR_EXCL_START
replace(value, mtl::string::to_string(match), mtl::string::to_string(replacement));
// GCOVR_EXCL_STOP
}
/// Replaces all places in the input where a match is found with the replacement.
/// @param[in, out] value An std::string to replace parts that match with a replacement.
/// @param[in] match A match to search for.
/// @param[in] replacement A replacement to replace the matches with.
inline void replace(std::string& value, const char* match, const char* replacement)
{
replace(value, mtl::string::to_string(match), mtl::string::to_string(replacement));
}
// ================================================================================================
// REPLACE_ALL - Replaces all matches in the input with all the replacements.
// ================================================================================================
/// Replaces all places in the input where a match is found with the replacement. The process is
/// repeated for all matches in the matches container replacing them with all replacements from the
/// replacement container. If the number of elements for the provided containers isn't the same it
/// throws std::invalid_argument. The element type for both containers should be std::string.
/// @param[in, out] value An std::string to replace parts that match with a replacement.
/// @param[in] match A container of std::string matches to search for.
/// @param[in] replacement A container of std::string to replace the matches with.
template<typename ContainerMatches, typename ContainerReplacements>
inline
std::enable_if_t
<mtl::is_std_string_v<typename ContainerMatches::value_type> &&
mtl::is_std_string_v<typename ContainerReplacements::value_type>, void>
replace_all(std::string& value, const ContainerMatches& container_matches,
const ContainerReplacements& container_replacements)
{
// cache size values
const auto matches_size = container_matches.size();
const auto replacements_size = container_replacements.size();
// check that the both containers are the same size
if(matches_size != replacements_size)
{
throw std::invalid_argument(
"mtl::string::replace_all requires the containers to be the same size.");
}
// just run mtl::string::replace for each item in each container
for(size_t i = 0; i < matches_size; ++i)
{
mtl::string::replace(value, container_matches[i], container_replacements[i]);
}
}
} // namespace string end
} // namespace mtl end
| 35.567601 | 99 | 0.680692 | [
"vector"
] |
c9d79715ce22817c9961f0ff10ec87b1878b27f7 | 14,291 | cpp | C++ | src/qt/~~askpassphrasedialog.cpp | artboomerangwin/artboomerang | 86c507b803a6a7c34d9da663fea19b936e70cc27 | [
"MIT"
] | null | null | null | src/qt/~~askpassphrasedialog.cpp | artboomerangwin/artboomerang | 86c507b803a6a7c34d9da663fea19b936e70cc27 | [
"MIT"
] | null | null | null | src/qt/~~askpassphrasedialog.cpp | artboomerangwin/artboomerang | 86c507b803a6a7c34d9da663fea19b936e70cc27 | [
"MIT"
] | null | null | null | #include "askpassphrasedialog.h"
#include "ui_askpassphrasedialog.h"
#include "guiconstants.h"
#include "walletmodel.h"
#include <QMessageBox>
#include <QPushButton>
#include <QKeyEvent>
#include <QBitmap>
#include <QDebug>
extern bool fWalletUnlockStakingOnly;
AskPassphraseDialog::AskPassphraseDialog(Mode mode, QWidget *parent, BitScreen *screen) :
QDialog(parent),
screen(screen),
ui(new Ui::AskPassphraseDialog),
mode(mode),
model(0),
fCapsLock(false)
{
ui->setupUi(this);
ui->capsLabel->hide();
ui->passEdit1->setMaxLength(MAX_PASSPHRASE_SIZE);
ui->passEdit2->setMaxLength(MAX_PASSPHRASE_SIZE);
ui->passEdit3->setMaxLength(MAX_PASSPHRASE_SIZE);
// Setup Caps Lock detection.
ui->passEdit1->installEventFilter(this);
ui->passEdit2->installEventFilter(this);
ui->passEdit3->installEventFilter(this);
ui->stakingCheckBox->setChecked(fWalletUnlockStakingOnly);
switch(mode)
{
case Encrypt: // Ask passphrase x2
ui->passLabel1->hide();
ui->passEdit1->hide();
ui->warningLabel->setText(tr("Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>."));
setWindowTitle(tr("Encrypt wallet"));
break;
case UnlockStaking:
ui->stakingCheckBox->setChecked(true);
ui->stakingCheckBox->show();
// fallthru
case Unlock: // Ask passphrase
ui->warningLabel->setText(tr("This operation needs your wallet passphrase to unlock the wallet."));
ui->passLabel2->hide();
ui->passEdit2->hide();
ui->passLabel3->hide();
ui->passEdit3->hide();
setWindowTitle(tr("Unlock wallet"));
break;
case Decrypt: // Ask passphrase
ui->warningLabel->setText(tr("This operation needs your wallet passphrase to decrypt the wallet."));
ui->passLabel2->hide();
ui->passEdit2->hide();
ui->passLabel3->hide();
ui->passEdit3->hide();
setWindowTitle(tr("Decrypt wallet"));
break;
case ChangePass: // Ask old passphrase + new passphrase x2
setWindowTitle(tr("Change passphrase"));
ui->warningLabel->setText(tr("Enter the old and new passphrase to the wallet."));
break;
}
textChanged();
connect(ui->passEdit1, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
connect(ui->passEdit2, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
connect(ui->passEdit3, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
#ifdef USE_FULLSCREEN
screenOrientationChanged();
connect(this->screen, SIGNAL(orientationChanged(Qt::ScreenOrientation)), this, SLOT(screenOrientationChanged()));
setStyleSheet("QDialog {border: 2px solid grey;}");
ActionBar *actionBar =new ActionBar(this);
QAction *closeAction = new QAction(QIcon(":/android_icons/action_close"), tr("&Close"), this);
connect(closeAction, SIGNAL(triggered()), this, SLOT(close()));
actionBar->addButton(closeAction);
ui->actionBarLayout->addWidget(actionBar);
actionBar->setTitle(windowTitle(), false);
//setWindowFlags(Qt::Popup | Qt::WindowStaysOnTopHint);
//overrideWindowFlags(Qt::Dialog | Qt::MSWindowsFixedSizeDialogHint | Qt::WindowTitleHint | Qt::WindowType_Mask);
// QDialog::setWindowModality(Qt::WindowModal);
//setParent(parentWidget(), Qt::Sheet);
// setParent(parent, Qt::Sheet);
// QPixmap pix(":/icons/bitcoin"); // ":/images/myimage" - without .PNG;
// label->setPixmap( pix.scaled(iconSize().width(),iconSize().height(), Qt::KeepAspectRatio));
QBitmap pix = QBitmap(screen->size());
pix.fill(Qt::black);//pix.
//setParent(0);
// parent->QDialog
/* QWidget *d = new QWidget(parent, Qt::WindowType_Mask);
d->setStyleSheet("* {background:#000000;}");
// d->setMask(pix.createMaskFromColor(QColor(0, 0, 0, 0), Qt::MaskOutColor));//screen->geometry()
// d->setAutoFillBackground(false);
// QPixmap pixmap = QPixmap::grabWidget(d);
// d->setMask(pixmap.createHeuristicMask());
d->setWindowFlags(Qt::Widget | Qt::FramelessWindowHint);
d->setWindowOpacity(0.5);
// d->setParent(0); // Create TopLevel-Widget
// d->setAttribute(Qt::WA_NoSystemBackground, true);
d->setAttribute(Qt::WA_TranslucentBackground, true);
// d->setAttribute(Qt::WA_PaintOnScreen);
d->resize(screen->size()); d->move(0,0);
d->showMaximized();
*/
// qDebug()<< parent->mask();
// QPixmap pixmap = QPixmap::grabWidget(parent);
// parent->setMask(pixmap.createHeuristicMask());
// parent->setMask(pix.createMaskFromColor(QColor(0, 0, 0, 0), Qt::MaskOutColor));
// qDebug()<< parent->mask();
//QWidget::showMaximized()
// this->setAutoFillBackground(true);
//this->setParent(d);
// setMask(pix.createMaskFromColor(QColor(0, 0, 0, 0), Qt::MaskOutColor));//screen->geometry()
// QWidget *myWidget = new QWhateverWidget();
// this->setAutoFillBackground(false);
// QPixmap pixmap = QPixmap::grabWidget(this);
// this->setMask(pixmap.createHeuristicMask());
// parent->createMaskFromColor(QColor(0, 0, 0, 0));
//createMaskFromColor(QColor(0, 0, 0, 0), Qt::MaskInColor);//MaskInColor, MaskOutColor
//setMask(QBitmap(size()).fill(Qt::black));//screen->geometry()
// setWindowFlags(Qt::WindowStaysOnTopHint);
//setWindowFlags(Qt::FramelessWindowHint|Qt::WindowStaysOnTopHint);
// setAttribute(Qt::WA_TranslucentBackground);
// setStyleSheet("background:transparent;");
#endif
}
AskPassphraseDialog::~AskPassphraseDialog()
{
secureClearPassFields();
delete ui;
}
void AskPassphraseDialog::screenOrientationChanged()
{
screen->adjustPopupDialogSize(this, true);
screen->adjustPopupDialogButtonsSize(this, ui->buttonBox);
/*
* ui->buttonBox->setFixedWidth(this->width()-this->layout()->contentsMargins().left()-this->layout()->contentsMargins().right());
int w = this->width()-this->layout()->contentsMargins().left()-this->layout()->contentsMargins().right()
-ui->buttonBox->layout()->contentsMargins().left()-ui->buttonBox->layout()->contentsMargins().right();
int cnt = ui->buttonBox->buttons().size();
int bw = ((w/cnt)-(6*cnt)); // width/num buttons - numbtn*btn spacing
foreach(QAbstractButton *p, ui->buttonBox->buttons())
{
p->setMinimumWidth( bw );
}
ui->buttonBox->setCenterButtons(true);
*/
}
void AskPassphraseDialog::setModel(WalletModel *model)
{
this->model = model;
}
void AskPassphraseDialog::accept()
{
SecureString oldpass, newpass1, newpass2;
if(!model)
return;
oldpass.reserve(MAX_PASSPHRASE_SIZE);
newpass1.reserve(MAX_PASSPHRASE_SIZE);
newpass2.reserve(MAX_PASSPHRASE_SIZE);
// TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
// Alternately, find a way to make this input mlock()'d to begin with.
oldpass.assign(ui->passEdit1->text().toStdString().c_str());
newpass1.assign(ui->passEdit2->text().toStdString().c_str());
newpass2.assign(ui->passEdit3->text().toStdString().c_str());
secureClearPassFields();
switch(mode)
{
case Encrypt: {
if(newpass1.empty() || newpass2.empty())
{
// Cannot encrypt with empty passphrase
break;
}
QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm wallet encryption"),
tr("Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR COINS</b>!") + "<br><br>" + tr("Are you sure you wish to encrypt your wallet?"),
QMessageBox::Yes|QMessageBox::Cancel,
QMessageBox::Cancel);
if(retval == QMessageBox::Yes)
{
if(newpass1 == newpass2)
{
if(model->setWalletEncrypted(true, newpass1))
{
QMessageBox::warning(this, tr("Wallet encrypted"),
"<qt>" +
tr("ArtBoomerang will close now to finish the encryption process. "
"Remember that encrypting your wallet cannot fully protect "
"your coins from being stolen by malware infecting your computer.") +
"<br><br><b>" +
tr("IMPORTANT: Any previous backups you have made of your wallet file "
"should be replaced with the newly generated, encrypted wallet file. "
"For security reasons, previous backups of the unencrypted wallet file "
"will become useless as soon as you start using the new, encrypted wallet.") +
"</b></qt>");
QApplication::quit();
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("Wallet encryption failed due to an internal error. Your wallet was not encrypted."));
}
QDialog::accept(); // Success
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("The supplied passphrases do not match."));
}
}
else
{
QDialog::reject(); // Cancelled
}
} break;
case UnlockStaking:
case Unlock:
if(!model->setWalletLocked(false, oldpass))
{
QMessageBox::critical(this, tr("Wallet unlock failed"),
tr("The passphrase entered for the wallet decryption was incorrect."));
}
else
{
fWalletUnlockStakingOnly = ui->stakingCheckBox->isChecked();
QDialog::accept(); // Success
}
break;
case Decrypt:
if(!model->setWalletEncrypted(false, oldpass))
{
QMessageBox::critical(this, tr("Wallet decryption failed"),
tr("The passphrase entered for the wallet decryption was incorrect."));
}
else
{
QDialog::accept(); // Success
}
break;
case ChangePass:
if(newpass1 == newpass2)
{
if(model->changePassphrase(oldpass, newpass1))
{
QMessageBox::information(this, tr("Wallet encrypted"),
tr("Wallet passphrase was successfully changed."));
QDialog::accept(); // Success
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("The passphrase entered for the wallet decryption was incorrect."));
}
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("The supplied passphrases do not match."));
}
break;
}
}
void AskPassphraseDialog::textChanged()
{
// Validate input, set Ok button to enabled when acceptable
bool acceptable = false;
switch(mode)
{
case Encrypt: // New passphrase x2
acceptable = !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty();
break;
case UnlockStaking:
case Unlock: // Old passphrase x1
case Decrypt:
acceptable = !ui->passEdit1->text().isEmpty();
break;
case ChangePass: // Old passphrase x1, new passphrase x2
acceptable = !ui->passEdit1->text().isEmpty() && !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty();
break;
}
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(acceptable);
}
bool AskPassphraseDialog::event(QEvent *event)
{
// Detect Caps Lock key press.
if (event->type() == QEvent::KeyPress) {
QKeyEvent *ke = static_cast<QKeyEvent *>(event);
if (ke->key() == Qt::Key_CapsLock) {
fCapsLock = !fCapsLock;
}
if (fCapsLock) {
ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!"));
ui->capsLabel->show();
} else {
ui->capsLabel->clear();
ui->capsLabel->hide();
}
}
return QWidget::event(event);
}
bool AskPassphraseDialog::eventFilter(QObject *object, QEvent *event)
{
/* Detect Caps Lock.
* There is no good OS-independent way to check a key state in Qt, but we
* can detect Caps Lock by checking for the following condition:
* Shift key is down and the result is a lower case character, or
* Shift key is not down and the result is an upper case character.
*/
if (event->type() == QEvent::KeyPress) {
QKeyEvent *ke = static_cast<QKeyEvent *>(event);
QString str = ke->text();
if (str.length() != 0) {
const QChar *psz = str.unicode();
bool fShift = (ke->modifiers() & Qt::ShiftModifier) != 0;
if ((fShift && psz->isLower()) || (!fShift && psz->isUpper())) {
fCapsLock = true;
ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!"));
} else if (psz->isLetter()) {
fCapsLock = false;
ui->capsLabel->clear();
}
}
}
return QDialog::eventFilter(object, event);
}
void AskPassphraseDialog::secureClearPassFields()
{
// Attempt to overwrite text so that they do not linger around in memory
ui->passEdit1->setText(QString(" ").repeated(ui->passEdit1->text().size()));
ui->passEdit2->setText(QString(" ").repeated(ui->passEdit2->text().size()));
ui->passEdit3->setText(QString(" ").repeated(ui->passEdit3->text().size()));
ui->passEdit1->clear();
ui->passEdit2->clear();
ui->passEdit3->clear();
}
| 40.143258 | 192 | 0.590162 | [
"geometry",
"object",
"model",
"solid"
] |
c9d85ed48ce75ad6188b03a174ca17421643af98 | 40,215 | cpp | C++ | ugene/src/plugins/query_designer/src/QueryViewController.cpp | iganna/lspec | c75cba3e4fa9a46abeecbf31b5d467827cf4fec0 | [
"MIT"
] | null | null | null | ugene/src/plugins/query_designer/src/QueryViewController.cpp | iganna/lspec | c75cba3e4fa9a46abeecbf31b5d467827cf4fec0 | [
"MIT"
] | null | null | null | ugene/src/plugins/query_designer/src/QueryViewController.cpp | iganna/lspec | c75cba3e4fa9a46abeecbf31b5d467827cf4fec0 | [
"MIT"
] | null | null | null | /**
* UGENE - Integrated Bioinformatics Tools.
* Copyright (C) 2008-2012 UniPro <ugene@unipro.ru>
* http://ugene.unipro.ru
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#include "QueryViewController.h"
#include "QueryViewItems.h"
#include "QueryPalette.h"
#include "QDSamples.h"
#include "QueryEditor.h"
#include "QDSceneIOTasks.h"
#include "QDRunDialog.h"
#include "QDGroupsEditor.h"
#include <U2Core/Log.h>
#include <U2Core/L10n.h>
#include <U2Core/Counter.h>
#include <U2Core/AppContext.h>
#include <U2Core/Settings.h>
#include <U2Core/TaskSignalMapper.h>
#include <U2Gui/GlassView.h>
#include <U2Gui/LastUsedDirHelper.h>
#include <U2Lang/QueryDesignerRegistry.h>
#include <U2Designer/DelegateEditors.h>
#include <QtGui/QMenu>
#include <QtGui/QToolBar>
#include <QtGui/QTabWidget>
#include <QtGui/QSplitter>
#include <QtGui/QFileDialog>
#include <QtGui/QMessageBox>
namespace U2 {
/************************************************************************/
/* Scene */
/************************************************************************/
const QSizeF QueryScene::MAX_SCENE_SIZE(10*1000, 10*1000);
const QSizeF QueryScene::DEFAULT_SCENE_SIZE(1000, 1000);
#define MAX_ITEM_SIZE 10000 // max point size for any visual item and whole scene
#define MIN_ROWS_NUMBER 3
#define DESCRIPTION_TOP_PAD 40
#define DESCRIPTION_BOTTOM_PAD 20
#define FOOTNOTES_AREA_TOP_MARGIN 20
#define FOOTNOTE_BOTTOM_MARGIN 20
QueryScene::QueryScene(QueryViewController* parent/* =0 */) : QGraphicsScene(parent),
dropCandidateLeft(NULL), dropCandidateRight(NULL), view(parent), rowsNum(3),
showSchemeLbl(false), showDesc(true), showOrder(true), modified(false) {
setSceneRect(0, 0, DEFAULT_SCENE_SIZE.width(), DEFAULT_SCENE_SIZE.height());
setItemIndexMethod(NoIndex);
scheme = new QDScheme;
initTitle();
initRuler();
initDescription();
}
QueryScene::~QueryScene() {
clearScene();
delete scheme;
delete labelTxtItem;
delete descTxtItem;
delete ruler;
}
#define LABEL_HEIGHT 40
#define LABEL_PIXEL_SIZE 15
#define LABEL_LEFT_PAD 200
void QueryScene::initTitle() {
labelTxtItem = new QDLabelItem("NewSchema");
QFont lblFont;
lblFont.setItalic(true);
lblFont.setPixelSize(LABEL_PIXEL_SIZE);
labelTxtItem->setFont(lblFont);
labelTxtItem->setPos(LABEL_LEFT_PAD,0);
if (view) {
connect(labelTxtItem, SIGNAL(si_editingFinished()), view, SLOT(sl_updateTitle()));
}
}
void QueryScene::initRuler() {
ruler = new QDRulerItem;
connect(this, SIGNAL(si_schemeChanged()), ruler, SLOT(sl_updateText()));
ruler->setPos(0,0);
addItem(ruler);
}
void QueryScene::initDescription() {
descTxtItem = new QDDescriptionItem("<Write description here>");
descTxtItem->setTextWidth(200);
qreal viewWidth(0);
if (views().isEmpty()) {
viewWidth = sceneRect().width();
} else {
assert(views().size() == 1);
QGraphicsView* v = views().first();
viewWidth = v->viewport()->width();
}
qreal xPos = (viewWidth - descTxtItem->boundingRect().width()) / 2.0;
qreal yPos = footnotesArea().bottom() + DESCRIPTION_TOP_PAD;
descTxtItem->setPos(xPos, yPos);
addItem(descTxtItem);
descTxtItem->setVisible(false);
}
int QueryScene::getRow(QDElement* const uv) const {
const QPointF& pos = uv->scenePos();
qreal top=annotationsArea().top();
int row = (pos.y()-top)/GRID_STEP;
return row;
}
bool yPosLessThan(QGraphicsItem* uv1, QGraphicsItem* uv2) {
const QPointF& pos1 = uv1->scenePos();
const QPointF& pos2 = uv2->scenePos();
if (pos1.y()<pos2.y()) {
return false;
}
return true;
}
void QueryScene::insertRow(int idx) {
assert(idx>=0);
if (idx>=rowsNum) {
rowsNum = idx+1;
return;
}
qreal rowTop = idx*GRID_STEP + annotationsArea().top();
//sort items by y-pos
QList<QGraphicsItem*> units;
foreach(QGraphicsItem* it, items()) {
if (it->type()==QDElementType) {
if(it->scenePos().y() >= rowTop) {
units.append(it);
}
}
}
qSort(units.begin(), units.end(), yPosLessThan);
foreach(QGraphicsItem* it, units) {
QPointF itPos = it->scenePos();
itPos.ry()+=GRID_STEP;
it->setPos(itPos);
}
}
void QueryScene::sl_adaptRowsNumber() {
int adaptedNum = rowsNum;
for (int i=rowsNum-1;i>=MIN_ROWS_NUMBER; i--) {
if (unitsIntersectedByRow(i).isEmpty()) {
--adaptedNum;
} else {
break;
}
}
setRowsNumber(adaptedNum);
}
void QueryScene::sl_updateRulerText() {
ruler->sl_updateText();
}
QString QueryScene::getLabel() const {
return labelTxtItem->toPlainText();
}
QString QueryScene::getDescription() const {
return descTxtItem->toPlainText();
}
void QueryScene::setLabel(const QString& lbl) {
labelTxtItem->setPlainText(lbl);
}
void QueryScene::setDescription(const QString& dsc) {
descTxtItem->setPlainText(dsc);
}
void QueryScene::sl_showLabel(bool show) {
if (showSchemeLbl==show) {
return;
}
showSchemeLbl = show;
int dy(0);
if (showSchemeLbl) {
addItem(labelTxtItem);
dy = LABEL_HEIGHT;
ruler->setPos(0, LABEL_HEIGHT);
} else {
removeItem(labelTxtItem);
dy = -LABEL_HEIGHT;
ruler->setPos(0,0);
}
foreach(QGraphicsItem* it, items()) {
if (it->type()==QDElementType) {
it->moveBy(0.0, dy);
}
}
descTxtItem->moveBy(0.0, dy);
update();
}
void QueryScene::sl_showSchemeDesc(bool show) {
descTxtItem->setVisible(show);
}
void QueryScene::sl_showItemDesc(bool show) {
showDesc = show;
foreach(QGraphicsItem* it, items()) {
if (it->type()==QDElementType) {
QDElement* uv = qgraphicsitem_cast<QDElement*>(it);
uv->sl_refresh();
uv->rememberSize();
uv->adaptSize();
sl_adaptRowsNumber();
}
}
}
void QueryScene::sl_showOrder(bool show) {
showOrder = show;
foreach(QGraphicsItem* it, items()) {
if (it->type()==QDElementType) {
QDElement* uv = qgraphicsitem_cast<QDElement*>(it);
uv->sl_refresh();
}
}
}
QRectF QueryScene::rulerArea() const {
QRectF area = ruler->boundingRect();
area.moveTopLeft(ruler->scenePos());
assert(area.width() < MAX_ITEM_SIZE && area.height() < MAX_ITEM_SIZE);
return area;
}
QRectF QueryScene::annotationsArea() const {
const QRectF& rect = sceneRect();
assert(rect.width() < MAX_ITEM_SIZE && rect.height() < MAX_ITEM_SIZE);
//qreal top = round(rect.top() + dy, GRID_STEP);
qreal top = rect.top() + ruler->boundingRect().height();
if (showSchemeLbl) {
top += LABEL_HEIGHT;
}
qreal areaHeight = rowsNum*GRID_STEP;
return QRectF(rect.left(), top, rect.width(), areaHeight);
}
QRectF QueryScene::footnotesArea() const {
qreal tlX = sceneRect().left();
qreal tlY = annotationsArea().bottom() + FOOTNOTES_AREA_TOP_MARGIN;
qreal brX = sceneRect().right();
qreal brY=tlY;
foreach(QGraphicsItem* it, items()) {
if (it->type()==FootnoteItemType) {
qreal itBottomEdge = it->scenePos().y() + it->boundingRect().height();
if (itBottomEdge>brY) {
brY = itBottomEdge;
}
}
}
brY += FOOTNOTE_BOTTOM_MARGIN;
QRectF rect(QPointF(tlX,tlY), QPointF(brX,brY));
assert(rect.width() < MAX_ITEM_SIZE && rect.height() < MAX_ITEM_SIZE);
return rect;
}
QList<QDElement*> QueryScene::getElements() const {
QList<QDElement*> res;
foreach(QGraphicsItem* item, items()) {
if (item->type()==QDElementType) {
QDElement* el = qgraphicsitem_cast<QDElement*>(item);
res.append(el);
}
}
return res;
}
QList<QGraphicsItem*> QueryScene::getFootnotes() const {
QList<QGraphicsItem*> res;
foreach(QGraphicsItem* item, items()) {
if (item->type()==FootnoteItemType) {
res.append(item);
}
}
return res;
}
QDElement* QueryScene::getUnitView(QDSchemeUnit* su) const {
foreach(QDElement* el, getElements()) {
if (el->getSchemeUnit()==su) {
return el;
}
}
return NULL;
}
#define MAX_ROWS_NUMBER 200
void QueryScene::setRowsNumber(int count) {
if (count <= MAX_ROWS_NUMBER) {
qreal dY = (count - rowsNum)*GRID_STEP;
rowsNum = count;
foreach(QGraphicsItem* item, items()) {
if(item->type()==FootnoteItemType) {
Footnote* fn = qgraphicsitem_cast<Footnote*>(item);
fn->moveBy(0.0, dY);
}
}
descTxtItem->moveBy(0.0, dY);
qreal bottom = descTxtItem->mapRectToScene(descTxtItem->boundingRect()).bottom();
bottom = footnotesArea().bottom() + DESCRIPTION_TOP_PAD;
descTxtItem->setY(bottom);
qreal newH = qMax(QueryScene::DEFAULT_SCENE_SIZE.height(),
descTxtItem->mapRectToScene(descTxtItem->boundingRect()).bottom() + DESCRIPTION_BOTTOM_PAD);
QRectF r = sceneRect();
if (newH > r.height()) {
r.setHeight(newH);
setSceneRect(r);
}
update();
}
}
void QueryScene::drawBackground(QPainter *painter, const QRectF &rect) {
Q_UNUSED(rect);
int step = GRID_STEP;
painter->setPen(QPen(QColor(200, 200, 255, 125)));
// draw horizontal grid
const QRectF& area = annotationsArea();
qreal start = area.top();
for (qreal y = start; y < start + (rowsNum+1)*step; y += step) {
painter->drawLine(area.left(), y, area.right(), y);
}
}
QList<QGraphicsItem*> QueryScene::getElements(const QRectF& area) {
QList<QGraphicsItem*> items = QGraphicsScene::items(area, Qt::IntersectsItemShape);
foreach(QGraphicsItem* item, items) {
if(item->type()!=QDElementType) {
items.removeAll(item);
}
}
return items;
}
void QueryScene::mousePressEvent(QGraphicsSceneMouseEvent *mouseEvent) {
if (!mouseEvent->isAccepted() && view->getActor() && (mouseEvent->button() == Qt::LeftButton)) {
addActor( view->getActor(), mouseEvent->scenePos());
}
QGraphicsScene::mousePressEvent(mouseEvent);
}
#define BINDING_AREA 50
void QueryScene::dragEnterEvent(QGraphicsSceneDragDropEvent *) {}
void QueryScene::dragMoveEvent(QGraphicsSceneDragDropEvent *event) {
const QString& mimeStr = event->mimeData()->text();
if (mimeStr==QDDistanceIds::E2S || mimeStr==QDDistanceIds::S2E ||
mimeStr==QDDistanceIds::S2S || mimeStr==QDDistanceIds::E2E) {
const QList<QGraphicsItem*>& sceneUnitViews = getElements(sceneRect());
if (sceneUnitViews.size()<2) {
event->setDropAction(Qt::IgnoreAction);
return;
}
if(dropCandidateLeft && dropCandidateRight) {
dropCandidateLeft->highlighted = false;
dropCandidateRight->highlighted = false;
}
QPointF mousePos = event->scenePos();
QRectF leftArea = sceneRect();
leftArea.setRight(mousePos.x());
const QList<QGraphicsItem*>& annItemsToLeft = getElements(leftArea);
QRectF rightArea = sceneRect();
rightArea.setLeft(mousePos.x());
const QList<QGraphicsItem*>& annItemsToRight = getElements(rightArea);
qreal delta = sceneRect().width()*sceneRect().width() + sceneRect().height()*sceneRect().height();
QDElement *src = NULL, *dst = NULL;
foreach(QGraphicsItem* itLeft, annItemsToLeft) {
QDElement* leftAnn = qgraphicsitem_cast<QDElement*>(itLeft);
assert(leftAnn);
foreach(QGraphicsItem* itRight, annItemsToRight) {
QDElement* rightAnn = qgraphicsitem_cast<QDElement*>(itRight);
assert(rightAnn);
QLineF srcToPos(leftAnn->getRightConnector(), mousePos);
QLineF dstToPos(rightAnn->getLeftConnector(), mousePos);
QLineF srcToDst(leftAnn->getRightConnector(), rightAnn->getLeftConnector());
qreal curDelta = srcToPos.length() + dstToPos.length() - srcToDst.length();
if(curDelta < delta) {
delta = curDelta;
src=leftAnn;
dst=rightAnn;
}
}
}
if(delta < BINDING_AREA) {
dropCandidateLeft = src;
dropCandidateRight = dst;
dropCandidateLeft->highlighted = true;
dropCandidateRight->highlighted = true;
update();
}
event->acceptProposedAction();
} else if(AppContext::getQDActorProtoRegistry()->getAllIds().contains(mimeStr)) {
event->acceptProposedAction();
} else {
event->acceptProposedAction();
}
}
void QueryScene::dropEvent(QGraphicsSceneDragDropEvent *event) {
if(!event->mimeData()->hasText()) {
return;
}
const QString& mimeStr = event->mimeData()->text();
if (AppContext::getQDActorProtoRegistry()->getAllIds().contains(mimeStr)) {
QDActorPrototype* proto = AppContext::getQDActorProtoRegistry()->getProto(mimeStr);
QDActor* actor = proto->createInstance();
addActor(actor, event->scenePos());
return;
} else if (mimeStr==QDDistanceIds::E2E) {
setupDistanceDialog(E2E);
} else if (mimeStr==QDDistanceIds::S2S) {
setupDistanceDialog(S2S);
} else if (mimeStr==QDDistanceIds::E2S) {
setupDistanceDialog(E2S);
} else if (mimeStr==QDDistanceIds::S2E) {
setupDistanceDialog(S2E);
}
if (dropCandidateLeft) {
dropCandidateLeft->highlighted = false;
}
if (dropCandidateRight) {
dropCandidateRight->highlighted = false;
}
dropCandidateLeft = NULL;
dropCandidateRight = NULL;
}
void QueryScene::setupDistanceDialog(QDDistanceType kind) {
if(dropCandidateLeft && dropCandidateRight) {
AddConstraintDialog dlg(this, kind, dropCandidateLeft, dropCandidateRight);
dlg.exec();
}
}
#define UNIT_PADDING 30
void QueryScene::addActor(QDActor* actor, const QPointF& pos) {
int count = 0;
foreach(QDActor* a, scheme->getActors()) {
if (a->getActorType() == actor->getActorType()) {
++count;
}
}
QDActorParameters* actorCfg = actor->getParameters();
QString defaultName = actor->getProto()->getDisplayName();
if (count>0) {
actorCfg->setLabel(QString("%1%2").arg(defaultName).arg(count));
}
else {
actorCfg->setLabel(defaultName);
}
qreal top = annotationsArea().top();
int rowNum = (pos.y() - top)/GRID_STEP;
assert(rowNum>=0);
qreal y = rowNum*GRID_STEP + top;
scheme->addActor(actor);
int dx = 0;
QMap<QDSchemeUnit*, QDElement*> unit2view;
foreach(QDSchemeUnit* su, actor->getSchemeUnits()) {
QDElement* uv = new QDElement(su);
unit2view[su] = uv;
addItem(uv);
uv->setPos(pos.x() + dx, y);
dx += UNIT_PADDING + uv->boundingRect().width();
}
foreach(QDConstraint* c, actor->getParamConstraints()) {
QDDistanceConstraint* dc = static_cast<QDDistanceConstraint*>(c);
if (dc) {
QueryViewController::setupConstraintEditor(dc);
Footnote* fn = new Footnote(unit2view.value(dc->getSource()),
unit2view.value(dc->getDestination()), dc->distanceType(), c
);
addItem(fn);
fn->updatePos();
}
}
connect(actor->getParameters(), SIGNAL(si_modified()), ruler, SLOT(sl_updateText()));
emit_schemeChanged();
setModified(true);
emit si_itemAdded();
}
void QueryScene::addDistanceConstraint(QDElement* src, QDElement* dst, QDDistanceType distType, int min, int max) {
if(src!=dst) {
QList<QDSchemeUnit*> units;
units << src->getSchemeUnit() << dst->getSchemeUnit();
QDConstraint* c = new QDDistanceConstraint(units, distType, min, max);
QueryViewController::setupConstraintEditor(c);
scheme->addConstraint(c);
connect(c->getParameters(), SIGNAL(si_modified()), ruler, SLOT(sl_updateText()));
Footnote* fn = new Footnote(src, dst, distType, c);
addItem(fn);
fn->updatePos();
updateDescription();
emit_schemeChanged();
}
setModified(true);
}
void QueryScene::removeActor(QDActor* actor) {
foreach(QGraphicsItem* it, getElements()) {
QDElement* uv = qgraphicsitem_cast<QDElement*>(it);
assert(uv);
if (uv->getActor()==actor) {
removeItem(uv);
delete uv;
}
}
const QList<QDActor*>& actors = scheme->getActors();
int removedIdx = actors.indexOf(actor);
scheme->removeActor(actor);
int actorsNumber = actors.size();
for (int idx=removedIdx; idx<actorsNumber; idx++) {
QDActor* a = actors.at(idx);
scheme->setOrder(a, idx);
foreach(QDElement* el, getElements()) {
if (el->getActor()==a) {
el->sl_refresh();
break;
}
}
}
emit_schemeChanged();
setModified(true);
}
void QueryScene::removeActors(const QList<QDActor*>& actors) {
foreach(QDActor* a, actors) {
removeActor(a);
}
}
void QueryScene::removeConstraint(QDConstraint* constraint) {
QDSchemeUnit* su = constraint->getSchemeUnits().at(0);
Q_UNUSED(su);
assert(su->getConstraints().contains(constraint));
foreach(QGraphicsItem* it, getFootnotes()) {
Footnote* fn = qgraphicsitem_cast<Footnote*>(it);
assert(fn);
if (fn->getConstraint()==constraint) {
removeItem(fn);
delete fn;
}
}
scheme->removeConstraint(constraint);
updateDescription();
emit_schemeChanged();
setModified(true);
}
void QueryScene::clearScene() {
removeActors(scheme->getActors());
scheme->clear();
}
QList<QGraphicsItem*> QueryScene::unitsIntersectedByRow(int idx) const {
const QRectF& area = annotationsArea();
QRectF currRow(area.left(), idx*GRID_STEP, area.width(), GRID_STEP);
currRow.moveTop(currRow.top()+annotationsArea().top());
QList<QGraphicsItem*> rowItems = items(currRow, Qt::IntersectsItemShape);
foreach(QGraphicsItem* it, rowItems) {
if (it->type()!=QDElementType) {
rowItems.removeAll(it);
}
}
return rowItems;
}
void QueryScene::setModified( bool b ) {
modified=b;
if (view) {
view->enableSaveAction(b);
}
}
void QueryScene::updateDescription() {
qreal y = footnotesArea().bottom() + DESCRIPTION_TOP_PAD;
descTxtItem->setY(y);
QRectF rect = sceneRect();
y = descTxtItem->mapRectToScene(descTxtItem->boundingRect()).bottom();
qreal newH = qMax(y + DESCRIPTION_BOTTOM_PAD, QueryScene::DEFAULT_SCENE_SIZE.height());
rect.setHeight(newH);
setSceneRect(rect);
}
/************************************************************************/
/* View Controller */
/************************************************************************/
enum {ElementsTab,GroupsTab,SamplesTab};
#define PALETTE_STATE "query_palette_settings"
QueryViewController::QueryViewController() : MWMDIWindow(tr("Query Designer")), currentActor(NULL) {
GCOUNTER(cvar, tvar, "OpenQDWindow");
scene = new QueryScene(this);
sceneView = new GlassView(scene);
sceneView->setDragMode(QGraphicsView::RubberBandDrag);
palette = new QueryPalette(this);
groupsEditor = new QDGroupsEditor(this);
QDSamplesWidget* samples = new QDSamplesWidget(scene, this);
tabs = new QTabWidget(this);
tabs->insertTab(ElementsTab, palette, tr("Elements"));
tabs->insertTab(GroupsTab, groupsEditor, tr("Groups"));
tabs->insertTab(SamplesTab, samples, tr("Samples"));
editor = new QueryEditor(this);
connect(scene, SIGNAL(selectionChanged()), SLOT(sl_editItem()));
connect(scene, SIGNAL(si_itemAdded()), SLOT(sl_itemAdded()));
connect(palette, SIGNAL(processSelected(QDActorPrototype*)), SLOT(sl_elementSelected(QDActorPrototype*)));
connect(samples, SIGNAL(setupGlass(GlassPane*)), sceneView, SLOT(setGlass(GlassPane*)));
connect(samples, SIGNAL(itemActivated(QDDocument*)), SLOT(sl_pasteSample(QDDocument*)));
connect(tabs, SIGNAL(currentChanged(int)), samples, SLOT(sl_cancel()));
connect(editor, SIGNAL(modified()), scene, SLOT(sl_setModified()));
QSplitter* splitter = new QSplitter(Qt::Horizontal, this);
splitter->addWidget(tabs);
splitter->addWidget(sceneView);
splitter->addWidget(editor);
Settings* settings = AppContext::getSettings();
if (settings->contains(PALETTE_STATE)) {
palette->restoreState(settings->getValue(PALETTE_STATE));
}
QHBoxLayout* layout = new QHBoxLayout(this);
layout->addWidget(splitter);
layout->setSpacing(0);
layout->setMargin(0);
layout->setContentsMargins(0, 0, 0, 0);
setLayout(layout);
createActions();
sl_updateTitle();
sl_scrollUp();
}
void QueryViewController::loadScene(const QString& content) {
QDDocument doc;
doc.setContent(content);
QList<QDDocument*> docs;
docs << &doc;
QDSceneSerializer::doc2scene(scene, docs);
scene->setModified(false);
sl_updateTitle();
}
void QueryViewController::createActions() {
runAction = new QAction(tr("Run Schema..."), this);
runAction->setIcon(QIcon(":query_designer/images/run.png"));
connect(runAction, SIGNAL(triggered()), SLOT(sl_run()));
newAction = new QAction(tr("New Schema"), this);
newAction->setShortcuts(QKeySequence::New);
newAction->setIcon(QIcon(":query_designer/images/filenew.png"));
connect(newAction, SIGNAL(triggered()), SLOT(sl_newScene()));
loadAction = new QAction(tr("Load Schema..."), this);
loadAction->setShortcut(QKeySequence("Ctrl+L"));
loadAction->setIcon(QIcon(":query_designer/images/fileopen.png"));
connect(loadAction, SIGNAL(triggered()), SLOT(sl_loadScene()));
saveAction = new QAction(tr("Save Schema"), this);
saveAction->setShortcut(QKeySequence::Save);
saveAction->setIcon(QIcon(":query_designer/images/filesave.png"));
saveAction->setDisabled(true);
connect(saveAction, SIGNAL(triggered()), SLOT(sl_saveScene()));
saveAsAction = new QAction(tr("Save Schema As..."), this);
saveAsAction->setShortcut(QKeySequence::SaveAs);
saveAsAction->setIcon(QIcon(":query_designer/images/filesave.png"));
connect(saveAsAction, SIGNAL(triggered()), SLOT(sl_saveSceneAs()));
deleteAction = new QAction(tr("Delete"), this);
deleteAction->setShortcut(QKeySequence::Delete);
deleteAction->setIcon(QIcon(":query_designer/images/delete.png"));
connect(deleteAction, SIGNAL(triggered()), SLOT(sl_deleteItem()));
showLabelAction = new QAction(tr("Show title"), this);
showLabelAction->setCheckable(true);
showLabelAction->setChecked(false);
connect(showLabelAction, SIGNAL(toggled(bool)), scene, SLOT(sl_showLabel(bool)));
showDescAction = new QAction(tr("Show description"), this);
showDescAction->setCheckable(true);
showDescAction->setChecked(false);
connect(showDescAction, SIGNAL(toggled(bool)), scene, SLOT(sl_showSchemeDesc(bool)));
showItemDescAction = new QAction(tr("Show element info"), this);
showItemDescAction->setCheckable(true);
showItemDescAction->setChecked(true);
connect(showItemDescAction, SIGNAL(toggled(bool)), scene, SLOT(sl_showItemDesc(bool)));
showOrderAction = new QAction(tr("Show order"), this);
showOrderAction->setCheckable(true);
showOrderAction->setChecked(true);
connect(showOrderAction, SIGNAL(toggled(bool)), scene, SLOT(sl_showOrder(bool)));
strandActions = new QActionGroup(this);
directStrandAction = new QAction(tr("Direct strand"), strandActions);
directStrandAction->setCheckable(true);
complementStrandAction = new QAction(tr("Reverse complementary strand"), strandActions);
complementStrandAction->setCheckable(true);
bothStrandsAction = new QAction(tr("Both strands"), strandActions);
bothStrandsAction->setCheckable(true);
QDStrandOption strand = scene->getScheme()->getStrand();
switch (strand)
{
case QDStrand_Both:
bothStrandsAction->setChecked(true);
break;
case QDStrand_DirectOnly:
directStrandAction->setChecked(true);
break;
case QDStrand_ComplementOnly:
complementStrandAction->setChecked(true);
break;
default:
assert(0);
break;
}
connect(strandActions, SIGNAL(triggered(QAction*)), SLOT(sl_setGlobalStrand(QAction*)));
}
void QueryViewController::setupViewModeMenu(QMenu* m) {
m->addAction(showLabelAction);
m->addAction(showDescAction);
m->addAction(showItemDescAction);
m->addAction(showOrderAction);
}
void QueryViewController::setupQuerySequenceModeMenu(QMenu* m) {
m->addAction(directStrandAction);
m->addAction(complementStrandAction);
m->addAction(bothStrandsAction);
}
void QueryViewController::setupStrandMenu(QMenu* m) {
m->addActions(strandActions->actions());
}
void QueryViewController::setupMDIToolbar(QToolBar* tb) {
tb->addAction(newAction);
tb->addAction(loadAction);
tb->addAction(saveAction);
tb->addAction(saveAsAction);
tb->addSeparator();
tb->addAction(runAction);
tb->addSeparator();
QToolButton* tt = new QToolButton(tb);
QMenu* viewModeMenu = new QMenu(tr("View Mode"), this);
setupViewModeMenu(viewModeMenu);
QAction* a = viewModeMenu->menuAction();
tt->setDefaultAction(a);
tt->setPopupMode(QToolButton::InstantPopup);
tt->setIcon(QIcon(":query_designer/images/eye.png"));
tb->addWidget(tt);
QToolButton* st = new QToolButton(tb);
QMenu* strandMenu = new QMenu(tr("Query Sequence Mode"), this);
setupStrandMenu(strandMenu);
QAction* sa = strandMenu->menuAction();
st->setDefaultAction(sa);
st->setPopupMode(QToolButton::InstantPopup);
st->setIcon(QIcon(":query_designer/images/strands.png"));
tb->addWidget(st);
tb->addSeparator();
tb->addAction(deleteAction);
}
void QueryViewController::setupViewMenu(QMenu* m) {
m->addAction(newAction);
m->addAction(loadAction);
m->addAction(saveAction);
m->addAction(saveAsAction);
m->addSeparator();
m->addAction(runAction);
m->addSeparator();
QMenu* viewModeMenu = new QMenu(tr("View Mode"), this);
viewModeMenu->setIcon(QIcon(":query_designer/images/eye.png"));
setupViewModeMenu(viewModeMenu);
m->addMenu(viewModeMenu);
QMenu* querySequenceModeMenu = new QMenu(tr("Query Sequence Mode"), this);
querySequenceModeMenu->setIcon((QIcon(":query_designer/images/strands.png")));
setupQuerySequenceModeMenu(querySequenceModeMenu);
m->addMenu(querySequenceModeMenu);
m->addSeparator();
m->addAction(deleteAction);
m->addSeparator();
}
void QueryViewController::switchToGroupsTab() {
tabs->setCurrentIndex(GroupsTab);
}
bool QueryViewController::onCloseEvent() {
saveState();
return confirmModified();
}
void QueryViewController::saveState() {
AppContext::getSettings()->setValue(PALETTE_STATE, palette->saveState());
}
void QueryViewController::sl_run() {
QDScheme* scheme = scene->getScheme();
if (scheme->isEmpty()) {
QMessageBox::critical(this, L10N::errorTitle(), tr("The schema is empty!"));
} else if (!scheme->isValid()) {
QMessageBox::critical(this, L10N::errorTitle(), tr("The schema is invalid! Please see the log for details."));
} else {
QDRunDialog runDlg(scene->getScheme(), this, inFile_, outFile_);
runDlg.exec();
}
}
void QueryViewController::sl_newScene() {
if(!scene->getScheme()->getActors().isEmpty()) {
if (!confirmModified()) {
return;
}
}
schemeUri.clear();
scene->setLabel("NewSchema");
scene->setDescription("<Insert description here>");
scene->clearScene();
sl_updateTitle();
}
void QueryViewController::sl_loadScene() {
if(!scene->getScheme()->getActors().isEmpty()) {
if (!confirmModified()) {
return;
}
}
LastUsedDirHelper dir(QUERY_DESIGNER_ID);
dir.url = QFileDialog::getOpenFileName(this, tr("Load Schema"), dir, QString("*.%1").arg(QUERY_SCHEME_EXTENSION));
if (!dir.url.isEmpty()) {
QDLoadSceneTask* t = new QDLoadSceneTask(scene, dir.url);
connect(new TaskSignalMapper(t), SIGNAL(si_taskFinished(Task*)), SLOT(sl_updateTitle()));
AppContext::getTaskScheduler()->registerTopLevelTask(t);
scene->setModified(false);
schemeUri = dir.url;
}
}
void QueryViewController::sl_saveScene() {
if (schemeUri.isEmpty()) {
sl_saveSceneAs();
} else {
QDSceneInfo info;
info.path = schemeUri;
info.schemeName = scene->getLabel();
info.description = scene->getDescription();
QDSaveSceneTask* t = new QDSaveSceneTask(scene, info);
AppContext::getTaskScheduler()->registerTopLevelTask(t);
scene->setModified(false);
}
}
void QueryViewController::sl_saveSceneAs() {
LastUsedDirHelper dir(QUERY_DESIGNER_ID);
dir.url = QFileDialog::getSaveFileName(this, tr("Save Schema"), dir, QString("*.%1").arg(QUERY_SCHEME_EXTENSION));
if (!dir.url.isEmpty()) {
schemeUri = dir.url;
sl_saveScene();
}
}
void QueryViewController::sl_deleteItem() {
QList<QDActor*> actors2remove;
QList<QDConstraint*> constraints2remove;
QList<QGraphicsItem*> selectedItems = scene->selectedItems();
foreach(QGraphicsItem* item, selectedItems) {
switch (item->type()) {
case QDElementType:
{
QDElement* uv = qgraphicsitem_cast<QDElement*>(item);
assert(uv);
QDActor* a = uv->getActor();
if(!actors2remove.contains(a)) {
actors2remove.append(a);
}
}
break;
case FootnoteItemType:
{
Footnote* fn = qgraphicsitem_cast<Footnote*>(item);
assert(fn);
QDConstraint* c = fn->getConstraint();
if (!constraints2remove.contains(c)) {
constraints2remove.append(c);
}
}
break;
default:
break;
}
}
QList<QDConstraint*> removedConstraints;
foreach (QDConstraint* c, constraints2remove) {
if (removedConstraints.contains(c)) {
continue;
}
QDSchemeUnit* su = c->getSchemeUnits().at(0);
QDActor* actor = su->getActor();
if (!su->getConstraints().contains(c)) { //param constraint
actors2remove.removeAll(actor);
removedConstraints << actor->getConstraints();
scene->removeActor(actor);
continue;
}
scene->removeConstraint(c);
}
scene->removeActors(actors2remove);
scene->setModified(true);
}
void QueryViewController::sl_editItem() {
const QList<QGraphicsItem*>& selectedItems = scene->selectedItems();
if(1==selectedItems.size()) {
QGraphicsItem* selectedItem = selectedItems.at(0);
if(selectedItem->type()==QDElementType) {
QDElement* unitView = qgraphicsitem_cast<QDElement*>(selectedItem);
QDActor* a = unitView->getSchemeUnit()->getActor();
editor->edit(a);
}
if(selectedItem->type()==FootnoteItemType) {
Footnote* fn = qgraphicsitem_cast<Footnote*>(selectedItem);
QDConstraint* con = fn->getConstraint();
editor->edit(con);
}
}
else {
editor->reset();
}
}
void QueryViewController::sl_elementSelected(QDActorPrototype* proto) {
scene->clearSelection();
editor->showProto(proto);
if (!proto) {
scene->views().at(0)->unsetCursor();
scene->views().at(0)->setCursor(Qt::ArrowCursor);
currentActor = NULL;
} else {
scene->views().at(0)->setCursor(Qt::CrossCursor);
delete currentActor;
currentActor = NULL;
currentActor = proto->createInstance();
}
}
void QueryViewController::sl_pasteSample(QDDocument* content) {
if(!scene->getScheme()->getActors().isEmpty()) {
if (!confirmModified()) {
return;
}
}
tabs->setCurrentIndex(ElementsTab);
scene->clearScene();
QList<QDDocument*> docList = ( QList<QDDocument*>() << content );
QDSceneSerializer::doc2scene(scene, docList);
sl_updateTitle();
scene->setModified(false);
schemeUri.clear();
}
void QueryViewController::sl_selectEditorCell(const QString& link) {
editor->setCurrentAttribute(link);
}
void QueryViewController::sl_updateTitle() {
setWindowTitle(tr("Query Designer - %1").arg(scene->getLabel()));
}
void QueryViewController::sl_setGlobalStrand(QAction* a) {
QDScheme* scheme = scene->getScheme();
QDStrandOption old = scheme->getStrand();
if (a==bothStrandsAction) {
scheme->setStrand(QDStrand_Both);
} else if (a==directStrandAction) {
scheme->setStrand(QDStrand_DirectOnly);
} else {
assert(a==complementStrandAction);
scheme->setStrand(QDStrand_ComplementOnly);
}
if (scheme->getStrand()!=old) {
scene->setModified(true);
}
}
void QueryViewController::sl_itemAdded() {
currentActor = NULL;
palette->resetSelection();
assert(scene->views().size() == 1);
scene->views().at(0)->unsetCursor();
scene->views().at(0)->setCursor(Qt::ArrowCursor);
}
void QueryViewController::sl_scrollUp() {
QPointF topLeft = scene->sceneRect().topLeft();
QSize s = sceneView->viewport()->rect().size();
QRectF topRect(topLeft, s);
sceneView->ensureVisible(topRect);
}
void QueryViewController::setupConstraintEditor(QDConstraint* c) {
if (c->constraintType()==QDConstraintTypes::DISTANCE) {
QMap<QString,PropertyDelegate*> delegates;
{
QVariantMap lenMap;
lenMap["minimum"] = QVariant(0);
lenMap["maximum"] = QVariant(INT_MAX);
lenMap["suffix"] = L10N::suffixBp();
delegates[QDConstraintController::MIN_LEN_ATTR] = new SpinBoxDelegate(lenMap);
delegates[QDConstraintController::MAX_LEN_ATTR] = new SpinBoxDelegate(lenMap);
}
c->setUIEditor(new DelegateEditor(delegates));
}
}
bool QueryViewController::confirmModified() {
if (scene->isModified()) {
AppContext::getMainWindow()->getMDIManager()->activateWindow(this);
int ret = QMessageBox::question(this, tr("Query Designer"),
tr("The schema has been modified.\n"
"Do you want to save changes?"),
QMessageBox::Save | QMessageBox::Discard
| QMessageBox::Cancel,
QMessageBox::Save);
if (QMessageBox::Cancel == ret) {
return false;
} else if (QMessageBox::Save == ret){
sl_saveScene();
}
}
return true;
}
void QueryViewController::enableSaveAction( bool enable ) {
if (saveAction) {
saveAction->setEnabled(enable);
}
}
/************************************************************************/
/* AddConstraintDialog */
/************************************************************************/
AddConstraintDialog::AddConstraintDialog(QueryScene* _scene, QDDistanceType _kind,
QDElement* defSrc, QDElement* defDst)
: scene(_scene), kind(_kind) {
setupUi(this);
QString title = "Add %1 Constraint";
switch (kind)
{
case E2S:
setWindowTitle(title.arg("'" + tr("End-Start") + "'"));
break;
case E2E:
setWindowTitle(title.arg("'" + tr("End-End") + "'"));
break;
case S2E:
setWindowTitle(title.arg("'" + tr("Start-End") + "'"));
break;
case S2S:
setWindowTitle(title.arg("'" + tr("Start-Start") + "'"));
break;
default:
break;
}
maxSpin->setMaximum(INT_MAX);
minSpin->setMaximum(INT_MAX);
const QList<QDElement*>& elements = scene->getElements();
int index = 0;
foreach(QDElement* el, elements) {
const QVariant& data = qVariantFromValue(el);
QDActor* a = el->getActor();
QString name = a->getParameters()->getLabel();
if (a->getSchemeUnits().size()>1) {
name += QString(".%1").arg(a->getUnitId(el->getSchemeUnit()));
}
fromCBox->insertItem(index, name);
fromCBox->setItemData(index, data);
toCBox->insertItem(index, name);
toCBox->setItemData(index, data);
++index;
}
assert(elements.contains(defSrc));
assert(elements.contains(defDst));
fromCBox->setCurrentIndex(elements.indexOf(defSrc));
toCBox->setCurrentIndex(elements.indexOf(defDst));
}
void AddConstraintDialog::accept() {
int min = minSpin->text().toInt();
int max = maxSpin->text().toInt();
QDElement* src = qVariantValue<QDElement*>(fromCBox->itemData(fromCBox->currentIndex()));
QDElement* dst = qVariantValue<QDElement*>(toCBox->itemData(toCBox->currentIndex()));
scene->addDistanceConstraint(src, dst, kind, min, max);
QDialog::accept();
}
/************************************************************************/
/* GUIUtils */
/************************************************************************/
QPixmap QDUtils::generateSnapShot(QDDocument* doc, const QRect& rect) {
QueryScene scene;
QList<QDDocument*> docs = (QList<QDDocument*>() << doc);
QDSceneSerializer::doc2scene(&scene, docs);
return generateSnapShot(&scene, rect);
}
QPixmap QDUtils::generateSnapShot( QueryScene* scene, const QRect& rect) {
//assert(!rect.isNull());
QRectF bounds;
foreach(QGraphicsItem* item, scene->items()) {
if (item->type()==QDElementType || item->type()==FootnoteItemType) {
QRectF itemBound = item->boundingRect();
QPointF pos = item->scenePos();
itemBound.moveTopLeft(pos);
bounds |= itemBound;
if (bounds.width() > MAX_ITEM_SIZE || bounds.height() > MAX_ITEM_SIZE) {
uiLog.trace(QString("Illegal QD item size, stop rendering preview!"));
break;
}
}
}
QPixmap pixmap(bounds.size().toSize());
if (pixmap.isNull()) { // failed to allocate
uiLog.trace(QString("Failed to allocate pixmap for the QD scene, bounds: x:%1 y:%2 w:%3 h:%4")
.arg(bounds.x()).arg(bounds.y()).arg(bounds.width()).arg(bounds.height()));
QPixmap naPixmap = QPixmap(rect.size());
naPixmap.fill();
QPainter p(&naPixmap);
p.drawText(naPixmap.rect(), Qt::AlignHCenter | Qt::AlignTop, QueryScene::tr("Preview is not available."));
return naPixmap;
}
pixmap.fill();
QPainter painter(&pixmap);
painter.setRenderHint(QPainter::Antialiasing);
scene->render(&painter, rect, bounds);
return pixmap;
}
}//namespace
| 33.153339 | 118 | 0.626731 | [
"render"
] |
518af20dba54c5e63a656b14256d4d818dd57b9a | 26,487 | cpp | C++ | Simple_Game_Engine/Source/SceneWorldData.cpp | HoloDev42/SimpleGameEngine | f8101781ab6705452d5edf0dacf85335d8b9f0c6 | [
"MIT"
] | null | null | null | Simple_Game_Engine/Source/SceneWorldData.cpp | HoloDev42/SimpleGameEngine | f8101781ab6705452d5edf0dacf85335d8b9f0c6 | [
"MIT"
] | null | null | null | Simple_Game_Engine/Source/SceneWorldData.cpp | HoloDev42/SimpleGameEngine | f8101781ab6705452d5edf0dacf85335d8b9f0c6 | [
"MIT"
] | 1 | 2018-09-15T00:41:19.000Z | 2018-09-15T00:41:19.000Z | #include "SceneWorldData.h"
SceneWorldData::SceneWorldData()
{
}
SceneWorldData::SceneWorldData(const SceneWorldData& other)
{
}
SceneWorldData::~SceneWorldData()
{
}
void SceneWorldData::Init(ID3D11Device* device, MaterialManager* materialManager)
{
// Init the model manager
m_ModelManager.Init(device, materialManager);
}
bool SceneWorldData::AddObjectToScene(ID3D11Device * device, MaterialManager* materialManager, SceneObjectType objectType, CullingVolumeType cullingVolumeType, CollisionBodyType physicBodyType, std::string modelFilename, std::string& objectName, DirectX::FXMVECTOR position, DirectX::FXMVECTOR quaternionRotation, DirectX::FXMVECTOR scale, float mass)
{
bool result;
SceneObject TempWorldObject;
TempWorldObject.ObjectType = objectType;
TempWorldObject.CullingType = cullingVolumeType;
float width = 0, height = 0, depth = 0;
switch (objectType)
{
case StaticObject:
{
result = m_ModelManager.AddStaticModel(device, materialManager, modelFilename);
if (!result)
{
return false;
}
m_ModelManager.GetStaticModel(modelFilename).GetWidthHeightAndDepth(width, height, depth);
break;
}
case AnimatedObject:
{
result = m_ModelManager.AddAnimatedModel(device, materialManager, modelFilename);
if (!result)
{
return false;
}
m_ModelManager.GetAnimatedModel(modelFilename).GetWidthHeightAndDepth(width, height, depth);
break;
}
case TerrainObject:
{
result = m_ModelManager.AddTerrainModel(device, materialManager, modelFilename);
if (!result)
{
return false;
}
m_ModelManager.GetTerrainModel(modelFilename).GetWidthHeightAndDepth(width, height, depth);
break;
}
}
// Store axis aligned bounding box depth width and height.
TempWorldObject.AABB_depth = depth;
TempWorldObject.AABB_height = height;
TempWorldObject.AABB_width = width;
objectName = GetValidSceneObjectName(objectName);
TempWorldObject.ObjectName = objectName;
TempWorldObject.Filename = modelFilename;
XMStoreFloat3(&TempWorldObject.Position, position);
XMStoreFloat4(&TempWorldObject.QuaternionRotation, quaternionRotation);
XMStoreFloat3(&TempWorldObject.Scale, scale);
//Build Transform to "World" Matrix
DirectX::XMMATRIX worldMatrix = DirectX::XMMatrixIdentity();
DirectX::XMMATRIX ScaleMatrix;
ScaleMatrix = DirectX::XMMatrixScaling(DirectX::XMVectorGetX(scale), DirectX::XMVectorGetY(scale), DirectX::XMVectorGetZ(scale));
DirectX::XMMATRIX RotationMatrix;
//RotationMatrix = DirectX::XMMatrixRotationRollPitchYawFromVector(XMLoadFloat3(&Rotation));
RotationMatrix = DirectX::XMMatrixRotationQuaternion(quaternionRotation);
DirectX::XMMATRIX TranslateMatrix;
TranslateMatrix = DirectX::XMMatrixTranslation(DirectX::XMVectorGetX(position), DirectX::XMVectorGetY(position), DirectX::XMVectorGetZ(position));
worldMatrix = DirectX::XMMatrixMultiply(worldMatrix, ScaleMatrix);
worldMatrix = DirectX::XMMatrixMultiply(worldMatrix, RotationMatrix);
worldMatrix = DirectX::XMMatrixMultiply(worldMatrix, TranslateMatrix);
XMStoreFloat4x4(&TempWorldObject.WorldMatrix, worldMatrix);
// Handle physics for object
switch (physicBodyType)
{
case CollisionPlane:
{
m_Physic.AddPlane(objectName, position, DirectX::XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f));
break;
}
case CollisionSphere:
{
m_Physic.AddSphere(objectName, position, max(max(width, depth), height) / 2, mass);
break;
}
case CollisionBox:
{
m_Physic.AddBox(objectName, position, width, height, depth, mass);
break;
}
case CollisionCylinder:
{
m_Physic.AddCylinder(objectName, position, max(width, depth), height, mass);
break;
}
case CollisionCone:
{
m_Physic.AddCone(objectName, position, max(width, depth), height, mass);
break;
}
case CollisionStaticTriangleMesh:
{
switch (objectType)
{
case StaticObject:
{
m_Physic.AddStaticTriangleMesh(objectName, position, m_ModelManager.GetStaticModel(modelFilename).GetIndicies(),m_ModelManager.GetStaticModel(modelFilename).GetVertices());
break;
}
case AnimatedObject:
{
break;
}
case TerrainObject:
{
break;
}
}
break;
}
case CollisionConvexHullMesh:
{
switch (objectType)
{
case StaticObject:
{
m_Physic.AddConvexHullMesh(objectName, position, m_ModelManager.GetStaticModel(modelFilename).GetIndicies(), m_ModelManager.GetStaticModel(modelFilename).GetVertices(), mass);
break;
}
case AnimatedObject:
{
break;
}
case TerrainObject:
{
break;
}
}
break;
}
case CollisionConvexDecompositionMesh:
{
switch (objectType)
{
case StaticObject:
{
m_Physic.AddConvexDecompMesh(objectName, position, m_ModelManager.GetStaticModel(modelFilename).GetIndicies(), m_ModelManager.GetStaticModel(modelFilename).GetVertices(), mass);
break;
}
case AnimatedObject:
{
break;
}
case TerrainObject:
{
break;
}
}
break;
}
case CollisionMeshFile:
{
switch (objectType)
{
case StaticObject:
{
std::string collisionMeshFile;
if (m_ModelManager.GetStaticModel(modelFilename).GetCollisionMeshFilename(collisionMeshFile))
{
m_Physic.AddCollisionMeshFromFile(objectName, position, collisionMeshFile, mass);
}
else
{
m_Physic.AddConvexHullMesh(objectName, position, m_ModelManager.GetStaticModel(modelFilename).GetIndicies(), m_ModelManager.GetStaticModel(modelFilename).GetVertices(), mass);
}
break;
}
case AnimatedObject:
{
break;
}
case TerrainObject:
{
break;
}
}
break;
}
}
m_SceneObjects.push_back(TempWorldObject);
return true;
}
bool SceneWorldData::LoadSceneFile(ID3D11Device * device, MaterialManager * materialManager, std::string objectDescriptionFilename)
{
bool result;
DataFileContainer objectDescFile;
SceneObjectType objectType = StaticObject;
CullingVolumeType cullingVolumeType = CullPoint;
CollisionBodyType physicBodyType = CollisionBox;
std::string objectName = "";
std::string modelFilename = "";
DirectX::XMVECTOR position = DirectX::XMVectorSet(0.0f, 0.0f, 0.0f, 0.0f);
DirectX::XMVECTOR quaternionRotation = DirectX::XMVectorSet(0.0f, 0.0f, 0.0f, 0.0f);
DirectX::XMVECTOR scale = DirectX::XMVectorSet(0.0f, 0.0f, 0.0f, 0.0f);
float mass = 0.0f;
//Clear the config data object and use it to parse the material file
objectDescFile.ClearDataContainer();
result = objectDescFile.LoadDataContainerFile(objectDescriptionFilename);
if (result)
{
int numberOfSections = objectDescFile.GetNumberOfRootSections();
if (numberOfSections > 0)
{
for (int i = 0; i < numberOfSections; i++)
{
std::string objectSectionName;
std::string objectTypeStr;
std::string cullingVolumeTypeStr;
std::string collisionBodyTypeStr;
std::vector<float> pos, rot, sca;
objectDescFile.GetSectionName(objectDescFile.GetIndiciePathToRootSecton(i), objectSectionName);
result = objectDescFile.GetStringValueByName(objectSectionName, "Name", objectName);
if (!result)
{
objectName = "JoeDoe";
}
result = objectDescFile.GetStringValueByName(objectSectionName, "ModelFilename", modelFilename);
if (!result)
{
return false;
}
result = objectDescFile.GetStringValueByName(objectSectionName, "ObjectType", objectTypeStr);
if (!result)
{
return false;
}
if (objectTypeStr == "StaticObject")
{
objectType = StaticObject;
}
else if (objectTypeStr == "AnimatedObject")
{
objectType = AnimatedObject;
}
else if (objectTypeStr == "TerrainObject")
{
objectType = TerrainObject;
}
else
{
return false;
}
result = objectDescFile.GetStringValueByName(objectSectionName, "CullingVolumeType", cullingVolumeTypeStr);
if (!result)
{
return false;
}
if (cullingVolumeTypeStr == "CullPoint")
{
cullingVolumeType = CullPoint;
}
else if (cullingVolumeTypeStr == "CullCube")
{
cullingVolumeType = CullCube;
}
else if (cullingVolumeTypeStr == "CullSphere")
{
cullingVolumeType = CullSphere;
}
else if (cullingVolumeTypeStr == "CullBox")
{
cullingVolumeType = CullBox;
}
else
{
return false;
}
result = objectDescFile.GetStringValueByName(objectSectionName, "CollisionBodyType", collisionBodyTypeStr);
if (!result)
{
return false;
}
if (collisionBodyTypeStr == "CollisionPlane")
{
physicBodyType = CollisionPlane;
}
else if (collisionBodyTypeStr == "CollisionSphere")
{
physicBodyType = CollisionSphere;
}
else if (collisionBodyTypeStr == "CollisionBox")
{
physicBodyType = CollisionBox;
}
else if (collisionBodyTypeStr == "CollisionCylinder")
{
physicBodyType = CollisionCylinder;
}
else if (collisionBodyTypeStr == "CollisionCone")
{
physicBodyType = CollisionCone;
}
else if (collisionBodyTypeStr == "CollisionStaticTriangleMesh")
{
physicBodyType = CollisionStaticTriangleMesh;
}
else if (collisionBodyTypeStr == "CollisionConvexHullMesh")
{
physicBodyType = CollisionConvexHullMesh;
}
else if (collisionBodyTypeStr == "CollisionConvexDecompositionMesh")
{
physicBodyType = CollisionConvexDecompositionMesh;
}
else if (collisionBodyTypeStr == "CollisionMeshFile")
{
physicBodyType = CollisionMeshFile;
}
else
{
return false;
}
result = objectDescFile.GetFloatVectorByName(objectSectionName, "Position", pos);
if (!result)
{
position = DirectX::XMVectorSet(0.0f, 0.0f, 0.0f, 0.0f);
}
if (pos.size() == 3)
{
position = DirectX::XMVectorSet(pos[0], pos[1], pos[2], 0.0f);
}
else
{
position = DirectX::XMVectorSet(0.0f, 0.0f, 0.0f, 0.0f);
}
result = objectDescFile.GetFloatVectorByName(objectSectionName, "Rotation", rot);
if (!result)
{
quaternionRotation = DirectX::XMVectorSet(0.0f, 0.0f, 0.0f, 0.0f);
}
if (rot.size() == 4)
{
quaternionRotation = DirectX::XMVectorSet(rot[0], rot[1], rot[2], rot[3]);
}
else
{
quaternionRotation = DirectX::XMVectorSet(0.0f, 0.0f, 0.0f, 0.0f);
}
result = objectDescFile.GetFloatVectorByName(objectSectionName, "Scale", sca);
if (!result)
{
scale = DirectX::XMVectorSet(1.0f, 1.0f, 1.0f, 0.0f);
}
if (sca.size() == 3)
{
scale = DirectX::XMVectorSet(sca[0], sca[1], sca[2], 0.0f);
}
else
{
scale = DirectX::XMVectorSet(1.0f, 1.0f, 1.0f, 0.0f);
}
result = objectDescFile.GetFloatValueByName(objectSectionName, "Mass", mass);
if (!result)
{
mass = 0.0f;
}
result = AddObjectToScene(device, materialManager, objectType, cullingVolumeType, physicBodyType, modelFilename, objectName, position, quaternionRotation, scale, mass);
if (!result)
{
return false;
}
}
}
else
{
return true;
}
}
else
{
return false;
}
return true;
}
void SceneWorldData::RemoveObject(int objectIndex)
{
m_Physic.RemoveRigidBody(m_SceneObjects[objectIndex].ObjectName);
m_SceneObjects.erase(m_SceneObjects.begin() + objectIndex);
}
void SceneWorldData::RemoveObject(std::string name)
{
for (auto it = m_SceneObjects.begin(); it < m_SceneObjects.end(); it++)
{
if (it->ObjectName == name)
{
m_Physic.RemoveRigidBody(it->ObjectName);
m_SceneObjects.erase(it);
}
}
}
std::string SceneWorldData::GetValidSceneObjectName(std::string name)
{
auto it = std::find_if(m_SceneObjects.begin(), m_SceneObjects.end(), [&name](const SceneObject& obj) {return obj.ObjectName == name; });
if (it != m_SceneObjects.end())
{
int nameCount = std::count_if(m_SceneObjects.begin(), m_SceneObjects.end(), [&name](const SceneObject& obj)
{
if (obj.ObjectName.find(name + "_D") != std::string::npos)
{
return true;
}
if (obj.ObjectName.find(name + "_D") == std::string::npos)
{
return false;
}
});
name = (name + "_D") + std::to_string(nameCount + 1);
}
return name;
}
bool SceneWorldData::ApplyCentralForceToObject(std::string name, DirectX::FXMVECTOR force)
{
auto it = std::find_if(m_SceneObjects.begin(), m_SceneObjects.end(), [&name](const SceneObject& obj) {return obj.ObjectName == name; });
if (it != m_SceneObjects.end())
{
m_Physic.GetRigidBodys().GetRigidBody(name)->activate(true);
m_Physic.GetRigidBodys().GetRigidBody(name)->applyCentralForce(btVector3(DirectX::XMVectorGetX(force), DirectX::XMVectorGetY(force), DirectX::XMVectorGetZ(force)));
}
return true;
}
bool SceneWorldData::ApplyCentralImpulseToObject(std::string name, DirectX::FXMVECTOR impulse)
{
auto it = std::find_if(m_SceneObjects.begin(), m_SceneObjects.end(), [&name](const SceneObject& obj) {return obj.ObjectName == name; });
if (it != m_SceneObjects.end())
{
m_Physic.GetRigidBodys().GetRigidBody(name)->activate(true);
m_Physic.GetRigidBodys().GetRigidBody(name)->applyCentralImpulse(btVector3(DirectX::XMVectorGetX(impulse), DirectX::XMVectorGetY(impulse), DirectX::XMVectorGetZ(impulse)));
}
return true;
}
bool SceneWorldData::ApplyForceToObject(std::string name, DirectX::FXMVECTOR force, DirectX::FXMVECTOR rel_position)
{
auto it = std::find_if(m_SceneObjects.begin(), m_SceneObjects.end(), [&name](const SceneObject& obj) {return obj.ObjectName == name; });
if (it != m_SceneObjects.end())
{
m_Physic.GetRigidBodys().GetRigidBody(name)->activate(true);
m_Physic.GetRigidBodys().GetRigidBody(name)->applyForce(btVector3(DirectX::XMVectorGetX(force), DirectX::XMVectorGetY(force), DirectX::XMVectorGetZ(force)), btVector3(DirectX::XMVectorGetX(rel_position), DirectX::XMVectorGetY(rel_position), DirectX::XMVectorGetZ(rel_position)));
}
return true;
}
bool SceneWorldData::ApplyImpulseToObject(std::string name, DirectX::FXMVECTOR impulse, DirectX::FXMVECTOR rel_position)
{
auto it = std::find_if(m_SceneObjects.begin(), m_SceneObjects.end(), [&name](const SceneObject& obj) {return obj.ObjectName == name; });
if (it != m_SceneObjects.end())
{
m_Physic.GetRigidBodys().GetRigidBody(name)->activate(true);
m_Physic.GetRigidBodys().GetRigidBody(name)->applyImpulse(btVector3(DirectX::XMVectorGetX(impulse), DirectX::XMVectorGetY(impulse), DirectX::XMVectorGetZ(impulse)), btVector3(DirectX::XMVectorGetX(rel_position), DirectX::XMVectorGetY(rel_position), DirectX::XMVectorGetZ(rel_position)));
}
return true;
}
void SceneWorldData::SetPositionFromObject(std::string name, DirectX::FXMVECTOR position)
{
auto it = std::find_if(m_SceneObjects.begin(), m_SceneObjects.end(), [&name](const SceneObject& obj) {return obj.ObjectName == name; });
if (it != m_SceneObjects.end())
{
XMStoreFloat3(&it->Position, position);
DirectX::XMMATRIX TranslateMatrix;
TranslateMatrix = DirectX::XMMatrixTranslation(it->Position.x, it->Position.y, it->Position.z);
DirectX::XMMATRIX RotationMatrix = DirectX::XMMatrixRotationQuaternion(DirectX::XMLoadFloat4(&it->QuaternionRotation));
DirectX::XMMATRIX worldMatrix = DirectX::XMMatrixIdentity() * RotationMatrix * TranslateMatrix;
XMStoreFloat4x4(&it->WorldMatrix, worldMatrix);
}
}
void SceneWorldData::SetRotationFromObject(std::string name, DirectX::FXMVECTOR rotation)
{
auto it = std::find_if(m_SceneObjects.begin(), m_SceneObjects.end(), [&name](const SceneObject& obj) {return obj.ObjectName == name; });
if (it != m_SceneObjects.end())
{
XMStoreFloat4(&it->QuaternionRotation, rotation);
DirectX::XMMATRIX TranslateMatrix;
TranslateMatrix = DirectX::XMMatrixTranslation(it->Position.x, it->Position.y, it->Position.z);
DirectX::XMMATRIX RotationMatrix = DirectX::XMMatrixRotationQuaternion(rotation);
DirectX::XMMATRIX worldMatrix = DirectX::XMMatrixIdentity() * RotationMatrix * TranslateMatrix;
XMStoreFloat4x4(&it->WorldMatrix, worldMatrix);
}
}
void SceneWorldData::SetPositionFromObject(int objectIndex, DirectX::FXMVECTOR position)
{
XMStoreFloat3(&m_SceneObjects[objectIndex].Position, position);
DirectX::XMMATRIX TranslateMatrix;
TranslateMatrix = DirectX::XMMatrixTranslation(m_SceneObjects[objectIndex].Position.x, m_SceneObjects[objectIndex].Position.y, m_SceneObjects[objectIndex].Position.z);
DirectX::XMMATRIX RotationMatrix = DirectX::XMMatrixRotationQuaternion(DirectX::XMLoadFloat4(&m_SceneObjects[objectIndex].QuaternionRotation));
DirectX::XMMATRIX worldMatrix = DirectX::XMMatrixIdentity() * RotationMatrix * TranslateMatrix;
XMStoreFloat4x4(&m_SceneObjects[objectIndex].WorldMatrix, worldMatrix);
}
void SceneWorldData::SetRotationFromObject(int objectIndex, DirectX::FXMVECTOR rotation)
{
XMStoreFloat4(&m_SceneObjects[objectIndex].QuaternionRotation, rotation);
DirectX::XMMATRIX TranslateMatrix;
TranslateMatrix = DirectX::XMMatrixTranslation(m_SceneObjects[objectIndex].Position.x, m_SceneObjects[objectIndex].Position.y, m_SceneObjects[objectIndex].Position.z);
DirectX::XMMATRIX RotationMatrix = DirectX::XMMatrixRotationQuaternion(rotation);
DirectX::XMMATRIX worldMatrix = DirectX::XMMatrixIdentity() * RotationMatrix * TranslateMatrix;
XMStoreFloat4x4(&m_SceneObjects[objectIndex].WorldMatrix, worldMatrix);
}
int SceneWorldData::GetNumberOfSceneObjects()
{
return m_SceneObjects.size();
}
int SceneWorldData::GetSubsetCountOfObject(int subsetIndex)
{
SceneObjectType objectType = m_SceneObjects[subsetIndex].ObjectType;
switch (objectType)
{
case StaticObject:
{
return m_ModelManager.GetStaticModel(m_SceneObjects[subsetIndex].Filename).GetSubsetCount();
}
case AnimatedObject:
{
return m_ModelManager.GetAnimatedModel(m_SceneObjects[subsetIndex].Filename).GetSubsetCount();
}
case TerrainObject:
{
return m_ModelManager.GetTerrainModel(m_SceneObjects[subsetIndex].Filename).GetSubsetCount();
}
default:
{
return 0;
}
}
}
SceneObjectData SceneWorldData::GetSubsetObjectData(MaterialManager* materialManager, int objectIndex, int subsetIndex)
{
SceneObjectData TempObjectData;
SceneObjectType& objectType = m_SceneObjects[objectIndex].ObjectType;
switch (objectType)
{
case StaticObject:
{
TempObjectData.ObjectRenderData = m_ModelManager.GetStaticModel(m_SceneObjects[objectIndex].Filename).GetSubsetRenderData(materialManager, subsetIndex);
break;
}
case AnimatedObject:
{
TempObjectData.ObjectRenderData = m_ModelManager.GetAnimatedModel(m_SceneObjects[objectIndex].Filename).GetSubsetRenderData(materialManager, subsetIndex);
break;
}
case TerrainObject:
{
TempObjectData.ObjectRenderData = m_ModelManager.GetTerrainModel(m_SceneObjects[objectIndex].Filename).GetSubsetRenderData(materialManager, subsetIndex);
break;
}
}
TempObjectData.WorldMatrix = m_SceneObjects[objectIndex].WorldMatrix;
TempObjectData.Position = m_SceneObjects[objectIndex].Position;
TempObjectData.QuaternionRotation = m_SceneObjects[objectIndex].QuaternionRotation;
TempObjectData.Scale = m_SceneObjects[objectIndex].Scale;
return TempObjectData;
}
DirectX::XMMATRIX SceneWorldData::GetObjectWorldMatrix(int objectIndex)
{
return XMLoadFloat4x4(&m_SceneObjects[objectIndex].WorldMatrix);
}
std::vector<PhysicDebugDraw::Lines>& SceneWorldData::GetDebugLinesToDraw()
{
return m_Physic.GetDebugLinesToDraw();
}
void SceneWorldData::PrepareFrameRenderData(MaterialManager* MaterialManager, float screenDepth, DirectX::FXMVECTOR CameraPos, DirectX::CXMMATRIX viewMatrix, DirectX::CXMMATRIX projectionMatrix)
{
m_FrustumCulling.ConstructFrustum(screenDepth, viewMatrix, projectionMatrix);
// Add the scene objects to their corresponding frame buffer.
for (int objectIndex = 0; objectIndex < m_SceneObjects.size(); objectIndex++)
{
if (TestIfSceneObjectIsInFrustum(m_SceneObjects[objectIndex]))
{
for (int subIndex = 0; subIndex < GetSubsetCountOfObject(objectIndex); subIndex++)
{
SceneObjectData ObjectData = GetSubsetObjectData(MaterialManager, objectIndex, subIndex);
if (ObjectData.ObjectRenderData.Material.RenderForward == false && ObjectData.ObjectRenderData.Material.IsTransparent == false)
{
m_DeferredFrameRenderData.push_back(ObjectData);
}
if (ObjectData.ObjectRenderData.Material.RenderForward == true && ObjectData.ObjectRenderData.Material.IsTransparent == false)
{
m_ForwardFrameRenderData.push_back(ObjectData);
}
if (ObjectData.ObjectRenderData.Material.IsTransparent == true)
{
m_TransparentFrameRenderData.push_back(ObjectData);
}
}
}
}
// Add the scene lights to their corresponding frame buffer.
for (int lightIndex = 0; lightIndex < m_LightManager.GetNumberOfDirectionalLights(); lightIndex++)
{
m_FrameDirectionalLightData.push_back(m_LightManager.GetDirectionalLightData(lightIndex));
}
for (int lightIndex = 0; lightIndex < m_LightManager.GetNumberOfPointLights(); lightIndex++)
{
m_FramePointLightData.push_back(m_LightManager.GetPointLightData(lightIndex));
}
for (int lightIndex = 0; lightIndex < m_LightManager.GetNumberOfSpotLights(); lightIndex++)
{
m_FrameSpotLightData.push_back(m_LightManager.GetSpotLightData(lightIndex));
}
for (int lightIndex = 0; lightIndex < m_LightManager.GetNumberOfCapsuleLights(); lightIndex++)
{
m_FrameCapsuleLightData.push_back(m_LightManager.GetCapsuleLightData(lightIndex));
}
for (int lightIndex = 0; lightIndex < m_LightManager.GetNumberOfImageBasedLights(); lightIndex++)
{
m_FrameImageBasedLightData.push_back(m_LightManager.GetIBLData(lightIndex));
}
SortTransparentFrameRenderDataByDepthFromCamera(CameraPos);
}
void SceneWorldData::SortTransparentFrameRenderDataByDepthFromCamera(DirectX::FXMVECTOR CameraPos)
{
struct DepthData
{
float Depth;
int ObjectIndex;
DepthData(float k, const int& s) : Depth(k), ObjectIndex(s) {}
};
struct greater_than_key
{
inline bool operator() (const DepthData& depthData1, const DepthData& depthData2)
{
return (depthData1.Depth > depthData2.Depth);
}
};
std::vector<DepthData> DepthSortVector;
for (int ObjIndex = 0; ObjIndex < m_TransparentFrameRenderData.size(); ObjIndex++)
{
float distX = DirectX::XMVectorGetX(XMLoadFloat3(&m_TransparentFrameRenderData[ObjIndex].Position)) - DirectX::XMVectorGetX(CameraPos);
float distY = DirectX::XMVectorGetY(XMLoadFloat3(&m_TransparentFrameRenderData[ObjIndex].Position)) - DirectX::XMVectorGetY(CameraPos);
float distZ = DirectX::XMVectorGetZ(XMLoadFloat3(&m_TransparentFrameRenderData[ObjIndex].Position)) - DirectX::XMVectorGetZ(CameraPos);
float Dist = distX*distX + distY*distY + distZ*distZ;
DepthSortVector.push_back(DepthData(Dist, ObjIndex));
}
std::sort(DepthSortVector.begin(), DepthSortVector.end(), greater_than_key());
std::vector<SceneObjectData> TempRenderDataSortVector;
for (int ObjIndex = 0; ObjIndex < m_TransparentFrameRenderData.size(); ObjIndex++)
{
TempRenderDataSortVector.push_back(m_TransparentFrameRenderData[DepthSortVector[ObjIndex].ObjectIndex]);
}
m_TransparentFrameRenderData = TempRenderDataSortVector;
return;
}
bool SceneWorldData::TestIfSceneObjectIsInFrustum(SceneObject & sceneObject)
{
float width = sceneObject.AABB_width;
float height = sceneObject.AABB_height;
float depth = sceneObject.AABB_depth;
switch (sceneObject.CullingType)
{
case CullPoint:
{
return m_FrustumCulling.CheckPoint(FrustumCulling::Point(sceneObject.Position.x, sceneObject.Position.y, sceneObject.Position.z));
break;
}
case CullCube:
{
return m_FrustumCulling.CheckCube(FrustumCulling::Cube(sceneObject.Position.x, sceneObject.Position.y, sceneObject.Position.z, max(max((width / 2), (depth / 2)), (height / 2))));
break;
}
case CullSphere:
{
return m_FrustumCulling.CheckSphere(FrustumCulling::Sphere(sceneObject.Position.x, sceneObject.Position.y, sceneObject.Position.z, max(max((width / 2), (depth / 2)), (height / 2))));
break;
}
case CullBox:
{
return m_FrustumCulling.CheckRectangle(FrustumCulling::Rectangle(sceneObject.Position.x, sceneObject.Position.y, sceneObject.Position.z, (width / 2), (height / 2), (depth / 2)));
break;
}
default:
break;
}
return false;
}
void SceneWorldData::ClearSceneRenderData()
{
// Clear all frame buffers.
m_DeferredFrameRenderData.clear();
m_ForwardFrameRenderData.clear();
m_TransparentFrameRenderData.clear();
m_FrameDirectionalLightData.clear();
m_FrameImageBasedLightData.clear();
m_FramePointLightData.clear();
m_FrameCapsuleLightData.clear();
m_FrameSpotLightData.clear();
}
std::vector<SceneObjectData>& SceneWorldData::GetDeferredFrameRenderData()
{
return m_DeferredFrameRenderData;
}
std::vector<SceneObjectData>& SceneWorldData::GetForwardFrameRenderData()
{
return m_ForwardFrameRenderData;
}
std::vector<SceneObjectData>& SceneWorldData::GetTransparentFrameRenderData()
{
return m_TransparentFrameRenderData;
}
std::vector<DirectionalLightData>& SceneWorldData::GetFrameDirectionalLightData()
{
return m_FrameDirectionalLightData;
}
std::vector<ImageBasedLightData>& SceneWorldData::GetFrameImageBasedLightData()
{
return m_FrameImageBasedLightData;
}
std::vector<PointLightData>& SceneWorldData::GetFramePointLightData()
{
return m_FramePointLightData;
}
std::vector<CapsuleLightData>& SceneWorldData::GetFrameCapsuleLightData()
{
return m_FrameCapsuleLightData;
}
std::vector<SpotLightData>& SceneWorldData::GetFrameSpotLightData()
{
return m_FrameSpotLightData;
}
void SceneWorldData::UpdatePhysic(float deltaTime)
{
// Get rigid body from the physic world.
RigidBodys bodys = m_Physic.GetRigidBodys();
// Update the bullet physic engine.
m_Physic.UpdateWorld(deltaTime);
// Update scene objects according to physics
for (auto it = m_SceneObjects.begin(); it < m_SceneObjects.end(); it++)
{
DirectX::XMStoreFloat3(&it->Position, bodys.GetRigidBodyPosition(it->ObjectName));
DirectX::XMStoreFloat4(&it->QuaternionRotation, bodys.GetRigidBodyRotation(it->ObjectName));
DirectX::XMStoreFloat4x4(&it->WorldMatrix, bodys.GetRigidBodyTransformMatrix(it->ObjectName));
}
}
LightManager& SceneWorldData::GetLightManager()
{
return m_LightManager;
}
void SceneWorldData::UpdateAnimations(ID3D11DeviceContext* deviceContext, float deltaTime, int animSet)
{
for (int i = 0; i < m_SceneObjects.size(); i++)
{
SceneObjectType objectType = m_SceneObjects[i].ObjectType;
switch (objectType)
{
case AnimatedObject:
{
m_ModelManager.GetAnimatedModel(m_SceneObjects[i].ObjectName).UpdateAnimation(deviceContext, deltaTime, animSet);
break;
}
}
}
}
| 27.504673 | 351 | 0.744856 | [
"object",
"vector",
"model",
"transform"
] |
51969953a4e53d8d0a011b773ed23152e4ecb91c | 4,458 | cc | C++ | src/operator/numpy/np_delete_op.cc | wms2537/incubator-mxnet | b7d7e02705deb1dc4942bf39efc19f133e2181f7 | [
"Apache-2.0",
"MIT"
] | 1 | 2019-12-20T11:25:06.000Z | 2019-12-20T11:25:06.000Z | src/operator/numpy/np_delete_op.cc | wms2537/incubator-mxnet | b7d7e02705deb1dc4942bf39efc19f133e2181f7 | [
"Apache-2.0",
"MIT"
] | null | null | null | src/operator/numpy/np_delete_op.cc | wms2537/incubator-mxnet | b7d7e02705deb1dc4942bf39efc19f133e2181f7 | [
"Apache-2.0",
"MIT"
] | null | null | null | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*!
* Copyright (c) 2019 by Contributors
* \file np_delete_op.cc
* \brief CPU Implementation of numpy insert operations
*/
#include <vector>
#include "./np_delete_op-inl.h"
namespace mxnet {
namespace op {
DMLC_REGISTER_PARAMETER(NumpyDeleteParam);
bool NumpyDeleteType(const nnvm::NodeAttrs& attrs,
std::vector<int>* in_type,
std::vector<int>* out_type) {
const NumpyDeleteParam& param = nnvm::get<NumpyDeleteParam>(attrs.parsed);
int insize = (param.step.has_value() || param.int_ind.has_value()) ? 1 : 2;
CHECK_EQ(in_type->size(), insize);
CHECK_EQ(out_type->size(), 1U);
if (insize == 3) {
CHECK_NE((*in_type)[1], -1) << "Index type must be set for insert operator\n";
CHECK(((*in_type)[1] == mshadow::DataType<int64_t>::kFlag) ||
((*in_type)[1] == mshadow::DataType<int32_t>::kFlag))
<< "Index type only support int32 or int64.\n";
}
TYPE_ASSIGN_CHECK(*out_type, 0, (*in_type)[0]);
TYPE_ASSIGN_CHECK(*in_type, 0, (*out_type)[0]);
return (*in_type)[0] != -1;
}
inline bool NumpyDeleteStorageType(const nnvm::NodeAttrs& attrs,
const int dev_mask,
DispatchMode* dispatch_mode,
std::vector<int>* in_attrs,
std::vector<int>* out_attrs) {
const NumpyDeleteParam& param = nnvm::get<NumpyDeleteParam>(attrs.parsed);
unsigned int insize = (param.step.has_value() || param.int_ind.has_value()) ? 1U : 2U;
CHECK_EQ(in_attrs->size(), insize);
CHECK_EQ(out_attrs->size(), 1U);
for (int& attr : *in_attrs) {
CHECK_EQ(attr, kDefaultStorage) << "Only default storage is supported";
}
for (int& attr : *out_attrs) {
attr = kDefaultStorage;
}
*dispatch_mode = DispatchMode::kFComputeEx;
return true;
}
NNVM_REGISTER_OP(_npi_delete)
.describe(
R"code(Delete values along the given axis before the given indices.)code" ADD_FILELINE)
.set_attr_parser(ParamParser<NumpyDeleteParam>)
.set_num_inputs([](const NodeAttrs& attrs) {
const NumpyDeleteParam& params = nnvm::get<NumpyDeleteParam>(attrs.parsed);
return (params.step.has_value() || params.int_ind.has_value()) ? 1U : 2U;
})
.set_num_outputs(1)
.set_attr<nnvm::FListInputNames>("FListInputNames",
[](const NodeAttrs& attrs) {
const NumpyDeleteParam& params =
nnvm::get<NumpyDeleteParam>(attrs.parsed);
return (params.step.has_value() ||
params.int_ind.has_value())
? std::vector<std::string>{"arr"}
: std::vector<std::string>{"arr", "obj"};
})
.set_attr<nnvm::FInferType>("FInferType", NumpyDeleteType)
.set_attr<mxnet::FComputeEx>("FComputeEx<cpu>", NumpyDeleteCompute<cpu>)
.set_attr<FInferStorageType>("FInferStorageType", NumpyDeleteStorageType)
.set_attr<FResourceRequest>("FResourceRequest",
[](const NodeAttrs& attrs) {
return std::vector<ResourceRequest>{ResourceRequest::kTempSpace};
})
.add_argument("arr", "NDArray-or-Symbol", "Input ndarray")
.add_argument("obj", "NDArray-or-Symbol", "Input ndarray")
.add_arguments(NumpyDeleteParam::__FIELDS__());
} // namespace op
} // namespace mxnet
| 43.705882 | 99 | 0.606999 | [
"vector"
] |
51a27b8767c5f1bdf5bfa9ffff1b16d435eab088 | 4,069 | cpp | C++ | src/forces/gravity.cpp | mattstvan/arc | 1e86947ba70bacd718dcbecbe08b5d4242fe8117 | [
"MIT"
] | null | null | null | src/forces/gravity.cpp | mattstvan/arc | 1e86947ba70bacd718dcbecbe08b5d4242fe8117 | [
"MIT"
] | null | null | null | src/forces/gravity.cpp | mattstvan/arc | 1e86947ba70bacd718dcbecbe08b5d4242fe8117 | [
"MIT"
] | 1 | 2022-03-31T02:27:33.000Z | 2022-03-31T02:27:33.000Z | #include <gravity.h>
/*
Gravity model functions
*/
/*
Default constructor
Sets central body to Earth with aspherical effects disabled
*/
GravityModel::GravityModel() {
this->body = EARTH;
this->model = J2;
this->is_aspherical = false;
this->degree = 0;
this->order = 0;
}
/*
Direct constructor
@param body Central body of this gravity source
@param is_aspherical If aspherical gravity should be modeled
@param degree Geopotential model degree
@param order Geopotential model order
*/
GravityModel::GravityModel(CelestialBody &body, GeopotentialModel model,
bool is_aspherical, int degree, int order) {
this->body = body;
this->model = model;
this->is_aspherical = is_aspherical;
this->degree = degree;
this->order = order;
}
/*
Calculate acceleration due to gravity, assuming a spherical body
@param sc_state Spacecraft ICRF state at which to calculate body gravity
@returns Vector of acceleration due to spherical gravity given state, in m/s^2
*/
Vector3 GravityModel::spherical(ICRF &sc_state) {
// If we are modelling central body gravity
if (sc_state.central_body.id == body.id) {
return sc_state.position.scale(-body.mu / pow(sc_state.position.mag(), 3));
} else {
// Get the position of the body at the spacecraft state's epoch,
// centered around the body the spacecraft is orbiting
ICRF body_state = body.propagate(sc_state.epoch)
.change_central_body(sc_state.central_body);
Vector3 spacecraft_centered_pos =
body_state.position.change_origin(sc_state.position);
double a_den = pow(spacecraft_centered_pos.mag(), 3.0);
double b_den = pow(body_state.position.mag(), 3.0);
// If this is central body gravity, b_den will be zero, causing a
// singularity
if (b_den == 0.0) {
b_den = 1.0;
}
Vector3 b = body_state.position.scale(-1.0 / b_den);
Vector3 grav_vector = spacecraft_centered_pos.scale(1.0 / a_den).add(b);
return grav_vector.scale(body.mu);
}
}
/*
Calculate the aspherical components of acceleration due to gravity
@param sc_state Spacecraft ICRF state at which to calculate body gravity
@returns Vector of acceleration due to aspherical gravity at given state, in
m/s^2
*/
Vector3 GravityModel::aspherical(ICRF &sc_state) {
// J2 Perturbation
// Ref: Curtis, H. (2013). Orbital mechanics for engineering students.
if (model == J2) {
// Body J2 value
double j2 = body.j2();
double rmag = sc_state.position.mag();
// Leading coefficient (same for all elements)
double coeff =
(3.0 / 2.0) * body.mu * j2 * pow(body.radius_equator, 2) / pow(rmag, 5);
// Initial acceleration vector elements
double a_x = 5.0 * pow(sc_state.position.z, 2) / pow(rmag, 2) - 1;
double a_y = 5.0 * pow(sc_state.position.z, 2) / pow(rmag, 2) - 1;
double a_z = 5.0 * pow(sc_state.position.z, 2) / pow(rmag, 2) - 3;
// Initial acceleration vector
Vector3 j2_vec{a_x, a_y, a_z};
// Scale by position and leading coefficient
return j2_vec.scale(coeff).scale(sc_state.position);
}
// Placeholder
return Vector3{};
}
/*
Calculate acceleration on a spacecraft due to gravity, given its ICRF state
@param sc_state Spacecraft ICRF state at which to calculate body gravity
@returns Vector of total acceleration due to gravity at given state, in m/s^2
*/
Vector3 GravityModel::acceleration(ICRF &state) {
// Empty acceleration vector
Vector3 accel;
// Get spherical gravity
Vector3 sph_grav = spherical(state);
accel = accel.add(sph_grav);
// If we are modeling aspherical effects
if (is_aspherical) {
Vector3 aspher = aspherical(state);
accel = accel.add(aspher);
}
return accel;
}
/*
GravityModel operator functions
*/
// I/O stream
std::ostream &operator<<(std::ostream &out, GravityModel &gm) {
out << "[GravityModel]" << std::endl
<< " Body: " << gm.body << std::endl
<< " Aspherical: " << gm.is_aspherical << std::endl
<< " Geopotential Degree/Order: " << gm.degree << "/" << gm.order;
return out;
} | 31.789063 | 80 | 0.68985 | [
"vector",
"model"
] |
51ac11025999874a1904c56479d6ab8ea868ca64 | 4,024 | cpp | C++ | src/utility/stdirectoryservices.cpp | Starstructor/starstructor-cpp | dc64a2ef9ff0990ebfeec845d2104f4fc9e7d1e7 | [
"MIT"
] | 6 | 2015-06-09T18:34:12.000Z | 2020-09-09T11:57:26.000Z | src/utility/stdirectoryservices.cpp | Starstructor/starstructor-cpp | dc64a2ef9ff0990ebfeec845d2104f4fc9e7d1e7 | [
"MIT"
] | 1 | 2017-01-24T09:05:20.000Z | 2017-01-24T09:05:20.000Z | src/utility/stdirectoryservices.cpp | Starstructor/starstructor-cpp | dc64a2ef9ff0990ebfeec845d2104f4fc9e7d1e7 | [
"MIT"
] | 3 | 2015-01-01T12:44:41.000Z | 2020-01-15T18:58:47.000Z | /*
Starstructor, the Starbound Toolset
Copyright (C) 2013-2014 Chris Stamford
Licensed under terms of The MIT License (MIT)
Source file contributers:
Chris Stamford contact: cstamford@gmail.com
*/
#include "utility/stdirectoryservices.hpp"
#include "utility/sttimer.hpp"
using std::lock_guard;
using std::mutex;
namespace Starstructor { namespace Utility {
DirectoryServices::DirectoryServices(const QDir& path, Utility::Logger& logger)
: m_logger(&logger)
{
rescanPath(path);
}
DirectoryServices::DirectoryServices(const QString& path, Utility::Logger& logger)
: DirectoryServices(QDir(path), logger)
{
}
void DirectoryServices::rescanPath(const QDir& path)
{
const QList<QString> filters = { "object", "material", "npc",
"structure", "dungeon", "world", "shipworld" };
QString msg = "Scanning for all files in " + path.path()
+ " with extensions:";
for (const auto& filter : filters)
{
msg += " ." + filter;
}
m_logger->writeLine(msg);
Timer timer;
const auto newFiles = getDirContents_r(path, filters);
m_logger->writeLine("Scanning complete in "
+ QString::number(timer.getTime()) + "ms. "
+ QString::number(m_files.count()) + " files found.");
lock_guard<mutex> lock(m_readWriteMutex);
m_files = std::move(newFiles);
}
void DirectoryServices::rescanPath(const QString& path)
{
rescanPath(QDir(path));
}
QList<QFileInfo> DirectoryServices::getFiles(const DirectoryServicesFlags flags) const
{
// If the caller wants everything, just copy the list, rather than
// going through the hassle of applying filters to it
if (flags &
DirectoryServicesFlag::OBJECT & DirectoryServicesFlag::MATERIAL &
DirectoryServicesFlag::NPC & DirectoryServicesFlag::STRUCTURE &
DirectoryServicesFlag::DUNGEON & DirectoryServicesFlag::WORLD &
DirectoryServicesFlag::SHIPWORLD)
{
lock_guard<mutex> lock(m_readWriteMutex);
return m_files;
}
QList<QString> filters;
if (flags & DirectoryServicesFlag::OBJECT)
filters.push_back("object");
if (flags & DirectoryServicesFlag::MATERIAL)
filters.push_back("material");
if (flags & DirectoryServicesFlag::NPC)
filters.push_back("npc");
if (flags & DirectoryServicesFlag::STRUCTURE)
filters.push_back("structure");
if (flags & DirectoryServicesFlag::DUNGEON)
filters.push_back("dungeon");
if (flags & DirectoryServicesFlag::WORLD)
filters.push_back("world");
if (flags & DirectoryServicesFlag::SHIPWORLD)
filters.push_back("shipworld");
return getFilteredList(filters);
}
QList<QFileInfo> DirectoryServices::getFilteredList(const QList<QString>& filters) const
{
QList<QFileInfo> newList;
lock_guard<mutex> lock(m_readWriteMutex);
for (const auto& file : m_files)
{
const QString suffix = file.suffix();
for (const auto& filter : filters)
{
if (suffix == filter)
newList.push_back(file.filePath());
}
}
return newList;
}
QList<QFileInfo> DirectoryServices::getDirContents_r(const QDir& directory,
const QList<QString>& filters) const
{
const QList<QFileInfo> fileList = directory.entryInfoList(
QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot, QDir::DirsFirst);
QList<QFileInfo> matchingFiles;
for (const auto& file : fileList)
{
if (file.isDir())
{
const auto recMatchingFiles = getDirContents_r(
QDir(file.absoluteFilePath()), filters);
if (!recMatchingFiles.isEmpty())
matchingFiles += recMatchingFiles;
}
else
{
const QString suffix = file.suffix();
for (const auto& filter : filters)
{
if (suffix == filter)
matchingFiles.push_back(file);
}
}
}
return matchingFiles;
}
}
}
| 25.794872 | 88 | 0.645626 | [
"object"
] |
51b1c813860b7742e1809c560490397be2d24041 | 14,915 | cpp | C++ | src/gameutils/microscenarioprovider.cpp | unghee/TorchCraftAI | e6d596483d2a9a8b796765ed98097fcae39b6ac0 | [
"MIT"
] | 629 | 2018-11-19T21:03:01.000Z | 2022-02-25T03:31:40.000Z | src/gameutils/microscenarioprovider.cpp | unghee/TorchCraftAI | e6d596483d2a9a8b796765ed98097fcae39b6ac0 | [
"MIT"
] | 27 | 2018-11-23T22:49:28.000Z | 2020-05-15T21:09:30.000Z | src/gameutils/microscenarioprovider.cpp | unghee/TorchCraftAI | e6d596483d2a9a8b796765ed98097fcae39b6ac0 | [
"MIT"
] | 129 | 2018-11-22T01:16:56.000Z | 2022-03-29T15:24:16.000Z | /*
* Copyright (c) 2017-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "microscenarioprovider.h"
#include "buildtype.h"
#include "microplayer.h"
#include "modules/once.h"
namespace cherrypi {
namespace {
// We don't want to reuse the same BWAPI instances too much, because the
// internal structures might overflow (dead units are not freed, for example)
//
// The BWAPI ID limit is 10,000 -- this smaller number gives us some buffer
// against eg. Scarabs, other units that get produced during the game
int constexpr kMaxUnits = 9000;
} // namespace
// It's possible to run this from not the rootdir of the repository,
// in which case you can set the mapPathPrefix to where the maps should be
// found. This is just the path to your cherrypi directory
void MicroScenarioProvider::setMapPathPrefix(const std::string& prefix) {
mapPathPrefix_ = prefix;
}
std::unique_ptr<Reward> MicroScenarioProvider::getReward() const {
return scenarioNow_.reward();
}
void MicroScenarioProvider::endScenario() {
VLOG(3) << "endScenario()";
if (!player1_ || !player2_) {
return;
}
VLOG(4) << "Game ended on frame " << player1_->state()->currentFrame();
microPlayer1().onGameEnd();
microPlayer2().onGameEnd();
if (launchedWithReplay()) {
player1_->queueCmds({{tc::BW::Command::Quit}});
player2_->queueCmds({{tc::BW::Command::Quit}});
// Send commands, and wait for game to finish properly
while (!player1_->state()->gameEnded()) {
player1_->step();
if (!player2_->state()->gameEnded()) {
player2_->step();
}
}
} else if (!needNewGame_) {
killAllUnits();
}
player1_.reset();
player2_.reset();
}
void MicroScenarioProvider::step(
std::shared_ptr<BasePlayer> player1,
std::shared_ptr<BasePlayer> player2,
int times) {
if (player1->state()->gameEnded() || player2->state()->gameEnded()) {
throw std::runtime_error("OpenBW process might be dead.");
}
for (int i = 0; i < times; ++i) {
VLOG(6) << "Stepping players.";
player1->step();
player2->step();
}
}
void MicroScenarioProvider::stepUntilCommandsReflected(
std::shared_ptr<BasePlayer> player1,
std::shared_ptr<BasePlayer> player2) {
auto frameNow = [&]() { return player1->state()->currentFrame(); };
int frameBefore;
int frameGoal = frameNow() + 1 + player1->state()->latencyFrames();
do {
frameBefore = frameNow();
step(player1, player2, 1);
} while (frameNow() != frameBefore && frameNow() <= frameGoal &&
!player1->state()->gameEnded());
}
void MicroScenarioProvider::endGame() {
VLOG(3) << "endGame()";
++resetCount_;
endScenario();
unitsThisGame_ = 0;
game_.reset();
}
void MicroScenarioProvider::killAllUnits() {
VLOG(3) << "killAllUnits()";
if (!player1_ || !player2_) {
return;
}
if (player1_->state()->gameEnded()) {
return;
}
auto killPlayerUnits = [&](auto& player) {
std::vector<tc::Client::Command> killCommands;
auto killUnits = [&](auto& units) {
for (const auto& unit : units) {
killCommands.emplace_back(
tc::BW::Command::CommandOpenbw,
tc::BW::OpenBWCommandType::KillUnit,
unit->id);
}
};
auto& unitsInfo = player->state()->unitsInfo();
killUnits(unitsInfo.myUnits());
killUnits(unitsInfo.neutralUnits());
player->queueCmds(std::move(killCommands));
step(player1_, player2_, 1);
};
killPlayerUnits(player1_);
killPlayerUnits(player2_);
stepUntilCommandsReflected(player1_, player2_);
}
void MicroScenarioProvider::createNewPlayers() {
VLOG(3) << "createNewPlayers()";
endScenario();
player1_ = std::make_shared<MicroPlayer>(client1_);
player2_ = std::make_shared<MicroPlayer>(client2_);
player1_->state()->setMapHack(true);
player2_->state()->setMapHack(true);
std::vector<tc::Client::Command> commands;
commands.emplace_back(tc::BW::Command::SetSpeed, 0);
commands.emplace_back(tc::BW::Command::SetGui, gui_);
commands.emplace_back(tc::BW::Command::SetCombineFrames, combineFrames_);
commands.emplace_back(tc::BW::Command::SetFrameskip, 1);
commands.emplace_back(tc::BW::Command::SetBlocking, true);
commands.emplace_back(tc::BW::Command::MapHack);
player1_->queueCmds(commands);
player2_->queueCmds(commands);
}
void MicroScenarioProvider::createNewGame() {
VLOG(3) << "createNewGame() on " << mapNow();
endGame();
lastMap_ = mapNow();
// Any race is fine for scenarios.
game_ = std::make_shared<GameMultiPlayer>(
mapPathPrefix_ + lastMap_,
tc::BW::Race::Terran,
tc::BW::Race::Terran,
scenarioNow_.gameType,
replay_,
gui_);
client1_ = game_->makeClient1();
client2_ = game_->makeClient2();
}
void MicroScenarioProvider::setupScenario() {
VLOG(3) << "setupScenario() #" << scenarioCount_;
++scenarioCount_;
auto info = setupScenario(player1_, player2_, scenarioNow_);
unitsThisGame_ += info.unitsCount;
unitsTotal_ += info.unitsCount;
if (info.hasAnyZergBuilding) {
needNewGame_ = true;
}
unitsSeenTotal_ += player1_->state()->unitsInfo().allUnitsEver().size();
}
MicroScenarioProvider::SetupScenarioResult MicroScenarioProvider::setupScenario(
std::shared_ptr<BasePlayer> player1,
std::shared_ptr<BasePlayer> player2,
FixedScenario const& scenario) {
SetupScenarioResult result;
bool queuedCommands = false;
auto queueCommands =
[&](const std::vector<torchcraft::Client::Command>& commands) {
player1->queueCmds(std::move(commands));
queuedCommands = queuedCommands || !commands.empty();
};
auto sendCommands = [&]() {
if (queuedCommands) {
VLOG(5) << "Sending commands";
step(player1, player2, 1);
queuedCommands = false;
}
};
auto getPlayerId = [&](int playerIndex) {
return (playerIndex == 0 ? player1 : player2)->state()->playerId();
};
// Add techs and upgrades first.
//
// We need to assign the state of *every* upgrade and tech, even ones not
// mentioned in the scenario description, because the level could have been
// raised in a previous episode.
for (int playerIndex = 0; playerIndex < int(scenario.players.size());
++playerIndex) {
VLOG(4) << "Setting techs for Player " << playerIndex;
for (auto* techType : buildtypes::allTechTypes) {
int techId = techType->tech;
int hasTech = false;
// Everyone always has these techs at the start of the game
if (techType != buildtypes::Defensive_Matrix &&
techType != buildtypes::Healing &&
techType != buildtypes::Scanner_Sweep &&
techType != buildtypes::Dark_Swarm &&
techType != buildtypes::Archon_Warp &&
techType != buildtypes::Dark_Archon_Meld &&
techType != buildtypes::Feedback &&
techType != buildtypes::Infestation &&
techType != buildtypes::Parasite) {
for (auto& techScenario : scenario.players[playerIndex].techs) {
if (techScenario == techId) {
VLOG(4) << "Adding tech for player " << playerIndex << ": "
<< techId;
hasTech = true;
break;
}
}
}
VLOG(7) << "Setting tech status for " << techType->name << " to "
<< hasTech;
queueCommands({torchcraft::Client::Command(
torchcraft::BW::Command::CommandOpenbw,
torchcraft::BW::OpenBWCommandType::SetPlayerResearched,
getPlayerId(playerIndex),
techId,
hasTech)});
}
sendCommands();
VLOG(4) << "Setting upgrades for Player " << playerIndex;
for (auto* upgradeType : buildtypes::allUpgradeTypes) {
if (upgradeType->level > 1) {
continue;
}
int upgradeId = upgradeType->upgrade;
int level = 0;
for (auto& upgradeScenario : scenario.players[playerIndex].upgrades) {
if (upgradeScenario.upgradeType == upgradeId) {
level = upgradeScenario.level;
VLOG(4) << "Adding upgrade for player " << playerIndex << ": "
<< upgradeId << " #" << level;
break;
}
}
queueCommands({torchcraft::Client::Command(
torchcraft::BW::Command::CommandOpenbw,
torchcraft::BW::OpenBWCommandType::SetPlayerUpgradeLevel,
getPlayerId(playerIndex),
upgradeId,
level)});
}
sendCommands();
}
// Next, we spawn units.
//
// Spawning units is tricky. There are a few considerations:
// * There's a maximum (About 128) commands that can be processed each frame.
// * We don't want one player's units to be around for too long before the
// other player's (to minimize the extra time to react/attack).
// * Building placement can be blocked by other units, so they need to
// spawn first.
// * If an add-on is spawned without its building, it will enter as neutral,
// which causes issues (IIRC UnitsInfo can't handle the change of owner).
//
// So, here are the distinct tiers in which we'll spawn units:
// * Non-combat buildings (because units can block buildings)
// * Player 0 non-addon buildings (because addons spawn neutral otherwise)
// * Player 1 non-addon buildings
// * Addon buildings
// * Combat buildings (Last, to minimize frames they could spend attacking)
// * Player 0 non-workers
// * Player 1 non-workers
// * Player 0 workers
// * Player 1 workers
auto queueUnits = [&](const std::vector<SpawnPosition>& units,
std::shared_ptr<BasePlayer> player) {
result.unitsCount += units.size();
queueCommands(OnceModule::makeSpawnCommands(
units, player->state(), player->state()->playerId()));
};
auto extractUnits = [](std::vector<SpawnPosition>& units,
std::function<bool(const SpawnPosition&)> predicate) {
VLOG(7) << "Extracting from " << units.size() << " units";
std::vector<SpawnPosition> output;
unsigned i = 0;
while (i < units.size()) {
if (predicate(units[i])) {
output.push_back(units[i]);
std::iter_swap(units.begin() + i, units.end() - 1);
units.pop_back();
} else {
++i;
}
}
VLOG(7) << units.size() << " units left after extraction. Took "
<< output.size() << " units.";
return output;
};
// Predicates for spawning units in tiers
auto producesCreep = [](const SpawnPosition& unit) {
auto* type = getUnitBuildType(unit.type);
return type->producesCreep;
};
auto isNonCombatNonAddonBuilding = [](const SpawnPosition& unit) {
auto* type = getUnitBuildType(unit.type);
return type->isBuilding && !type->isAddon && !type->hasAirWeapon &&
!type->hasGroundWeapon && type != buildtypes::Terran_Bunker &&
type != buildtypes::Protoss_Shield_Battery;
};
auto isAddon = [](const SpawnPosition& unit) {
auto* type = getUnitBuildType(unit.type);
return type->isAddon;
};
auto isCombatBuilding = [](const SpawnPosition& unit) {
auto* type = getUnitBuildType(unit.type);
return type->isBuilding && !type->isAddon;
};
auto isNonWorker = [](const SpawnPosition& unit) {
auto* type = getUnitBuildType(unit.type);
return type != buildtypes::Terran_SCV &&
type != buildtypes::Protoss_Probe && type != buildtypes::Zerg_Drone;
};
auto isAnything = [](const SpawnPosition& unit) { return true; };
std::vector<SpawnPosition> units0(scenario.players[0].units);
std::vector<SpawnPosition> units1(scenario.players[1].units);
std::vector<std::tuple<int, std::vector<SpawnPosition>>> tiers;
// Semi-hack: OpenBW chokes when destroying a bunch of creep-producing
// buildings at the same time. Let's not spawn them until we can fix that.
auto zergBuildings0 = extractUnits(units0, producesCreep);
auto zergBuildings1 = extractUnits(units1, producesCreep);
result.hasAnyZergBuilding =
!zergBuildings0.empty() || !zergBuildings1.empty();
// Add-ons still aren't getting assigned to buildings properly.
extractUnits(units0, isAddon);
extractUnits(units1, isAddon);
tiers.emplace_back(
std::make_tuple(0, extractUnits(units0, isNonCombatNonAddonBuilding)));
tiers.emplace_back(
std::make_tuple(1, extractUnits(units1, isNonCombatNonAddonBuilding)));
tiers.emplace_back(std::make_tuple(0, extractUnits(units0, isAddon)));
tiers.emplace_back(std::make_tuple(1, extractUnits(units1, isAddon)));
tiers.emplace_back(0, zergBuildings0);
tiers.emplace_back(1, zergBuildings1);
tiers.emplace_back(
std::make_tuple(0, extractUnits(units0, isCombatBuilding)));
tiers.emplace_back(
std::make_tuple(1, extractUnits(units1, isCombatBuilding)));
tiers.emplace_back(std::make_tuple(0, extractUnits(units0, isNonWorker)));
tiers.emplace_back(std::make_tuple(1, extractUnits(units1, isNonWorker)));
tiers.emplace_back(std::make_tuple(0, extractUnits(units0, isAnything)));
tiers.emplace_back(std::make_tuple(1, extractUnits(units1, isAnything)));
for (auto i = 0u; i < tiers.size(); ++i) {
auto& tier = tiers[i];
int playerIndex = std::get<0>(tier);
auto& units = std::get<1>(tier);
VLOG(4) << "Spawning " << units.size() << " units for player "
<< playerIndex << " in Tier " << i;
queueUnits(units, playerIndex == 0 ? player1 : player2);
sendCommands();
}
// Lastly, add any scenario-specific functions
for (auto& stepFunction : scenario.stepFunctions) {
VLOG(4) << "Running a step function";
player1->addModule(std::make_shared<LambdaModule>(std::move(stepFunction)));
}
stepUntilCommandsReflected(player1, player2);
return result;
}
std::pair<std::shared_ptr<BasePlayer>, std::shared_ptr<BasePlayer>>
MicroScenarioProvider::startNewScenario(
const std::function<void(BasePlayer*)>& setup1,
const std::function<void(BasePlayer*)>& setup2) {
VLOG(3) << "startNewScenario()";
VLOG(4) << "Total units spawned: " << unitsThisGame_ << "/" << unitsTotal_;
VLOG(4) << "Total units seen all time: " << unitsSeenTotal_;
scenarioNow_ = getFixedScenario();
bool mapChanged = lastMap_ != mapNow();
bool exceededUnitLimit = unitsThisGame_ > kMaxUnits;
if (mapChanged) {
VLOG(4) << "Map changed from " << lastMap_ << " to " << mapNow();
}
if (exceededUnitLimit) {
VLOG(4) << "Exceeded unit limit";
}
needNewGame_ =
launchedWithReplay() || !game_ || mapChanged || exceededUnitLimit;
if (needNewGame_) {
endGame();
} else {
endScenario();
}
if (needNewGame_) {
createNewGame();
}
createNewPlayers();
setup1(player1_.get());
setup2(player2_.get());
setupScenario();
microPlayer1().onGameStart();
microPlayer2().onGameStart();
return {player1_, player2_};
}
} // namespace cherrypi
| 33.820862 | 80 | 0.655783 | [
"vector"
] |
51b36f99226263e87fc92b4dab05343d46eb5c6f | 3,734 | cpp | C++ | lib/Interpreter/Program.cpp | kwalberg/allium | 13b98d56fe480f0e87a45cf870a76ef7a96f398d | [
"MIT"
] | null | null | null | lib/Interpreter/Program.cpp | kwalberg/allium | 13b98d56fe480f0e87a45cf870a76ef7a96f398d | [
"MIT"
] | null | null | null | lib/Interpreter/Program.cpp | kwalberg/allium | 13b98d56fe480f0e87a45cf870a76ef7a96f398d | [
"MIT"
] | null | null | null | #include <iostream>
#include "Interpreter/Program.h"
#include "Interpreter/WitnessProducer.h"
namespace interpreter {
bool Program::prove(const Expression &expr) {
// TODO: if `main` ever takes arguments, they need to be allocated here.
std::vector<Value> mainArgs;
if(witnesses(*this, expr, mainArgs).next()) {
return true;
} else {
return false;
}
}
bool operator==(const Implication &left, const Implication &right) {
return left.head == right.head && left.body == right.body &&
left.variableCount == right.variableCount;
}
bool operator!=(const Implication &left, const Implication &right) {
return !(left == right);
}
bool operator==(const Predicate &left, const Predicate &right) {
return left.implications == right.implications;
}
bool operator!=(const Predicate &left, const Predicate &right) {
return !(left == right);
}
bool operator==(const Program &left, const Program &right) {
return left.predicates == right.predicates &&
left.entryPoint == right.entryPoint;
}
bool operator!=(const Program &left, const Program &right) {
return !(left == right);
}
std::ostream& operator<<(std::ostream &out, const Expression &expr) {
return expr.match<std::ostream&>(
[&](TruthValue tv) -> std::ostream& { return out << tv; },
[&](PredicateReference pr) -> std::ostream& { return out << pr; },
[&](EffectCtorRef ecr) -> std::ostream& { return out << ecr; },
[&](Conjunction conj) -> std::ostream& { return out << conj; }
);
}
std::ostream& operator<<(std::ostream &out, const ConstructorRef &ctor) {
out << ctor.index << "(";
for(const auto &arg : ctor.arguments) out << arg << ", ";
return out << ")";
}
std::ostream& operator<<(std::ostream &out, const String &str) {
return out << str.value;
}
std::ostream& operator<<(std::ostream &out, const Int &i) {
return out << i.value;
}
std::ostream& operator<<(std::ostream &out, const VariableRef &vr) {
if(vr.index == VariableRef::anonymousIndex)
out << "var _";
else
out << "var " << vr.index;
if(vr.isDefinition)
out << " def";
return out;
}
std::ostream& operator<<(std::ostream &out, const Value &val) {
return val.match<std::ostream&>(
[&](ConstructorRef cr) -> std::ostream& { return out << cr; },
[&](String str) -> std::ostream& { return out << str; },
[&](Int i) -> std::ostream& { return out << i; },
[&](Value *v) -> std::ostream& { return out << "ptr " << *v; },
[&](VariableRef vr) -> std::ostream& { return out << vr; });
}
std::ostream& operator<<(std::ostream &out, const TruthValue &tv) {
return out << (tv.value ? "true" : "false");
}
std::ostream& operator<<(std::ostream &out, const PredicateReference &pr) {
out << pr.index << "(";
for(const auto &arg : pr.arguments) out << arg << ", ";
return out << ")";
}
std::ostream& operator<<(std::ostream &out, const EffectCtorRef &ecr) {
return out << "do " << ecr.effectIndex << "." << ecr.effectCtorIndex;
}
std::ostream& operator<<(std::ostream &out, const Conjunction &conj) {
return out << "(" << conj.getLeft() << " and " << conj.getRight() << ")";
}
std::ostream& operator<<(std::ostream &out, const Implication &impl) {
return out << impl.head << " <- " << impl.body;
}
std::ostream& operator<<(std::ostream &out, const Predicate &p) {
out << "pred {\n";
for(const auto &impl : p.implications) out << " " << impl << "\n";
return out << "}";
}
std::ostream& operator<<(std::ostream &out, const Program &prog) {
out << "Program\n";
for(const auto &pred : prog.predicates)
out << " " << pred << "\n";
return out;
}
} // namespace interpreter
| 30.357724 | 77 | 0.603107 | [
"vector"
] |
51b3f47000ea9d5eafcbcea40e0b1a39a35ff492 | 4,162 | cpp | C++ | client/testMain.cpp | jgbarbosa/display-wall | ed5c42a16a20065747707ea5bec969d799609d44 | [
"MIT"
] | 3 | 2017-03-14T23:19:49.000Z | 2017-03-27T09:53:01.000Z | client/testMain.cpp | jgbarbosa/display-wall | ed5c42a16a20065747707ea5bec969d799609d44 | [
"MIT"
] | null | null | null | client/testMain.cpp | jgbarbosa/display-wall | ed5c42a16a20065747707ea5bec969d799609d44 | [
"MIT"
] | 1 | 2017-03-16T16:11:44.000Z | 2017-03-16T16:11:44.000Z | /*
Copyright (c) 2016-17 Ingo Wald
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 "mpiCommon/MPICommon.h"
#include "Client.h"
#include "ospcommon/tasking/parallel_for.h"
// std
#include <vector>
namespace ospray {
namespace dw {
using namespace ospcommon;
using std::cout;
using std::endl;
using std::flush;
void renderFrame(const MPI::Group &me, Client *client)
{
static size_t frameID = 0;
static double lastTime = getSysTime();
assert(client);
const vec2i totalPixels = client->totalPixelsInWall();
vec2i tileSize(32);
// vec2i tileSize(160,10);
vec2i numTiles = divRoundUp(totalPixels,tileSize);
size_t tileCount = numTiles.product();
tasking::parallel_for(tileCount,[&](int tileID){
if ((tileID % me.size) != me.rank)
return;
PlainTile tile(tileSize);
const int tile_x = tileID % numTiles.x;
const int tile_y = tileID / numTiles.x;
tile.region.lower = vec2i(tile_x,tile_y)*tileSize;
tile.region.upper = min(tile.region.lower+tileSize,totalPixels);
for (int iy=tile.region.lower.y;iy<tile.region.upper.y;iy++)
for (int ix=tile.region.lower.x;ix<tile.region.upper.x;ix++) {
#if 0
int r = (frameID+ix) % 255;
int g = (frameID+iy) % 255;
int b = (frameID+ix+iy) % 255;
int rgba = (b<<16)+(g<<8)+(r<<0);
#else
int r = (frameID+(ix>>2)) % 255;
int g = (frameID+(iy>>2)) % 255;
int b = (frameID+(ix>>2)+(iy>>2)) % 255;
int rgba = (b<<16)+(g<<8)+(r<<0);
#endif
tile.pixel[(ix-tile.region.lower.x)+tileSize.x*(iy-tile.region.lower.y)] = rgba;
}
assert(client);
client->writeTile(tile);
});
++frameID;
double thisTime = getSysTime();
printf("done rendering frame %li (%f fps)\n",frameID,1.f/(thisTime-lastTime));
lastTime = thisTime;
// me.barrier();
client->endFrame();
}
extern "C" int main(int ac, char **av)
{
MPI::init(ac,av);
MPI::Group world(MPI_COMM_WORLD);
std::string portName = "";
std::vector<std::string> nonDashArgs;
for (int i=1;i<ac;i++) {
const std::string arg = av[i];
if (arg[0] == '-') {
throw std::runtime_error("unknown arg "+arg);
} else
nonDashArgs.push_back(arg);
}
if (nonDashArgs.size() != 2) {
cout << "Usage: ./ospDwTest <hostName> <portNo>" << endl;
exit(1);
}
const std::string hostName = nonDashArgs[0];
const int portNum = atoi(nonDashArgs[1].c_str());
ServiceInfo serviceInfo;
serviceInfo.getFrom(hostName,portNum);
// -------------------------------------------------------
// args parsed, now do the job
// -------------------------------------------------------
MPI::Group me = world.dup();
Client *client = new Client(me,serviceInfo.mpiPortName);
while (1)
renderFrame(me,client);
return 0;
}
} // ::ospray::dw
} // ::ospray
| 32.771654 | 94 | 0.596828 | [
"vector"
] |
51b41967c2b1b8c6ef0bf91aa47c1b9b63b9c129 | 1,704 | cpp | C++ | Model Algorithms/Graphs/Shortest Path from Source to Destination with exactly k edges.cpp | UtkarshPathrabe/Competitive-Coding | ba322fbb1b88682d56a9b80bdd92a853f1caa84e | [
"MIT"
] | 13 | 2021-09-02T07:30:02.000Z | 2022-03-22T19:32:03.000Z | Model Algorithms/Graphs/Shortest Path from Source to Destination with exactly k edges.cpp | UtkarshPathrabe/Competitive-Coding | ba322fbb1b88682d56a9b80bdd92a853f1caa84e | [
"MIT"
] | null | null | null | Model Algorithms/Graphs/Shortest Path from Source to Destination with exactly k edges.cpp | UtkarshPathrabe/Competitive-Coding | ba322fbb1b88682d56a9b80bdd92a853f1caa84e | [
"MIT"
] | 3 | 2021-08-24T16:06:22.000Z | 2021-09-17T15:39:53.000Z | /* Time Complexity: O((V^3)*k); Space Complexity: O(V^2) */
#include <bits/stdc++.h>
using namespace std;
int shortestPath (vector < vector <int> > &graph, int src, int dest, int k) {
int V = graph.size();
int sp[V][V][2];
for (int e = 0; e <= k; e++) {
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
sp[i][j][e%2] = INT_MAX;
if (e == 0 && i == j) {
sp[i][j][e] = 0;
}
if (e == 1 && graph[i][j] != INT_MAX) {
sp[i][j][e] = graph[i][j];
}
if (e > 1) {
for (int l = 0; l < V; l++) {
if ((graph[i][l] != INT_MAX) && (i != l) && (j != l) && (sp[l][j][(e-1)%2] != INT_MAX)) {
sp[i][j][e%2] = min (sp[i][j][e%2], graph[i][l] + sp[l][j][(e-1)%2]);
}
}
}
}
}
}
return sp[src][dest][k%2];
}
int main (void) {
vector < vector <int> > graph;
vector <int> temp;
temp.push_back (0);
temp.push_back (10);
temp.push_back (3);
temp.push_back (2);
graph.push_back (temp);
temp.erase (temp.begin(), temp.end());
temp.push_back (INT_MAX);
temp.push_back (0);
temp.push_back (INT_MAX);
temp.push_back (7);
graph.push_back (temp);
temp.erase (temp.begin(), temp.end());
temp.push_back (INT_MAX);
temp.push_back (INT_MAX);
temp.push_back (0);
temp.push_back (6);
graph.push_back (temp);
temp.erase (temp.begin(), temp.end());
temp.push_back (INT_MAX);
temp.push_back (INT_MAX);
temp.push_back (INT_MAX);
temp.push_back (0);
graph.push_back (temp);
temp.erase (temp.begin(), temp.end());
int src = 0, dest = 3, k = 2;
cout << "The weight of the shortest path from " << src << " to " << dest << " with exactly " << k << " edges is: " << shortestPath (graph, src, dest, k) << "." << endl;
return 0;
}
| 26.625 | 169 | 0.539906 | [
"vector"
] |
51c526d681a0cb3808e3c57b138dfbcc53563229 | 6,379 | cpp | C++ | fbpcs/emp_games/attribution/test/AttributionAppTest.cpp | adshastri/fbpcs | 81d816ee56ea36f8f58dca6ae803fa50138cb91e | [
"MIT"
] | null | null | null | fbpcs/emp_games/attribution/test/AttributionAppTest.cpp | adshastri/fbpcs | 81d816ee56ea36f8f58dca6ae803fa50138cb91e | [
"MIT"
] | null | null | null | fbpcs/emp_games/attribution/test/AttributionAppTest.cpp | adshastri/fbpcs | 81d816ee56ea36f8f58dca6ae803fa50138cb91e | [
"MIT"
] | null | null | null | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <cstdint>
#include <filesystem>
#include <string>
#include <unordered_map>
#include <vector>
#include <gtest/gtest.h>
#include <fbpcf/mpc/EmpGame.h>
#include "folly/Format.h"
#include "folly/Random.h"
#include "folly/logging/xlog.h"
#include <fbpcf/io/FileManagerUtil.h>
#include "../../common/TestUtil.h"
#include "../AttributionApp.h"
#include "../AttributionMetrics.h"
#include "AttributionTestUtils.h"
namespace measurement::private_attribution {
class AttributionAppTest : public ::testing::Test {
protected:
void SetUp() override {
port_ = 5000 + folly::Random::rand32() % 1000;
baseDir_ = private_measurement::test_util::getBaseDirFromPath(__FILE__);
std::string tempDir = std::filesystem::temp_directory_path();
serverIpAlice_ = "";
serverIpBob_ = "127.0.0.1";
outputPathAlice_ = folly::sformat(
"{}/output_path_alice.json_{}", tempDir, folly::Random::secureRand64());
outputPathBob_ = folly::sformat(
"{}/output_path_bob.json_{}", tempDir, folly::Random::secureRand64());
}
void TearDown() override {
std::filesystem::remove(outputPathAlice_);
std::filesystem::remove(outputPathBob_);
}
std::string serverIpAlice_;
std::string serverIpBob_;
uint16_t port_;
std::string baseDir_;
std::string outputPathAlice_;
std::string outputPathBob_;
};
TEST_F(AttributionAppTest, TestMPCAEMCorrectnessWithPrivateScaling) {
// Attribution rules we want to test
std::vector<std::string> attribution_rules{"last_click_1d", "last_touch_1d"};
// Aggregators we want to test
std::vector<std::string> aggregators{"measurement"};
for (auto attribution_rule : attribution_rules) {
for (auto aggregator : aggregators) {
// modifiable input parameters
std::string inputPrefix = "test_correctness";
// inputPrefix should is sufficient in specifying the right input data
// for both Alice (publisher) and bob (partner)
std::string attributionRuleAlice = attribution_rule;
std::string aggregatorAlice = aggregator;
std::string attributionRuleBob = "";
std::string aggregatorBob = "";
std::string OutputJsonFileName = baseDir_ + inputPrefix + "/" +
attributionRuleAlice + "." + aggregatorAlice + ".json";
auto [resAlice, resBob] = runGameAndGenOutputXOR(
serverIpAlice_,
port_,
attributionRuleAlice,
aggregatorAlice,
baseDir_ + inputPrefix + "/" + attributionRuleAlice +
".publisher.csv",
outputPathAlice_,
serverIpBob_,
port_,
attributionRuleBob,
aggregatorBob,
baseDir_ + inputPrefix + "/" + attributionRuleAlice + ".partner.csv",
outputPathBob_);
// for XORed cases, additional step to decode real answer
auto [revealedResAlice, revealedresBob] = revealXORedResult(
resAlice, resBob, aggregatorAlice, attributionRuleAlice);
// verify whether the output is what we expected
verifyOutput(revealedResAlice, revealedresBob, OutputJsonFileName);
}
}
}
TEST_F(AttributionAppTest, Test1DayClickAttributionFormat) {
// modifiable input parameters
std::string inputPrefix = "attribution_format_test";
// inputPrefix should is sufficient in specifying the right input data
// for both Alice (publisher) and bob (partner)
std::string attributionRuleAlice = "last_click_1d";
std::string aggregatorAlice = "attribution";
std::string attributionRuleBob = "";
std::string aggregatorBob = "";
std::string OutputJsonFileName = baseDir_ + inputPrefix + "/" +
attributionRuleAlice + "." + aggregatorAlice + ".json";
auto [resAlice, resBob] = runGameAndGenOutputXOR(
serverIpAlice_,
port_,
attributionRuleAlice,
aggregatorAlice,
baseDir_ + inputPrefix + "/publisher.csv",
outputPathAlice_,
serverIpBob_,
port_,
attributionRuleBob,
aggregatorBob,
baseDir_ + inputPrefix + "/partner.csv",
outputPathBob_);
// for XORed cases, additional step to decode real answer
auto [revealedResAlice, revealedresBob] = revealXORedResult(
resAlice, resBob, aggregatorAlice, attributionRuleAlice);
// verify whether the output is what we expected
verifyOutput(revealedResAlice, revealedresBob, OutputJsonFileName);
}
// Test cases are iterate in https://fb.quip.com/IUHDApxKEAli
// TODO: add comment support for parser, support attribution test. task:
// T90348605
TEST_F(AttributionAppTest, TestMPCAEMCorrectness) {
// Attribution rules we want to test
std::vector<std::string> attribution_rules{"last_click_1d", "last_touch_1d"};
// Aggregators we want to test
std::vector<std::string> aggregators{"measurement", "pcm_ify"};
for (auto attribution_rule : attribution_rules) {
for (auto aggregator : aggregators) {
// modifiable input parameters
std::string inputPrefix = "test_correctness";
// inputPrefix should is sufficient in specifying the right input data
// for both Alice (publisher) and bob (partner)
std::string attributionRuleAlice = attribution_rule;
std::string aggregatorAlice = aggregator;
std::string attributionRuleBob = "";
std::string aggregatorBob = "";
std::string OutputJsonFileName = baseDir_ + inputPrefix + "/" +
attributionRuleAlice + "." + aggregatorAlice + ".json";
auto [resAlice, resBob] = runGameAndGenOutputPUBLIC(
serverIpAlice_,
port_,
attributionRuleAlice,
aggregatorAlice,
baseDir_ + inputPrefix + "/" + attributionRuleAlice +
".publisher.csv",
outputPathAlice_,
serverIpBob_,
port_,
attributionRuleBob,
aggregatorBob,
baseDir_ + inputPrefix + "/" + attributionRuleAlice + ".partner.csv",
outputPathBob_);
// Because in PCM format, bob doesn't have any output
if (aggregator == "pcm_ify") {
resBob = resAlice;
}
// verify whether the output is what we expected
verifyOutput(resAlice, resBob, OutputJsonFileName);
}
}
}
} // namespace measurement::private_attribution
| 34.295699 | 80 | 0.684747 | [
"vector"
] |
51cef6e43ce38d58954c12bce0ede9f06c0dc7a0 | 2,310 | cpp | C++ | test/basic_tests/GameMapTest.cpp | ezalenski/MechMania-2016-AI | ffab99043294a43a67eacbb02d215b72cd704581 | [
"MIT"
] | null | null | null | test/basic_tests/GameMapTest.cpp | ezalenski/MechMania-2016-AI | ffab99043294a43a67eacbb02d215b72cd704581 | [
"MIT"
] | null | null | null | test/basic_tests/GameMapTest.cpp | ezalenski/MechMania-2016-AI | ffab99043294a43a67eacbb02d215b72cd704581 | [
"MIT"
] | null | null | null | //
// Created by Edmund Zalenski on 10/9/16.
//
#include <gtest/gtest.h>
#include "GameMap.h"
class GameMapTest : public ::testing::Test
{
protected:
virtual void TearDown() {
}
virtual void SetUp() {
}
public:
GameMapTest() : Test() {
g = new GameMap();
}
virtual ~GameMapTest() {
delete g;
}
GameMap* g;
std::vector<int> pos1;
std::vector<int> pos2;
};
TEST_F (GameMapTest, GameMapTest_InBounds_Test1) {
GameMap test = *g;
pos1 = {2, 2};
ASSERT_TRUE (test.is_in_bounds(pos1));
}
TEST_F (GameMapTest, GameMapTest_InBounds_Test2) {
GameMap test = *g;
pos1 = {0, 0};
ASSERT_TRUE (test.is_in_bounds(pos1));
}
TEST_F (GameMapTest, GameMapTest_Not_InBounds_Test1) {
GameMap test = *g;
pos1 = {5, 5};
ASSERT_FALSE (test.is_in_bounds(pos1));
}
TEST_F (GameMapTest, GameMapTest_Not_InBounds_Test2) {
GameMap test = *g;
pos1 = {6, 6};
ASSERT_FALSE (test.is_in_bounds(pos1));
}
TEST_F (GameMapTest, GameMapTest_Not_InBounds_Test3) {
GameMap test = *g;
pos1 = {3, 3};
ASSERT_FALSE (test.is_in_bounds(pos1));
}
TEST_F (GameMapTest, GameMapTest_InRange_Test1) {
GameMap test = *g;
pos1 = {3, 3};
pos2 = {3, 3};
ASSERT_TRUE (test.in_vision_of(pos1, pos2, 5));
}
TEST_F (GameMapTest, GameMapTest_InRange_Test2) {
GameMap test = *g;
pos1 = {0, 2};
pos2 = {0, 5};
ASSERT_TRUE (test.in_vision_of(pos1, pos2, 5));
}
TEST_F (GameMapTest, GameMapTest_InRange_Test3) {
GameMap test = *g;
pos1 = {1, 2};
pos2 = {3, 2};
ASSERT_TRUE (test.in_vision_of(pos1, pos2, 5));
}
TEST_F (GameMapTest, GameMapTest_Not_InRange_Test) {
GameMap test = *g;
pos1 = {0, 0};
pos2 = {2, 2};
ASSERT_FALSE (test.in_vision_of(pos1, pos2, 5));
}
TEST_F (GameMapTest, GameMapTest_Not_InRange_Test2) {
GameMap test = *g;
pos1 = {1, 2};
pos2 = {1, 5};
ASSERT_FALSE (test.in_vision_of(pos1, pos2, 1));
}
TEST_F (GameMapTest, GameMapTest_Not_InRange_Test3) {
GameMap test = *g;
pos1 = {1, 0};
pos2 = {1, 2};
ASSERT_FALSE (test.in_vision_of(pos1, pos2, 5));
}
TEST_F (GameMapTest, GameMapTest_Not_InRange_Test4) {
GameMap test = *g;
pos1 = {0, 1};
pos2 = {2, 1};
ASSERT_FALSE (test.in_vision_of(pos1, pos2, 5));
} | 21.588785 | 54 | 0.625541 | [
"vector"
] |
51d36d355efa76a35923ff40c273698e2ca33b13 | 310 | cpp | C++ | company questions/binary.cpp | yusufkhan004/DSA-practice-problems | 04e0ea2b311a63a38fbf9d28e974b266da1a60a1 | [
"MIT"
] | null | null | null | company questions/binary.cpp | yusufkhan004/DSA-practice-problems | 04e0ea2b311a63a38fbf9d28e974b266da1a60a1 | [
"MIT"
] | null | null | null | company questions/binary.cpp | yusufkhan004/DSA-practice-problems | 04e0ea2b311a63a38fbf9d28e974b266da1a60a1 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin >> n;
vector<int> bin;
while (n != 0){
int rem = n % 2;
bin.push_back(rem);
n = n / 2;
}
reverse(bin.begin(), bin.end());
for (int i : bin){
cout << i << "";
}
return 0;
} | 16.315789 | 36 | 0.43871 | [
"vector"
] |
51e0371f04bae4bdd737c642640b641d4e412647 | 1,568 | cc | C++ | extern/acgl/src/ACGL/OpenGL/Data/GeometryDataLoadStore.cc | Faerbit/Saxum | 3b255142337e08988f2b4f1f56d6e061e8754336 | [
"CC-BY-3.0",
"CC-BY-4.0"
] | 2 | 2015-03-12T16:19:10.000Z | 2015-11-24T20:23:26.000Z | extern/acgl/src/ACGL/OpenGL/Data/GeometryDataLoadStore.cc | Faerbit/Saxum | 3b255142337e08988f2b4f1f56d6e061e8754336 | [
"CC-BY-3.0",
"CC-BY-4.0"
] | 15 | 2015-03-14T14:13:12.000Z | 2015-06-02T18:39:55.000Z | extern/acgl/src/ACGL/OpenGL/Data/GeometryDataLoadStore.cc | Faerbit/Saxum | 3b255142337e08988f2b4f1f56d6e061e8754336 | [
"CC-BY-3.0",
"CC-BY-4.0"
] | null | null | null | /***********************************************************************
* Copyright 2011-2012 Computer Graphics Group RWTH Aachen University. *
* All rights reserved. *
* Distributed under the terms of the MIT License (see LICENSE.TXT). *
**********************************************************************/
#include <ACGL/OpenGL/Data/GeometryDataLoadStore.hh>
#include <ACGL/Utils/FileHelpers.hh>
#include <ACGL/Utils/StringHelpers.hh>
using namespace ACGL;
using namespace ACGL::OpenGL;
using namespace ACGL::Utils;
using namespace ACGL::Utils::StringHelpers;
namespace ACGL{
namespace OpenGL{
///////////////////////////////////////////////////////////////////////////////////////////////////
// generic load/save
///////////////////////////////////////////////////////////////////////////////////////////////////
SharedGeometryData loadGeometryData(const std::string& _filename)
{
// lower case file ending:
std::string fileEnding = getFileEnding(_filename);
if(fileEnding == "obj")
{
return loadGeometryDataFromOBJ(_filename);
}
else if(fileEnding == "atb")
{
return loadGeometryDataFromATB(_filename);
}
else if(fileEnding == "vap")
{
return loadGeometryDataFromVAP(_filename);
}
else
{
error() << "geometry file format of " << _filename << " not supported" << std::endl;
}
return SharedGeometryData();
}
} // OpenGL
} // ACGL
| 31.36 | 99 | 0.478316 | [
"geometry"
] |
51e111f9f83aa55d88b99c57c08d9d2958751fa0 | 1,246 | cpp | C++ | ch09/274.cpp | mallius/CppPrimer | 0285fabe5934492dfed0a9cf67ba5650982a5f76 | [
"MIT"
] | null | null | null | ch09/274.cpp | mallius/CppPrimer | 0285fabe5934492dfed0a9cf67ba5650982a5f76 | [
"MIT"
] | null | null | null | ch09/274.cpp | mallius/CppPrimer | 0285fabe5934492dfed0a9cf67ba5650982a5f76 | [
"MIT"
] | 1 | 2022-01-25T15:51:34.000Z | 2022-01-25T15:51:34.000Z | #include <iostream>
#include <string>
#include <vector>
#include <list>
#include <deque>
using std::string;
using std::vector;
using std::list;
using std::deque;
using std::cout;
using std::endl;
using std::cin;
int main(void)
{
list<int> ilist;
for(size_t ix = 0; ix != 4; ++ix)
ilist.push_back(ix);
for(list<int>::iterator it = ilist.begin(); it != ilist.end(); ++it)
{
cout << *it << endl;
}
cout << "---push_front---" << endl;
list<int> ilist2;
for(size_t ix = 0; ix != 4; ++ix)
ilist2.push_front(ix);
for(list<int>::iterator it = ilist2.begin(); it != ilist2.end(); ++it)
{
cout << *it << endl;
}
cout << "--insert---" << endl;
string spouse("Beth");
vector<string> svec;
list<string> slist;
slist.insert(slist.begin(), spouse);
svec.insert(svec.begin(), spouse);
svec.insert(svec.end(), 3, "Ann");
string sarray[4] = {"quasi", "simba", "frollo", "scar"};
svec.insert(svec.end(), sarray, sarray+4);
slist.insert(slist.end(), sarray+2, sarray+4);
for(vector<string>::iterator it = svec.begin(); it != svec.end(); ++it)
{
cout << *it << endl;
}
cout << "---slist---" << endl;
for(list<string>::iterator it = slist.begin(); it != slist.end(); ++it)
{
cout << *it << endl;
}
return 0;
}
| 20.096774 | 72 | 0.5939 | [
"vector"
] |
51e7359f51407022ab82257f7cbd9951ea9198f7 | 12,299 | hpp | C++ | include/System/Single.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | include/System/Single.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | include/System/Single.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
// Including type: System.ValueType
#include "System/ValueType.hpp"
// Including type: System.IComparable
#include "System/IComparable.hpp"
// Including type: System.IFormattable
#include "System/IFormattable.hpp"
// Including type: System.IConvertible
#include "System/IConvertible.hpp"
// Including type: System.IComparable`1
#include "System/IComparable_1.hpp"
// Including type: System.IEquatable`1
#include "System/IEquatable_1.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: System
namespace System {
// Forward declaring type: IFormatProvider
class IFormatProvider;
// Forward declaring type: TypeCode
struct TypeCode;
// Forward declaring type: Decimal
struct Decimal;
// Forward declaring type: DateTime
struct DateTime;
// Forward declaring type: Type
class Type;
}
// Forward declaring namespace: System::Globalization
namespace System::Globalization {
// Forward declaring type: NumberStyles
struct NumberStyles;
// Forward declaring type: NumberFormatInfo
class NumberFormatInfo;
}
// Completed forward declares
// Type namespace: System
namespace System {
// Size: 0x4
#pragma pack(push, 1)
// WARNING Layout: Sequential may not be correctly taken into account!
// Autogenerated type: System.Single
// [ComVisibleAttribute] Offset: D7AD1C
struct Single/*, public System::ValueType, public System::IComparable, public System::IFormattable, public System::IConvertible, public System::IComparable_1<float>, public System::IEquatable_1<float>*/ {
public:
// System.Single m_value
// Size: 0x4
// Offset: 0x0
float m_value;
// Field size check
static_assert(sizeof(float) == 0x4);
// Creating value type constructor for type: Single
constexpr Single(float m_value_ = {}) noexcept : m_value{m_value_} {}
// Creating interface conversion operator: operator System::ValueType
operator System::ValueType() noexcept {
return *reinterpret_cast<System::ValueType*>(this);
}
// Creating interface conversion operator: operator System::IComparable
operator System::IComparable() noexcept {
return *reinterpret_cast<System::IComparable*>(this);
}
// Creating interface conversion operator: operator System::IFormattable
operator System::IFormattable() noexcept {
return *reinterpret_cast<System::IFormattable*>(this);
}
// Creating interface conversion operator: operator System::IConvertible
operator System::IConvertible() noexcept {
return *reinterpret_cast<System::IConvertible*>(this);
}
// Creating interface conversion operator: operator System::IComparable_1<float>
operator System::IComparable_1<float>() noexcept {
return *reinterpret_cast<System::IComparable_1<float>*>(this);
}
// Creating interface conversion operator: operator System::IEquatable_1<float>
operator System::IEquatable_1<float>() noexcept {
return *reinterpret_cast<System::IEquatable_1<float>*>(this);
}
// Creating conversion operator: operator float
constexpr operator float() const noexcept {
return m_value;
}
// static field const value: static public System.Single MinValue
static constexpr const float MinValue = -3.4028235e+38;
// Get static field: static public System.Single MinValue
static float _get_MinValue();
// Set static field: static public System.Single MinValue
static void _set_MinValue(float value);
// static field const value: static public System.Single Epsilon
static constexpr const float Epsilon = 1e-45;
// Get static field: static public System.Single Epsilon
static float _get_Epsilon();
// Set static field: static public System.Single Epsilon
static void _set_Epsilon(float value);
// static field const value: static public System.Single MaxValue
static constexpr const float MaxValue = 3.4028235e+38;
// Get static field: static public System.Single MaxValue
static float _get_MaxValue();
// Set static field: static public System.Single MaxValue
static void _set_MaxValue(float value);
// Get static field: static public System.Single PositiveInfinity
static float _get_PositiveInfinity();
// Set static field: static public System.Single PositiveInfinity
static void _set_PositiveInfinity(float value);
// Get static field: static public System.Single NegativeInfinity
static float _get_NegativeInfinity();
// Set static field: static public System.Single NegativeInfinity
static void _set_NegativeInfinity(float value);
// Get static field: static public System.Single NaN
static float _get_NaN();
// Set static field: static public System.Single NaN
static void _set_NaN(float value);
// static public System.Boolean IsInfinity(System.Single f)
// Offset: 0x1B34D60
static bool IsInfinity(float f);
// static public System.Boolean IsPositiveInfinity(System.Single f)
// Offset: 0x1B34D78
static bool IsPositiveInfinity(float f);
// static public System.Boolean IsNegativeInfinity(System.Single f)
// Offset: 0x1B34D8C
static bool IsNegativeInfinity(float f);
// static public System.Boolean IsNaN(System.Single f)
// Offset: 0x1B34D9C
static bool IsNaN(float f);
// public System.Int32 CompareTo(System.Object value)
// Offset: 0xF06010
int CompareTo(::Il2CppObject* value);
// public System.Int32 CompareTo(System.Single value)
// Offset: 0xF06018
int CompareTo(float value);
// public System.Boolean Equals(System.Single obj)
// Offset: 0xF0607C
bool Equals(float obj);
// public System.String ToString(System.IFormatProvider provider)
// Offset: 0xF06110
::Il2CppString* ToString(System::IFormatProvider* provider);
// public System.String ToString(System.String format)
// Offset: 0xF06148
::Il2CppString* ToString(::Il2CppString* format);
// public System.String ToString(System.String format, System.IFormatProvider provider)
// Offset: 0xF06188
::Il2CppString* ToString(::Il2CppString* format, System::IFormatProvider* provider);
// static public System.Single Parse(System.String s)
// Offset: 0x1B35138
static float Parse(::Il2CppString* s);
// static public System.Single Parse(System.String s, System.IFormatProvider provider)
// Offset: 0x1B35174
static float Parse(::Il2CppString* s, System::IFormatProvider* provider);
// static public System.Single Parse(System.String s, System.Globalization.NumberStyles style, System.IFormatProvider provider)
// Offset: 0x1B351AC
static float Parse(::Il2CppString* s, System::Globalization::NumberStyles style, System::IFormatProvider* provider);
// static private System.Single Parse(System.String s, System.Globalization.NumberStyles style, System.Globalization.NumberFormatInfo info)
// Offset: 0x1B3516C
static float Parse(::Il2CppString* s, System::Globalization::NumberStyles style, System::Globalization::NumberFormatInfo* info);
// static public System.Boolean TryParse(System.String s, out System.Single result)
// Offset: 0x1B35200
static bool TryParse(::Il2CppString* s, float& result);
// static public System.Boolean TryParse(System.String s, System.Globalization.NumberStyles style, System.IFormatProvider provider, out System.Single result)
// Offset: 0x1B352F0
static bool TryParse(::Il2CppString* s, System::Globalization::NumberStyles style, System::IFormatProvider* provider, float& result);
// static private System.Boolean TryParse(System.String s, System.Globalization.NumberStyles style, System.Globalization.NumberFormatInfo info, out System.Single result)
// Offset: 0x1B35238
static bool TryParse(::Il2CppString* s, System::Globalization::NumberStyles style, System::Globalization::NumberFormatInfo* info, float& result);
// public System.TypeCode GetTypeCode()
// Offset: 0xF061CC
System::TypeCode GetTypeCode();
// private System.Boolean System.IConvertible.ToBoolean(System.IFormatProvider provider)
// Offset: 0xF061D4
bool System_IConvertible_ToBoolean(System::IFormatProvider* provider);
// private System.Char System.IConvertible.ToChar(System.IFormatProvider provider)
// Offset: 0xF061DC
::Il2CppChar System_IConvertible_ToChar(System::IFormatProvider* provider);
// private System.SByte System.IConvertible.ToSByte(System.IFormatProvider provider)
// Offset: 0xF061E8
int8_t System_IConvertible_ToSByte(System::IFormatProvider* provider);
// private System.Byte System.IConvertible.ToByte(System.IFormatProvider provider)
// Offset: 0xF061F0
uint8_t System_IConvertible_ToByte(System::IFormatProvider* provider);
// private System.Int16 System.IConvertible.ToInt16(System.IFormatProvider provider)
// Offset: 0xF061F8
int16_t System_IConvertible_ToInt16(System::IFormatProvider* provider);
// private System.UInt16 System.IConvertible.ToUInt16(System.IFormatProvider provider)
// Offset: 0xF06200
uint16_t System_IConvertible_ToUInt16(System::IFormatProvider* provider);
// private System.Int32 System.IConvertible.ToInt32(System.IFormatProvider provider)
// Offset: 0xF06208
int System_IConvertible_ToInt32(System::IFormatProvider* provider);
// private System.UInt32 System.IConvertible.ToUInt32(System.IFormatProvider provider)
// Offset: 0xF06210
uint System_IConvertible_ToUInt32(System::IFormatProvider* provider);
// private System.Int64 System.IConvertible.ToInt64(System.IFormatProvider provider)
// Offset: 0xF06218
int64_t System_IConvertible_ToInt64(System::IFormatProvider* provider);
// private System.UInt64 System.IConvertible.ToUInt64(System.IFormatProvider provider)
// Offset: 0xF06220
uint64_t System_IConvertible_ToUInt64(System::IFormatProvider* provider);
// private System.Single System.IConvertible.ToSingle(System.IFormatProvider provider)
// Offset: 0xF06228
float System_IConvertible_ToSingle(System::IFormatProvider* provider);
// private System.Double System.IConvertible.ToDouble(System.IFormatProvider provider)
// Offset: 0xF06230
double System_IConvertible_ToDouble(System::IFormatProvider* provider);
// private System.Decimal System.IConvertible.ToDecimal(System.IFormatProvider provider)
// Offset: 0xF06238
System::Decimal System_IConvertible_ToDecimal(System::IFormatProvider* provider);
// private System.DateTime System.IConvertible.ToDateTime(System.IFormatProvider provider)
// Offset: 0xF06240
System::DateTime System_IConvertible_ToDateTime(System::IFormatProvider* provider);
// private System.Object System.IConvertible.ToType(System.Type type, System.IFormatProvider provider)
// Offset: 0xF0624C
::Il2CppObject* System_IConvertible_ToType(System::Type* type, System::IFormatProvider* provider);
// public override System.Boolean Equals(System.Object obj)
// Offset: 0xF06074
// Implemented from: System.ValueType
// Base method: System.Boolean ValueType::Equals(System.Object obj)
bool Equals(::Il2CppObject* obj);
// public override System.Int32 GetHashCode()
// Offset: 0xF060C8
// Implemented from: System.ValueType
// Base method: System.Int32 ValueType::GetHashCode()
int GetHashCode();
// public override System.String ToString()
// Offset: 0xF060DC
// Implemented from: System.ValueType
// Base method: System.String ValueType::ToString()
::Il2CppString* ToString();
}; // System.Single
#pragma pack(pop)
static check_size<sizeof(Single), 0 + sizeof(float)> __System_SingleSizeCheck;
static_assert(sizeof(Single) == 0x4);
}
#include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
DEFINE_IL2CPP_ARG_TYPE(System::Single, "System", "Single");
| 51.676471 | 207 | 0.730872 | [
"object"
] |
51e838ff2900cf28e90978acdf0ac129e0f802d0 | 2,330 | cpp | C++ | src/LightBulb/Learning/Evolution/TeachingEvolutionEnvironment.cpp | domin1101/ANNHelper | 50acb5746d6dad6777532e4c7da4983a7683efe0 | [
"Zlib"
] | 5 | 2016-02-04T06:14:42.000Z | 2017-02-06T02:21:43.000Z | src/LightBulb/Learning/Evolution/TeachingEvolutionEnvironment.cpp | domin1101/ANNHelper | 50acb5746d6dad6777532e4c7da4983a7683efe0 | [
"Zlib"
] | 41 | 2015-04-15T21:05:45.000Z | 2015-07-09T12:59:02.000Z | src/LightBulb/Learning/Evolution/TeachingEvolutionEnvironment.cpp | domin1101/LightBulb | 50acb5746d6dad6777532e4c7da4983a7683efe0 | [
"Zlib"
] | null | null | null | // Includes
#include "LightBulb/Learning/Evolution/TeachingEvolutionEnvironment.hpp"
#include "LightBulb/Learning/Evolution/TeachedIndividual.hpp"
#include "LightBulb/Learning/LearningState.hpp"
#include "LightBulb/NetworkTopology/FeedForwardNetworkTopology.hpp"
//Library includes
namespace LightBulb
{
TeachingEvolutionEnvironment::TeachingEvolutionEnvironment() = default;
TeachingEvolutionEnvironment::~TeachingEvolutionEnvironment() = default;
AbstractIndividual* TeachingEvolutionEnvironment::createNewIndividual()
{
return new TeachedIndividual(*this, *networkOptions);
}
TeachingEvolutionEnvironment::TeachingEvolutionEnvironment(AbstractTeacher* teacher_, FeedForwardNetworkTopologyOptions& networkOptions_)
{
teacher = teacher_;
networkOptions.reset(new FeedForwardNetworkTopologyOptions(networkOptions_));
}
void TeachingEvolutionEnvironment::doSimulationStep()
{
// Just recalculate the current total error values of all individuals
for (auto teachedIndividual = individuals.begin(); teachedIndividual != individuals.end(); teachedIndividual++)
{
(*teachedIndividual)->doNNCalculation();
}
const Highscore& highscore = getHighscoreList();
if (learningState && !learningState->disabledDatasets[DATASET_TEACHING_ERROR])
learningState->addData(DATASET_TEACHING_ERROR, static_cast<TeachedIndividual*>(highscore.front().second)->getCurrentTeachingError());
if (learningState && !learningState->disabledDatasets[DATASET_WEIGHTDECAY_ERROR])
learningState->addData(DATASET_WEIGHTDECAY_ERROR, static_cast<TeachedIndividual*>(highscore.front().second)->getCurrentWeightDecayError());
}
std::vector<std::string> TeachingEvolutionEnvironment::getDataSetLabels() const
{
auto labels = AbstractEvolutionEnvironment::getDataSetLabels();
labels.push_back(DATASET_TEACHING_ERROR);
labels.push_back(DATASET_WEIGHTDECAY_ERROR);
return labels;
}
void TeachingEvolutionEnvironment::getFitness(const AbstractIndividual& individual, LightBulb::Scalar<>& fitness) const
{
// Just return the total error of the individual (negate it, so the error 0 is the maximum)
fitness.getEigenValueForEditing() = -static_cast<const TeachedIndividual&>(individual).getCurrentTotalError();
}
AbstractTeacher& TeachingEvolutionEnvironment::getTeacher() const
{
return *teacher;
}
}
| 36.984127 | 142 | 0.807296 | [
"vector"
] |
51f3e9e6de4ef5363c939d9b07ebeac99176ceea | 15,124 | cpp | C++ | src/top_quantifier_desc.cpp | b1f6c1c4/cfg-enum | 1a08071bde87f578ceaf834004c01b593db9bce8 | [
"BSD-3-Clause"
] | 4 | 2021-06-11T07:34:50.000Z | 2022-03-30T15:32:07.000Z | src/top_quantifier_desc.cpp | b1f6c1c4/cfg-enum | 1a08071bde87f578ceaf834004c01b593db9bce8 | [
"BSD-3-Clause"
] | null | null | null | src/top_quantifier_desc.cpp | b1f6c1c4/cfg-enum | 1a08071bde87f578ceaf834004c01b593db9bce8 | [
"BSD-3-Clause"
] | 2 | 2021-11-16T09:13:46.000Z | 2021-12-20T14:53:57.000Z | #include "top_quantifier_desc.h"
#include <set>
#include <cassert>
#include <iostream>
using namespace std;
TopQuantifierDesc::TopQuantifierDesc(value v) {
while (true) {
if (Forall* f = dynamic_cast<Forall*>(v.get())) {
for (VarDecl decl : f->decls) {
d.push_back(make_pair(QType::Forall, vector<VarDecl>{decl}));
}
v = f->body;
} else if (NearlyForall* f = dynamic_cast<NearlyForall*>(v.get())) {
d.push_back(make_pair(QType::NearlyForall, f->decls));
v = f->body;
} else {
break;
}
}
}
pair<TopQuantifierDesc, value> get_tqd_and_body(value v)
{
TopQuantifierDesc tqd(v);
while (true) {
if (Forall* f = dynamic_cast<Forall*>(v.get())) {
v = f->body;
} else if (NearlyForall* f = dynamic_cast<NearlyForall*>(v.get())) {
v = f->body;
} else {
break;
}
}
return make_pair(tqd, v);
}
pair<TopAlternatingQuantifierDesc, value> get_taqd_and_body(value v)
{
TopAlternatingQuantifierDesc taqd(v);
while (true) {
if (Forall* f = dynamic_cast<Forall*>(v.get())) {
v = f->body;
} else if (Exists* e = dynamic_cast<Exists*>(v.get())) {
v = e->body;
} else {
break;
}
}
return make_pair(taqd, v);
}
vector<VarDecl> TopQuantifierDesc::decls() const {
vector<VarDecl> res;
for (auto p : d) {
for (auto decl : p.second) {
res.push_back(decl);
}
}
return res;
}
vector<QRange> TopQuantifierDesc::with_foralls_grouped() const {
vector<QRange> res;
QRange cur;
cur.start = 0;
cur.end = 0;
for (auto p : d) {
QType ty = p.first;
if (ty == QType::Forall) {
cur.end++;
cur.decls.push_back(p.second[0]);
cur.qtype = ty;
} else if (ty == QType::NearlyForall) {
if (cur.end > cur.start) {
res.push_back(cur);
}
cur.start = cur.end;
cur.decls = p.second;
cur.end = cur.start + cur.decls.size();
cur.qtype = ty;
res.push_back(cur);
cur.start = cur.end;
cur.decls.clear();
} else {
assert(false);
}
}
if (cur.end > cur.start) {
res.push_back(cur);
}
return res;
}
vector<QSRange> TopQuantifierDesc::grouped_by_sort() const {
vector<QSRange> res;
QSRange cur;
cur.start = 0;
cur.end = 0;
for (auto p : d) {
QType ty = p.first;
for (auto decl : p.second) {
if (cur.end > cur.start && !(cur.qtype == ty && sorts_eq(cur.decls[0].sort, decl.sort))) {
res.push_back(cur);
cur.start = cur.end;
cur.decls.clear();
}
cur.decls.push_back(decl);
cur.qtype = ty;
cur.sort = decl.sort;
cur.end++;
}
if (ty == QType::NearlyForall && cur.end > cur.start) {
res.push_back(cur);
cur.start = cur.end;
cur.decls.clear();
}
}
if (cur.end > cur.start) {
res.push_back(cur);
}
set<string> names;
for (int i = 0; i < (int)res.size(); i++) {
if (i > 0 && res[i].qtype != res[i-1].qtype) {
names.clear();
}
UninterpretedSort* usort = dynamic_cast<UninterpretedSort*>(res[i].decls[0].sort.get());
assert(usort != NULL);
if (res[i].qtype == QType::Forall) {
assert (names.count(usort->name) == 0);
}
names.insert(usort->name);
}
return res;
}
value TopQuantifierDesc::with_body(value body) const {
vector<QRange> qrs = with_foralls_grouped();
for (int i = qrs.size() - 1; i >= 0; i--) {
QRange& qr = qrs[i];
if (qr.qtype == QType::Forall) {
body = v_forall(qr.decls, body);
}
else if (qr.qtype == QType::NearlyForall) {
body = v_nearlyforall(qr.decls, body);
}
else {
assert(false);
}
}
return body;
}
int TopQuantifierDesc::weighted_sort_count(std::string sort) const {
lsort so = s_uninterp(sort);
int count = 0;
for (auto p : d) {
QType ty = p.first;
for (VarDecl const& decl : p.second) {
if (sorts_eq(so, decl.sort)) {
count += (ty == QType::NearlyForall ? 2 : 1);
}
}
}
return count;
}
TopAlternatingQuantifierDesc::TopAlternatingQuantifierDesc(value v)
{
Alternation alt;
while (true) {
if (Forall* f = dynamic_cast<Forall*>(v.get())) {
if (alt.decls.size() > 0 && alt.altType != AltType::Forall) {
alts.push_back(alt);
alt.decls = {};
}
alt.altType = AltType::Forall;
for (VarDecl decl : f->decls) {
alt.decls.push_back(decl);
}
v = f->body;
} else if (/* NearlyForall* f = */ dynamic_cast<NearlyForall*>(v.get())) {
assert(false);
} else if (Exists* f = dynamic_cast<Exists*>(v.get())) {
if (alt.decls.size() > 0 && alt.altType != AltType::Exists) {
alts.push_back(alt);
alt.decls = {};
}
alt.altType = AltType::Exists;
for (VarDecl decl : f->decls) {
alt.decls.push_back(decl);
}
v = f->body;
} else {
break;
}
}
if (alt.decls.size() > 0) {
alts.push_back(alt);
}
}
value TopAlternatingQuantifierDesc::get_body(value v)
{
while (true) {
if (Forall* f = dynamic_cast<Forall*>(v.get())) {
v = f->body;
}
else if (Exists* f = dynamic_cast<Exists*>(v.get())) {
v = f->body;
}
else {
break;
}
}
return v;
}
value TopAlternatingQuantifierDesc::with_body(value v)
{
for (int i = alts.size() - 1; i >= 0; i--) {
Alternation& alt = alts[i];
if (alt.altType == AltType::Forall) {
v = v_forall(alt.decls, v);
} else {
v = v_exists(alt.decls, v);
}
}
return v;
}
vector<QSRange> TopAlternatingQuantifierDesc::grouped_by_sort() const {
vector<QSRange> res;
QSRange cur;
cur.start = 0;
cur.end = 0;
for (auto alt : alts) {
assert(alt.altType == AltType::Forall || alt.altType == AltType::Exists);
QType ty = alt.altType == AltType::Forall ? QType::Forall : QType::Exists;
for (auto decl : alt.decls) {
if (cur.end > cur.start && !(cur.qtype == ty && sorts_eq(cur.decls[0].sort, decl.sort))) {
res.push_back(cur);
cur.start = cur.end;
cur.decls.clear();
}
cur.decls.push_back(decl);
cur.qtype = ty;
cur.sort = decl.sort;
cur.end++;
}
/*if (ty == QType::NearlyForall && cur.end > cur.start) {
res.push_back(cur);
cur.start = cur.end;
cur.decls.clear();
}*/
}
if (cur.end > cur.start) {
res.push_back(cur);
}
set<string> names;
for (int i = 0; i < (int)res.size(); i++) {
if (i > 0 && res[i].qtype != res[i-1].qtype) {
names.clear();
}
UninterpretedSort* usort = dynamic_cast<UninterpretedSort*>(res[i].decls[0].sort.get());
assert(usort != NULL);
if (res[i].qtype == QType::Forall) {
assert (names.count(usort->name) == 0);
}
names.insert(usort->name);
}
return res;
}
TopAlternatingQuantifierDesc TopAlternatingQuantifierDesc::
replace_exists_with_forall() const {
Alternation bigalt;
bigalt.altType = AltType::Forall;
for (Alternation const& alt : alts) {
for (VarDecl decl : alt.decls) {
bigalt.decls.push_back(decl);
}
}
TopAlternatingQuantifierDesc res;
res.alts.push_back(bigalt);
return res;
}
/*value rename_into(vector<Alternation> const& alts, value v)
{
int alt_idx = 0;
int inner_idx = 0;
TopAlternatingQuantifierDesc atqd(v);
vector<Alternation>& alts1 = atqd.alts;
int alt_idx1 = 0;
int inner_idx1 = 0;
map<iden, iden> var_map;
while (alt_idx1 < (int)alts1.size()) {
while (inner_idx1 < (int)alts1[alt_idx1].decls.size()) {
if (alt_idx == (int)alts.size()) {
return nullptr;
}
if (inner_idx == (int)alts[alt_idx].decls.size()) {
inner_idx = 0;
alt_idx++;
} else {
if (alts[alt_idx].altType == alts1[alt_idx1].altType
&& sorts_eq(
alts[alt_idx].decls[inner_idx].sort,
alts1[alt_idx1].decls[inner_idx1].sort))
{
var_map.insert(make_pair(
alts1[alt_idx1].decls[inner_idx1].name,
alts[alt_idx].decls[inner_idx].name));
inner_idx1++;
}
inner_idx++;
}
}
inner_idx1 = 0;
alt_idx1++;
}
value substed = v->replace_var_with_var(TopAlternatingQuantifierDesc::get_body(var_map));
TopAlternatingQuantifierDesc new_taqd;
new_taqd.alts = alts;
return new_taqd.with_body(substed);
}
value TopQuantifierDesc::rename_into(value v)
{
cout << "Top rename_into " << v->to_string() << endl;
v = remove_unneeded_quants(v.get());
cout << "removed unneeded " << v->to_string() << endl;
vector<Alternation> alts;
alts.resize(d.size());
for (int i = 0; i < (int)d.size(); i++) {
assert (d[i].first == QType::Forall);
alts[i].decls = d[i].second;
alts[i].altType = AltType::Forall;
}
value res = ::rename_into(alts, v);
if (res) {
cout << "result " << res->to_string() << endl;
} else {
cout << "result null" << endl;
}
return res;
}
value TopAlternatingQuantifierDesc::rename_into(value v)
{
cout << "Alt rename_into " << v->to_string() << endl;
v = remove_unneeded_quants(v.get());
cout << "removed unneeded " << v->to_string() << endl;
value res = ::rename_into(alts, v);
if (res) {
cout << "result " << res->to_string() << endl;
} else {
cout << "result null" << endl;
}
return res;
}*/
/*void TopAlternatingQuantifierDesc::rename_into_all_possibilities_rec(
TopAlternatingQuantifierDesc const& v_taqd,
int v_idx,
int v_inner_idx,
int this_idx,
int this_inner_idx,
value const& body,
map<iden, iden>& var_map,
vector<value>& results)
{
if (v_idx == (int)v_taqd.alts.size()) {
results.push_back(this->with_body(body->replace_var_with_var(var_map)));
return;
}
if (v_inner_idx == (int)v_taqd.alts[v_idx].decls.size()) {
rename_into_all_possibilities_rec(
v_taqd,
v_idx + 1, 0,
this_idx, this_inner_idx,
body, var_map, results);
return;
}
if (this_idx == (int)this->alts.size()) {
return;
}
if (this_inner_idx == (int)this->alts[this_idx].decls.size()) {
rename_into_all_possibilities_rec(
v_taqd,
v_idx, v_inner_idx,
this_idx + 1, 0,
body, var_map, results);
return;
}
if (v_taqd.alts[v_idx].altType != this->alts[this_idx].altType) {
rename_into_all_possibilities_rec(
v_taqd,
v_idx, v_inner_idx,
this_idx + 1, 0,
body, var_map, results);
return;
}
rename_into_all_possibilities_rec(
v_taqd,
v_idx, v_inner_idx,
this_idx, this_inner_idx + 1,
body, var_map, results);
if (sorts_eq(
v_taqd.alts[v_idx].decls[v_inner_idx].sort,
this->alts[this_idx].decls[this_inner_idx].sort))
{
var_map[v_taqd.alts[v_idx].decls[v_inner_idx].name] =
this->alts[this_idx].decls[this_inner_idx].name;
rename_into_all_possibilities_rec(v_taqd, v_idx, v_inner_idx + 1, this_idx, this_inner_idx + 1, body, var_map, results);
}
}*/
static bool is_valid(vector<vector<pair<int,int>>>& candidate) {
for (int i = 0; i < (int)candidate.size(); i++) {
for (int j = 0; j < (int)candidate[i].size(); j++) {
for (int k = i; k < (int)candidate.size(); k++) {
for (int l = 0; l < (int)candidate[k].size(); l++) {
if (!(i == k && j == l) && candidate[i][j] == candidate[k][l]) {
return false;
}
}
}
}
}
int last_min_x;
int last_max_x;
for (int i = 0; i < (int)candidate.size(); i++) {
int min_x = candidate[i][0].first;
int max_x = candidate[i][0].first;
for (int j = 1; j < (int)candidate[i].size(); j++) {
min_x = min(min_x, candidate[i][j].first);
max_x = max(max_x, candidate[i][j].first);
}
if (i > 0) {
if (min_x < last_max_x) {
return false;
}
}
last_min_x = min_x;
last_max_x = max_x;
}
return true;
}
std::vector<value> TopAlternatingQuantifierDesc::rename_into_all_possibilities(value v) {
cout << "rename_into_all_possibilities " << v->to_string() << endl;
for (Alternation const& alt : alts) {
cout << "type: " << (alt.altType == AltType::Forall ? "forall" : "exists");
cout << " ";
}
cout << endl;
v = remove_unneeded_quants(v.get());
TopAlternatingQuantifierDesc taqd(v);
value body = TopAlternatingQuantifierDesc::get_body(v);
vector<vector<vector<pair<int,int>>>> possibilities;
vector<vector<int>> indices;
vector<vector<pair<int,int>>> candidate;
possibilities.resize(taqd.alts.size());
indices.resize(taqd.alts.size());
candidate.resize(taqd.alts.size());
for (int i = 0; i < (int)taqd.alts.size(); i++) {
possibilities[i].resize(taqd.alts[i].decls.size());
indices[i].resize(taqd.alts[i].decls.size());
candidate[i].resize(taqd.alts[i].decls.size());
for (int j = 0; j < (int)taqd.alts[i].decls.size(); j++) {
indices[i][j] = 0;
VarDecl const& decl = taqd.alts[i].decls[j];
for (int k = 0; k < (int)this->alts.size(); k++) {
if (this->alts[k].altType == taqd.alts[i].altType ||
(taqd.alts[i].altType == AltType::Forall
&& this->alts[k].altType == AltType::Exists)
) {
for (int l = 0; l < (int)this->alts[k].decls.size(); l++) {
if (sorts_eq(decl.sort, this->alts[k].decls[l].sort)) {
possibilities[i][j].push_back(make_pair(k, l));
}
}
}
}
if (possibilities[i][j].size() == 0) {
return {};
}
}
}
vector<value> results;
while (true) {
for (int i = 0; i < (int)taqd.alts.size(); i++) {
for (int j = 0; j < (int)taqd.alts[i].decls.size(); j++) {
candidate[i][j] = possibilities[i][j][indices[i][j]];
}
}
if (is_valid(candidate)) {
map<iden, iden> var_map;
for (int i = 0; i < (int)taqd.alts.size(); i++) {
for (int j = 0; j < (int)taqd.alts[i].decls.size(); j++) {
var_map.insert(make_pair(taqd.alts[i].decls[j].name,
this->alts[candidate[i][j].first].decls[candidate[i][j].second].name));
}
}
results.push_back(order_and_or_eq(this->with_body(body->replace_var_with_var(var_map))));
}
for (int i = 0; i < (int)taqd.alts.size(); i++) {
for (int j = 0; j < (int)taqd.alts[i].decls.size(); j++) {
indices[i][j]++;
if (indices[i][j] == (int)possibilities[i][j].size()) {
indices[i][j] = 0;
} else {
goto continue_loop;
}
}
}
break;
continue_loop: { }
}
for (value res : results) {
cout << "result: " << res->to_string() << endl;
}
return results;
}
std::vector<value> TopQuantifierDesc::rename_into_all_possibilities(value v) {
vector<Alternation> alts;
alts.resize(d.size());
for (int i = 0; i < (int)d.size(); i++) {
assert (d[i].first == QType::Forall);
alts[i].decls = d[i].second;
alts[i].altType = AltType::Forall;
}
TopAlternatingQuantifierDesc taqd;
taqd.alts = alts;
return taqd.rename_into_all_possibilities(v);
}
| 24.793443 | 124 | 0.575707 | [
"vector"
] |
51f5f4a2055d0a2575f74f4a3b458b965c0a3556 | 1,120 | cpp | C++ | 11838 - Come and Go.cpp | MohammadShakhatreh/Problems | c91b1f33828f6c891967d015df36b7cd3164d421 | [
"MIT"
] | null | null | null | 11838 - Come and Go.cpp | MohammadShakhatreh/Problems | c91b1f33828f6c891967d015df36b7cd3164d421 | [
"MIT"
] | null | null | null | 11838 - Come and Go.cpp | MohammadShakhatreh/Problems | c91b1f33828f6c891967d015df36b7cd3164d421 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
const int N = 2010;
bool vis[N];
stack<int> st;
vector<vector<int> > g;
int n, m, dfstime, idx[N], low[N], cmp;
void dfs(int u){
idx[u] = low[u] = ++dfstime;
st.push(u);
vis[u] = true;
for(int i = 0, v; i < (int)g[u].size(); ++i) {
v = g[u][i];
if(idx[v] == 0) dfs(v);
if(vis[v]) low[u] = min(low[u], low[v]);
}
if(idx[u] == low[u]) {
while(true){
int v = st.top();
st.pop();
vis[v] = false;
if(v == u) break;
}
++cmp;
}
}
void solve(){
g.clear();
dfstime = 0; cmp = 0;
while(!st.empty()) st.pop();
memset(vis, 0, sizeof vis);
memset(idx, 0, sizeof idx);
memset(low, 0, sizeof low);
g.resize(n);
for(int i = 0, from, to, p; i < m; ++i){
scanf("%d%d%d", &from, &to, &p);
--from; --to;
g[from].push_back(to);
if(p == 2) g[to].push_back(from);
}
for(int i = 0; i < n; ++i)
if(idx[i] == 0)
dfs(i);
if(cmp == 1)
puts("1");
else
puts("0");
}
int main(int argc, char const *argv[]){
#ifndef ONLINE_JUDGE
freopen("in.txt", "r", stdin);
#endif
while(scanf("%d%d", &n, &m) && n > 0)
solve();
return 0;
} | 15.555556 | 47 | 0.514286 | [
"vector"
] |
51f753ae0879171d4070563f49fdaba0c18196a4 | 761 | cpp | C++ | Leetcode Solution/Binary Search/Easy/349. Intersection of Two Arrays.cpp | bilwa496/Placement-Preparation | bd32ee717f671d95c17f524ed28b0179e0feb044 | [
"MIT"
] | 169 | 2021-05-30T10:02:19.000Z | 2022-03-27T18:09:32.000Z | Leetcode Solution/Binary Search/Easy/349. Intersection of Two Arrays.cpp | bilwa496/Placement-Preparation | bd32ee717f671d95c17f524ed28b0179e0feb044 | [
"MIT"
] | 1 | 2021-10-02T14:46:26.000Z | 2021-10-02T14:46:26.000Z | Leetcode Solution/Binary Search/Easy/349. Intersection of Two Arrays.cpp | bilwa496/Placement-Preparation | bd32ee717f671d95c17f524ed28b0179e0feb044 | [
"MIT"
] | 44 | 2021-05-30T19:56:29.000Z | 2022-03-17T14:49:00.000Z |
class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
vector<int> ans;
unordered_map<int,int> mp;
for(int i=0;i<nums1.size();i++)
{
if(mp[nums1[i]])
{
continue;
}
mp[nums1[i]]++;
}
for(int i=0;i<nums2.size();i++)
{
if(mp[nums2[i]])
{
ans.push_back(nums2[i]);
mp[nums2[i]] = 0;
}
}
return ans;
}
};
| 22.382353 | 70 | 0.277267 | [
"vector"
] |
51fb3e94bee6c72c615f497fe4a38c97a1d63ecd | 2,116 | cpp | C++ | swapusage.cpp | hhoffstaette/swapusage | d3109815b6bb154f1254bafa29fecf72d6f17e57 | [
"Apache-2.0"
] | 3 | 2018-10-19T17:47:55.000Z | 2021-12-25T19:56:52.000Z | swapusage.cpp | hhoffstaette/swapusage | d3109815b6bb154f1254bafa29fecf72d6f17e57 | [
"Apache-2.0"
] | null | null | null | swapusage.cpp | hhoffstaette/swapusage | d3109815b6bb154f1254bafa29fecf72d6f17e57 | [
"Apache-2.0"
] | null | null | null |
#include "pid.h"
#include "process.h"
#include "swap.h"
#include <algorithm>
#include <iomanip>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
// lambda for sorting by swap
static auto orderBySwap = [](const unique_ptr<ProcessInfo>& first, const unique_ptr<ProcessInfo>& second)
{
return first->swap > second->swap;
};
int main(int argc, char* argv[])
{
vector<unique_ptr<ProcessInfo>> procs;
bool all_procs = true;
if (argc == 1)
{
// no pid: collect all processes
procs = get_process_infos();
}
else
{
const string pidarg = argv[1];
if (pidarg == "-h" || pidarg == "--help")
{
cerr << "Usage: swapusage [pid]" << endl;
return EXIT_SUCCESS;
}
int pid = to_pid(pidarg.c_str());
if (pid == UNKNOWN_PID)
{
cerr << "Not a process id: " << pidarg << endl;
return EXIT_FAILURE;
}
string name = get_process_name(pid);
if (name == UNKNOWN_PROCESS_NAME)
{
cerr << "No such process: " << pid << endl;
return EXIT_FAILURE;
}
long swap = get_swap_for_pid(pid);
if (swap == UNKNOWN_SWAP)
{
cerr << "Cannot read swap for pid: " << pid << endl;
return EXIT_FAILURE;
}
// finally collect valid process info
if (swap > 0)
{
procs.emplace_back(make_unique<ProcessInfo>(pid, swap, name));
all_procs = false;
}
}
if (procs.empty())
{
cout << "No swap used." << endl ;
}
else
{
// sort by swap
sort(procs.begin(), procs.end(), orderBySwap);
cout << "====================================" << endl;
cout << setw(8) << "Swap kB";
cout << setw(6) << "PID";
cout << " ";
cout << setw(16) << left << "Name" << endl;
cout << "====================================" << endl;
long all_swap = 0;
for (unique_ptr<ProcessInfo>& p: procs)
{
cout << setw(8) << right << p->swap;
cout << setw(6) << right << p->pid;
cout << " ";
cout << setw(16) << left << p->name << endl;
all_swap += p->swap;
}
if (all_procs)
{
cout << "------------------------------------" << endl;
cout << setw(8) << right << all_swap << " kB total." << endl;
}
}
return EXIT_SUCCESS;
}
| 19.962264 | 105 | 0.558129 | [
"vector"
] |
51fc59f0c76203a59d438d1714b353976aefe40d | 1,040 | cc | C++ | algo/trees/preorder.cc | liuheng/recipes | 6f3759ab4e4fa64d9fd83a60ee6b6846510d910b | [
"MIT"
] | null | null | null | algo/trees/preorder.cc | liuheng/recipes | 6f3759ab4e4fa64d9fd83a60ee6b6846510d910b | [
"MIT"
] | null | null | null | algo/trees/preorder.cc | liuheng/recipes | 6f3759ab4e4fa64d9fd83a60ee6b6846510d910b | [
"MIT"
] | null | null | null | #include <stack>
#include <vector>
#include <cstdio>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
vector<int> preorderTraversal(TreeNode *root) {
stack<TreeNode*> S;
vector<int> values;
TreeNode *node = root;
while (!S.empty() || node != NULL)
{
if (node != NULL)
{
values.push_back(node->val);
S.push(node);
node = node->left;
}
else
{
node = S.top();
S.pop();
node = node->right;
}
}
return values;
}
int main() {
TreeNode *root = new TreeNode(0);
TreeNode *p1 = new TreeNode(1);
TreeNode *p2 = new TreeNode(2);
TreeNode *p3 = new TreeNode(3);
TreeNode *p4 = new TreeNode(4);
TreeNode *p5 = new TreeNode(5);
root->left = p1;
p1->right = p2;
root->right = p3;
p3->left = p4;
p3->right = p5;
vector<int> v = preorderTraversal(root);
for (int i: v) {
printf("%d ", i);
}
printf("\n");
return 0;
}
| 18.245614 | 56 | 0.555769 | [
"vector"
] |
a4010939da8f1b50c4106150f42c9a0107452e44 | 1,512 | hpp | C++ | gcpp/classes/ocode.hpp | razzlefratz/MotleyTools | 3c69c574351ce6f4b7e687c13278d4b6cbb200f3 | [
"0BSD"
] | 2 | 2015-10-15T19:32:42.000Z | 2021-12-20T15:56:04.000Z | gcpp/classes/ocode.hpp | razzlefratz/MotleyTools | 3c69c574351ce6f4b7e687c13278d4b6cbb200f3 | [
"0BSD"
] | null | null | null | gcpp/classes/ocode.hpp | razzlefratz/MotleyTools | 3c69c574351ce6f4b7e687c13278d4b6cbb200f3 | [
"0BSD"
] | null | null | null | /*====================================================================*
*
* ocode.hpp - declaration of ocode class;
*
* this object implements a generic means of storing information by
* name and classification; it is used by the olist, oheap, oroster,
* oglossary and ocatalog oject classes;
*
*. Motley Tools by Charles Maier
*: Published 1982-2005 by Charles Maier for personal use
*; Licensed under the Internet Software Consortium License
*
*--------------------------------------------------------------------*/
#ifndef oCODE_HEADER
#define oCODE_HEADER
/*====================================================================*
* custom header files;
*--------------------------------------------------------------------*/
#include "../classes/stdafx.hpp"
#include "../classes/otypes.hpp"
/*====================================================================*
* class declaration;
*--------------------------------------------------------------------*/
class __declspec (dllexport) ocode
{
public:
ocode ();
virtual ~ ocode ();
char const * label (signed value, char const * label) const;
signed value (char const * label, signed value) const;
protected:
const struct _code_ * mtable;
unsigned mcount;
private:
static const struct _code_ table [];
static const unsigned count;
};
/*====================================================================*
* end declaration;
*--------------------------------------------------------------------*/
#endif
| 28.528302 | 72 | 0.439153 | [
"object"
] |
a408f6f73317ee830062ef4878b32cb3f81f053b | 3,979 | cpp | C++ | src/core/classfactory.cpp | dream-overflow/o3d | 087ab870cc0fd9091974bb826e25c23903a1dde0 | [
"FSFAP"
] | 2 | 2019-06-22T23:29:44.000Z | 2019-07-07T18:34:04.000Z | src/core/classfactory.cpp | dream-overflow/o3d | 087ab870cc0fd9091974bb826e25c23903a1dde0 | [
"FSFAP"
] | null | null | null | src/core/classfactory.cpp | dream-overflow/o3d | 087ab870cc0fd9091974bb826e25c23903a1dde0 | [
"FSFAP"
] | null | null | null | /**
* @file classfactory.cpp
* @brief
* @author Frederic SCHERMA (frederic.scherma@dreamoverflow.org)
* @date 2001-12-25
* @copyright Copyright (c) 2001-2017 Dream Overflow. All rights reserved.
* @details
*/
#include "o3d/core/precompiled.h"
#include "o3d/core/classfactory.h"
#include "o3d/core/baseobject.h"
#include "o3d/core/debug.h"
#include "o3d/core/memory.h"
using namespace o3d;
//ClassFactory::T_ClassFactoryMap ClassFactory::m_Map;
ClassFactory::T_ClassInfoMap *ClassFactory::m_mapInfo = nullptr;
ClassFactory::T_IdClassInfoMap *ClassFactory::m_idMapInfo = nullptr;
// instanciation
/*Serialize* ClassFactory::getInstanceOfSerialize(const String &className)
{
T_ClassFactoryMap::iterator it = m_Map.find(className);
if (it == m_Map.end())
{
O3D_ERROR(E_InvalidClassName(className));
}
return (*it).second;
}*/
ClassInfo* ClassFactory::getInstanceOfClassInfo(const String &className)
{
T_ClassInfoMap::iterator it = m_mapInfo->find(className);
if (it == m_mapInfo->end())
{
O3D_ERROR(E_InvalidClassName(className));
}
return (*it).second;
}
// delete the map
void ClassFactory::destroy()
{
deletePtr(m_mapInfo);
deletePtr(m_idMapInfo);
}
// serialisation
/*Bool ClassFactory::writeToFile(OutStream& os, Serialize &object)
{
// export class name
String className = object.getClassName();
file << className;
// export object
return object.writeToFile(file);
}
Serialize* ClassFactory::readFromFile(InStream& is)
{
// import class name
String className;
file >> className;
// create a class instance
Serialize* object = getInstanceOfSerialize(className)->makeInstance();
// and read the object
if (object->readFromFile(file))
return object;
else
{
deletePtr(object);
return nullptr;
}
}*/
//! Write an object to a file for a further class factory read
Bool ClassFactory::writeToFile(OutStream& os, BaseObject &object)
{
// export class name
String className = object.getClassInfo()->getClassName();
os << className;
// export object
return object.writeToFile(os);
}
BaseObject* ClassFactory::readFromFile(InStream& is, BaseObject *parent)
{
// import class name
String className;
is >> className;
// create a class instance
BaseObject *object = getInstanceOfClassInfo(className)->createInstance(parent);
// and read the object
if (object->readFromFile(is))
return object;
else
{
deletePtr(object);
return nullptr;
}
}
// register classes
/*void ClassFactory::registerSerialize(const String& className, Serialize *obj)
{
m_Map[className] = obj;
}
void ClassFactory::unregisterSerialize(const String& className)
{
T_ClassFactoryMap::iterator it = m_Map.find(className);
if (it != m_Map.end())
m_Map.erase(it);
}*/
void ClassFactory::registerClassInfo(const String &className, ClassInfo *obj)
{
if (!m_mapInfo)
m_mapInfo = new T_ClassInfoMap;
if (!m_idMapInfo)
m_idMapInfo = new T_IdClassInfoMap;
if (m_mapInfo->find(obj->getClassName()) != m_mapInfo->end())
O3D_ERROR(E_InvalidOperation(String("Class name is already registred: ") + obj->getClassName()));
if (m_idMapInfo->find(obj->getClassType()) != m_idMapInfo->end())
O3D_ERROR(E_InvalidOperation(String("Class type is already registred: ") << obj->getClassType()));
m_idMapInfo->insert(std::pair<UInt32, ClassInfo*>(obj->getClassType(), obj));
m_mapInfo->insert(std::pair<String, ClassInfo*>(className, obj));
}
void ClassFactory::unRegisterClassInfo(const String& className)
{
if (!m_mapInfo)
return;
if (!m_idMapInfo)
return;
T_ClassInfoMap::iterator it = m_mapInfo->find(className);
ClassInfo *obj = nullptr;
if (it != m_mapInfo->end())
{
obj = it->second;
m_mapInfo->erase(it);
}
if (obj != nullptr)
{
T_IdClassInfoMap::iterator it2 = m_idMapInfo->find(obj->getClassType());
if (it2 != m_idMapInfo->end())
m_idMapInfo->erase(it2);
deletePtr(obj);
}
}
| 23.269006 | 100 | 0.703192 | [
"object"
] |
a4232b0a3b7c5b693e0ed087140f96cabbc46ce9 | 4,639 | hpp | C++ | mi/MeshImporterObj.hpp | tmichi/xendocast | 482c7e668423c11b1cc0f6e2fa98bd3b582536a8 | [
"MIT"
] | null | null | null | mi/MeshImporterObj.hpp | tmichi/xendocast | 482c7e668423c11b1cc0f6e2fa98bd3b582536a8 | [
"MIT"
] | 1 | 2017-06-14T04:32:12.000Z | 2017-06-14T04:32:12.000Z | mi/MeshImporterObj.hpp | tmichi/xendocast | 482c7e668423c11b1cc0f6e2fa98bd3b582536a8 | [
"MIT"
] | null | null | null | /**
* @file MeshImporterObj.hpp
* @author Takashi Michikawa <michikawa@acm.org>
*/
#ifndef MI_MESH_IMPORTER_OBJ_HPP
#define MI_MESH_IMPORTER_OBJ_HPP 1
#include <vector>
#include "Tokenizer.hpp"
#include "MeshImporter.hpp"
namespace mi
{
/**
* @class MeshImporterObj MeshImporterObj.hpp <mi/MeshImporterObj.hpp>
* @brief Obj Importer.
*/
class MeshImporterObj : public MeshImporter
{
public:
/**
* @brief Constructor.
* @param [in] mesh Mesh object.
*/
explicit MeshImporterObj ( Mesh& mesh ) : MeshImporter( mesh, false ) {
return;
}
/**
* @brief Destructor.
*/
virtual ~MeshImporterObj ( void ) {
return;
}
private:
/**
* @brief Write body part of STL file.
* @param [in] File stream.
*/
virtual bool readBody ( std::ifstream &fin ) {
Mesh& mesh = this->getMesh();
std::vector<Eigen::Vector3d> vx;
std::deque< std::deque<int> > index;
int count = -1;
while ( fin ) {
std::string buffer;
std::getline( fin, buffer );
if( fin.eof() ) break;
if ( buffer.find_first_of( "#" ) == 0 ) continue;
if ( buffer.length() == 0 ) continue;
Tokenizer tokenizer1 ( buffer, " " ) ;
if ( tokenizer1.size() == 0 ) continue;
if ( tokenizer1.get( 0 ).compare( "v" ) == 0 ) {
Eigen::Vector3d p;
p.x() = std::atof( tokenizer1.get( 1 ).c_str() );
p.y() = std::atof( tokenizer1.get( 2 ).c_str() );
p.z() = std::atof( tokenizer1.get( 3 ).c_str() );
vx.push_back( p );
} else if ( tokenizer1.get( 0 ).compare( "g" ) == 0 ) {
count++;
} else if ( tokenizer1.get( 0 ).compare( "f" ) == 0 ) {
index.push_back( std::deque<int>() );
for( int i = 1 ; i < tokenizer1.size() ; ++i ) {
Tokenizer tokenizer2( tokenizer1.get( i ), "/" );
if ( tokenizer2.get( 0 ).length() != 0 ) {
std::string token = tokenizer2.get( 0 );
int fid = std::atoi( token.c_str() );
if( fid != 0 ) index[ index.size() - 1 ].push_back( fid - 1 );
}
}
}
}
mesh.init();
for ( size_t i = 0 ; i < vx.size() ; ++i ) {
mesh.addPoint( vx[i] );
}
for( size_t j = 0 ; j < index.size() ; ++j ) {
//N-gon -> triangles
for ( size_t k = 0 ; k < index[j].size() - 2; ++k ) {
std::vector<int> fid;
fid.push_back( index[j][0] );
fid.push_back( index[j][k+1] );
fid.push_back( index[j][k+2] );
mesh.addFace( fid );
}
}
return true;
}
public:
/**
* @brief Return type of expoter.
* @return String value.
*/
virtual std::string toString ( void ) const {
return std::string ( "obj" );
}
};
}
#endif// MI_MESH_ImportER_OBJ_HPP
| 43.764151 | 119 | 0.318388 | [
"mesh",
"object",
"vector"
] |
a425d7dca537d1dd1b8c3210d642afb40ae6292f | 5,237 | cc | C++ | src/memo/model/steg/Steg.cc | infinit/memo | 3a8394d0f647efe03ccb8bfe885a7279cb8be8a6 | [
"Apache-2.0"
] | 124 | 2017-06-22T19:20:54.000Z | 2021-12-23T21:36:37.000Z | src/memo/model/steg/Steg.cc | infinit/memo | 3a8394d0f647efe03ccb8bfe885a7279cb8be8a6 | [
"Apache-2.0"
] | 4 | 2017-08-21T15:57:29.000Z | 2019-01-10T02:52:35.000Z | src/memo/model/steg/Steg.cc | infinit/memo | 3a8394d0f647efe03ccb8bfe885a7279cb8be8a6 | [
"Apache-2.0"
] | 12 | 2017-06-29T09:15:35.000Z | 2020-12-31T12:39:52.000Z | #include <arpa/inet.h>
#include <boost/filesystem/fstream.hpp>
#include <elle/cryptography/hash.hh>
#include <elle/random.hh>
#include <elle/reactor/filesystem.hh>
#include <elle/system/Process.hh>
#include <memo/model/steg/Steg.hh>
#include <memo/model/MissingBlock.hh>
#include <memo/model/blocks/Block.hh>
extern "C"
{
void outguess_extract(
u_char* key, int key_length, // secret key
u_char** out, u_int* out_len, // output extracted/decrypted data
char* filename // input image
);
int outguess_inject(
u_char* data, int len, // data to embed
u_char* key, int key_length, // secret key
char* filename // input/output image
);
}
ELLE_LOG_COMPONENT("memo.fs.steg");
namespace memo
{
namespace model
{
namespace steg
{
namespace bfs = boost::filesystem;
class InjectionFailure: public elle::reactor::filesystem::Error
{
public:
InjectionFailure()
: elle::reactor::filesystem::Error(EIO, "injection failure")
{}
};
Steg::Steg(bfs::path const& storage, std::string const& pass)
: _storage_path(storage)
, _passphrase(pass)
{
// populate file list
for (auto const& p: bfs::recursive_directory_iterator(_storage_path))
if (p.extension() == ".jpg" || p.extension() == ".JPG")
{
ELLE_DEBUG("caching %s", p);
_free_blocks.push_back(p);
auto hash = elle::cryptography::hash::sha256(p.string());
auto const res = Address(hash.contents());
_cache.emplace(res, p);
}
}
Address
Steg::_pick() const
{
if (_free_blocks.empty())
throw std::bad_alloc();
auto v = elle::pick_one(_free_blocks.size());
bfs::path p = _free_blocks[v];
_free_blocks[v] = _free_blocks[_free_blocks.size() - 1];
_free_blocks.pop_back();
auto const hash = elle::cryptography::hash::sha256(p.string());
auto const res = Address(hash.contents());
_cache.emplace(res, p);
_used_blocks.push_back(res);
return res;
}
std::unique_ptr<blocks::MutableBlock>
Steg::_make_mutable_block() const
{
if (_root)
{
Address address = _pick();
auto res = std::make_unique<blocks::Block>(address);
return res;
}
else
{
_root = _pick();
_root_data = std::make_unique<blocks::Block>(*_root);
Address user_root = _pick();
_root_data->data().append(user_root.value(), sizeof(Address));
const_cast<Steg*>(this)->__store(*_root_data);
return std::make_unique<blocks::Block>(*_root);
}
}
void
Steg::_store(blocks::Block& block)
{
if (block.address() == *_root)
{
Address redirect(_root_data->data().contents());
blocks::Block b(redirect, elle::Buffer(block.data().contents(), block.data().size()));
__store(b);
}
else
__store(block);
}
void
Steg::__store(blocks::Block& block)
{
if (block.data().empty())
return;
elle::Buffer b;
b.append("steg", 4);
int32_t size = block.data().size();
size = htonl(size);
b.append(&size, 4);
b.append(block.data().contents(), block.data().size());
auto it = _cache.find(block.address());
if (it == _cache.end())
throw MissingBlock(block.address());
int res = outguess_inject(b.mutable_contents(), b.size(),
(unsigned char*)_passphrase.c_str(), _passphrase.length(),
(char*)it->second.string().c_str());
if (res < 0)
throw InjectionFailure();
ELLE_TRACE("Injected %s bytes from %s", b.size(), it->second);
}
std::unique_ptr<blocks::Block>
Steg::_fetch(Address address) const
{
if (!_root)
{
ELLE_DEBUG("First fetch: %x", address);
_root = address;
_root_data = __fetch(address);
Address redirect(_root_data->data().contents());
return __fetch(redirect);
}
if (_root == address)
{
Address redirect(_root_data->data().contents());
return __fetch(redirect);
}
return __fetch(address);
}
std::unique_ptr<blocks::Block>
Steg::__fetch(Address address) const
{
auto it = _cache.find(address);
if (it == _cache.end())
throw MissingBlock(address);
{
auto itfree = std::find(_free_blocks.begin(), _free_blocks.end(), it->second);
// Check if we mistakenly believe the bloc is free
if (itfree != _free_blocks.end())
{
_free_blocks[itfree - _free_blocks.begin()] = _free_blocks[_free_blocks.size() - 1];
_free_blocks.pop_back();
}
}
unsigned char* d;
unsigned int dlen;
outguess_extract((unsigned char*)_passphrase.c_str(), _passphrase.length(),
&d, &dlen,
(char*)it->second.string().c_str());
ELLE_TRACE("Extracted %s bytes from %s", dlen, it->second);
if (memcmp("steg", d, 4))
{
ELLE_WARN("Corrupted data");
free(d);
return std::make_unique<blocks::Block>(address);
}
int32_t size = *((int32_t*)d + 1);
size = ntohl(size);
if (size > dlen - 8)
throw std::runtime_error("Short read");
if (size < dlen - 8)
ELLE_WARN("Too much data: %s > %s", dlen-8, size);
elle::Buffer data;
data.append(d+8, size);
free(d);
ELLE_DEBUG("fetched %s: %s bytes", it->second, data.size());
return std::make_unique<blocks::Block>(address, std::move(data));
}
void
Steg::_remove(Address address)
{
auto it = _cache.find(address);
if (it == _cache.end())
throw MissingBlock(address);
_free_blocks.push_back(it->second);
}
}}}
| 25.42233 | 90 | 0.647508 | [
"model"
] |
a4277fe202eb525052ec019efda5e13a85a73ad8 | 1,171 | cpp | C++ | framework/GUI/GUIJavascript/Sources/ModuleGUIJavascript.cpp | RakeshShrestha/kigs | 2ada0068c8618935ed029db442ecf58f6bf96126 | [
"MIT"
] | 38 | 2020-05-08T13:39:57.000Z | 2022-03-28T05:58:41.000Z | framework/GUI/GUIJavascript/Sources/ModuleGUIJavascript.cpp | RakeshShrestha/kigs | 2ada0068c8618935ed029db442ecf58f6bf96126 | [
"MIT"
] | 3 | 2020-06-01T14:12:36.000Z | 2020-06-24T13:05:21.000Z | framework/GUI/GUIJavascript/Sources/ModuleGUIJavascript.cpp | RakeshShrestha/kigs | 2ada0068c8618935ed029db442ecf58f6bf96126 | [
"MIT"
] | 16 | 2020-05-04T19:20:35.000Z | 2022-01-25T08:31:29.000Z | #include "Core.h"
#include "ModuleGUIJavascript.h"
#include "WindowJavascript.h"
#include "DisplayDeviceCapsJavascript.h"
IMPLEMENT_CLASS_INFO(ModuleGUIJavascript);
ModuleGUIJavascript::ModuleGUIJavascript(const kstl::string& name,CLASS_NAME_TREE_ARG) : ModuleBase(name,PASS_CLASS_NAME_TREE_ARG)
{
}
ModuleGUIJavascript::~ModuleGUIJavascript()
{
}
void ModuleGUIJavascript::Init(KigsCore* core, const kstl::vector<CoreModifiableAttribute*>* params)
{
BaseInit(core,"GUIJavascript",params);
//! declare WindowJavascript to be the current implementation of Window
DECLARE_FULL_CLASS_INFO(core,WindowJavascript,Window,GUI)
DECLARE_FULL_CLASS_INFO(core,DisplayDeviceCapsJavascript,DisplayDeviceCaps,GUI)
}
void ModuleGUIJavascript::Close()
{
BaseClose();
}
void ModuleGUIJavascript::Update(const Timer& timer, void* addParam)
{
}
SP<ModuleBase> MODULEINITFUNC(KigsCore* core, const kstl::vector<CoreModifiableAttribute*>* params)
{
KigsCore::ModuleStaticInit(core);
DECLARE_CLASS_INFO_WITHOUT_FACTORY(ModuleGUIJavascript, "ModuleGUIJavascript");
auto ptr = MakeRefCounted<ModuleGUIJavascript>("ModuleGUIJavascript");
ptr->Init(core,params);
return ptr;
}
| 26.613636 | 130 | 0.809564 | [
"vector"
] |
a42cfab99d23e86eec3ef4f53c3ab040303a5ccf | 5,781 | cpp | C++ | src/webservice/WebService.cpp | zhangguoqing/nebula | cd3b7d58c3165de28528c4e64abbc8f2b87a3ca5 | [
"Apache-2.0"
] | null | null | null | src/webservice/WebService.cpp | zhangguoqing/nebula | cd3b7d58c3165de28528c4e64abbc8f2b87a3ca5 | [
"Apache-2.0"
] | null | null | null | src/webservice/WebService.cpp | zhangguoqing/nebula | cd3b7d58c3165de28528c4e64abbc8f2b87a3ca5 | [
"Apache-2.0"
] | null | null | null | /* Copyright (c) 2018 vesoft inc. All rights reserved.
*
* This source code is licensed under Apache 2.0 License,
* attached with Common Clause Condition 1.0, found in the LICENSES directory.
*/
#include "base/Base.h"
#include "webservice/WebService.h"
#include <proxygen/httpserver/RequestHandlerFactory.h>
#include "webservice/NotFoundHandler.h"
#include "webservice/GetFlagsHandler.h"
#include "webservice/SetFlagsHandler.h"
#include "webservice/GetStatsHandler.h"
#include "webservice/StatusHandler.h"
DEFINE_int32(ws_http_port, 11000, "Port to listen on with HTTP protocol");
DEFINE_int32(ws_h2_port, 11002, "Port to listen on with HTTP/2 protocol");
DEFINE_string(ws_ip, "127.0.0.1", "IP/Hostname to bind to");
DEFINE_int32(ws_threads, 4, "Number of threads for the web service.");
namespace nebula {
namespace {
class WebServiceHandlerFactory : public proxygen::RequestHandlerFactory {
public:
explicit WebServiceHandlerFactory(HandlerGen&& genMap) : handlerGenMap_(genMap) {}
void onServerStart(folly::EventBase*) noexcept override {
}
void onServerStop() noexcept override {
}
proxygen::RequestHandler* onRequest(proxygen::RequestHandler*,
proxygen::HTTPMessage* msg) noexcept override {
std::string path = msg->getPath();
if (path == "/") {
path = "/status";
}
VLOG(2) << "Got request \"" << path << "\"";
auto it = handlerGenMap_.find(path);
if (it != handlerGenMap_.end()) {
return it->second();
}
// Unknown url path
return new NotFoundHandler();
}
private:
HandlerGen handlerGenMap_;
};
} // anonymous namespace
using proxygen::HTTPServer;
using proxygen::HTTPServerOptions;
using folly::SocketAddress;
std::unique_ptr<HTTPServer> WebService::server_;
std::unique_ptr<thread::NamedThread> WebService::wsThread_;
HandlerGen WebService::handlerGenMap_;
// static
void WebService::registerHandler(const std::string& path,
std::function<proxygen::RequestHandler*()>&& gen) {
handlerGenMap_.emplace(path, gen);
}
// static
Status WebService::start() {
// Register the default handlers
registerHandler("/get_flag", [] {
return new GetFlagsHandler();
});
registerHandler("/get_flags", [] {
return new GetFlagsHandler();
});
registerHandler("/set_flag", [] {
return new SetFlagsHandler();
});
registerHandler("/set_flags", [] {
return new SetFlagsHandler();
});
registerHandler("/get_stat", [] {
return new GetStatsHandler();
});
registerHandler("/get_stats", [] {
return new GetStatsHandler();
});
registerHandler("/", [] {
return new StatusHandler();
});
registerHandler("/status", [] {
return new StatusHandler();
});
std::vector<HTTPServer::IPConfig> ips = {
{SocketAddress(FLAGS_ws_ip, FLAGS_ws_http_port, true), HTTPServer::Protocol::HTTP},
{SocketAddress(FLAGS_ws_ip, FLAGS_ws_h2_port, true), HTTPServer::Protocol::HTTP2},
};
CHECK_GT(FLAGS_ws_threads, 0)
<< "The number of webservice threads must be greater than zero";
HTTPServerOptions options;
options.threads = static_cast<size_t>(FLAGS_ws_threads);
options.idleTimeout = std::chrono::milliseconds(60000);
options.enableContentCompression = false;
options.handlerFactories = proxygen::RequestHandlerChain()
.addThen<WebServiceHandlerFactory>(std::move(handlerGenMap_))
.build();
options.h2cEnabled = true;
server_ = std::make_unique<HTTPServer>(std::move(options));
server_->bind(ips);
std::condition_variable cv;
std::mutex mut;
auto status = Status::OK();
bool serverStartedDone = false;
// Start HTTPServer mainloop in a separate thread
wsThread_ = std::make_unique<thread::NamedThread>(
"webservice-listener",
[&] () {
server_->start(
[&]() {
auto addresses = server_->addresses();
CHECK_EQ(addresses.size(), 2UL);
if (FLAGS_ws_http_port == 0) {
FLAGS_ws_http_port = addresses[0].address.getPort();
}
if (FLAGS_ws_h2_port == 0) {
FLAGS_ws_h2_port = addresses[1].address.getPort();
}
LOG(INFO) << "Web service started on "
<< "HTTP[" << FLAGS_ws_http_port << "], "
<< "HTTP2[" << FLAGS_ws_h2_port << "]";
{
std::lock_guard<std::mutex> g(mut);
serverStartedDone = true;
}
cv.notify_all();
},
[&] (std::exception_ptr eptr) {
CHECK(eptr);
try {
std::rethrow_exception(eptr);
} catch (const std::exception &e) {
status = Status::Error("%s", e.what());
}
{
std::lock_guard<std::mutex> g(mut);
serverStartedDone = true;
}
cv.notify_all();
});
});
{
std::unique_lock<std::mutex> lck(mut);
cv.wait(lck, [&]() {
return serverStartedDone;
});
if (!status.ok()) {
LOG(ERROR) << "Failed to start web service: " << status;
wsThread_->join();
}
}
return status;
}
// static
void WebService::stop() {
server_->stop();
wsThread_->join();
}
} // namespace nebula
| 30.914439 | 91 | 0.572392 | [
"vector"
] |
a42f0b2074600181ca8a1c92d033cd11cf38c9f9 | 3,241 | cpp | C++ | segment_tree/counting_zeros.cpp | KishoreKaushal/CS2800 | c50bf8f3b05d3d226f467e654da82360f7a3e1e0 | [
"MIT"
] | 3 | 2018-03-13T07:44:56.000Z | 2018-12-20T11:04:36.000Z | segment_tree/counting_zeros.cpp | KishoreKaushal/CS2800 | c50bf8f3b05d3d226f467e654da82360f7a3e1e0 | [
"MIT"
] | null | null | null | segment_tree/counting_zeros.cpp | KishoreKaushal/CS2800 | c50bf8f3b05d3d226f467e654da82360f7a3e1e0 | [
"MIT"
] | null | null | null | #include<iostream>
#include<vector>
#include<algorithm>
#include<numeric>
#include<utility>
using namespace std;
#define RIGHT(i) ((i*2 + 2))
#define LEFT(i) ((i*2 + 1))
#define MAXN (100000)
class segment_tree{
public:
int size;
vector<int> arr;
vector<int> tree;
segment_tree(int n){
size = n;
arr.reserve(n+1);
tree.reserve(4*(n+1));
}
void build(){
build(0, 0, size-1);
}
void build(int i, int tl, int tr){
if (tl == tr) {
tree[i] = (arr[tl]==0?1:0); /*1 if arr[tl] is 0*/
} else {
int tm = (tl + tr)/2;
build(LEFT(i), tl, tm);
build(RIGHT(i), tm+1, tr);
/*combine*/
tree[i] = tree[LEFT(i)] + tree[RIGHT(i)];
}
}
void toggle(int pos){
int new_val = arr[pos] = (arr[pos]==0?1:0);
update(0, 0, size-1, pos, new_val);
}
void update(int pos, int new_val){
arr[pos] = new_val;
update(0, 0, size-1, pos, new_val);
}
void update(int i, int tl, int tr, int pos, int new_val){
if (tl == tr){
tree[i] = (new_val==0?1:0);
} else {
int tm = (tl+tr)/2;
if (pos <= tm) update(LEFT(i) , tl, tm, pos, new_val);
else update(RIGHT(i), tm+1, tr, pos, new_val);
/*combine*/
tree[i] = tree[LEFT(i)] + tree[RIGHT(i)];
}
}
int count_zero(int l, int r){
return count_zero(0, 0, size-1, l, r);
}
int count_zero(int i, int tl, int tr, int l, int r){
if (l > r) return 0;
if (tl == l && tr == r) return tree[i];
int tm = (tl + tr)/2;
return count_zero(LEFT(i), tl, tm, l, min(r,tm))
+ count_zero(RIGHT(i), tm+1, tr, max(tm+1 , l), r);
}
int find_kth(int k){
if (k > count_zero(0,size-1)) return -1; /*no kth zero*/
find_kth(0, 0, size-1, k);
}
int find_kth(int i, int tl, int tr, int k){
if (tree[i] < k) return -1;
if (tl == tr) return tl;
int tm = (tl + tr)/2;
if (tree[LEFT(i)] >= k) return find_kth(LEFT(i), tl, tm, k);
return find_kth(RIGHT(i), tm+1, tr, k-tree[LEFT(i)]);
}
};
int main(){
ios_base::sync_with_stdio(false);
cin.tie(nullptr); cout.tie(nullptr);
cout.setf(ios::fixed); cout.precision(6);
int N; // size of the array
int Q; // number of the queries
int T; // type of query
int L,R,P,K;
// three types of the query is possible:
// 1. count the number of zeros in the given range - L , R
// 2. toggle the bits at position P - P
// 3. find the index of the Kth zero - K
cin>>N>>Q;
segment_tree seg(N);
for (int i=0; i<N; ++i){
cin>>seg.arr[i];
}
seg.build();
for(int i=0; i<Q; ++i){
cin>>T;
switch(T){
case 1: cin>>L>>R; cout<<seg.count_zero(L,R)<<endl;
break;
case 2: cin>>P; seg.toggle(P);
break;
case 3: cin>>K; cout<<seg.find_kth(K)<<endl;
break;
default:
break;
}
}
return 0;
} | 25.519685 | 68 | 0.471768 | [
"vector"
] |
bf9a645da2b97565c00d42aa4975cacbf04d69d0 | 6,903 | cpp | C++ | src/GraphSeg.cpp | Shengzi99/GraphSegmentation-plug-play-python-lib | ccf21246053bd6a889d9cbbae33bb43e9b0396f5 | [
"MIT"
] | 1 | 2020-08-10T03:43:12.000Z | 2020-08-10T03:43:12.000Z | src/GraphSeg.cpp | Shengzi99/GraphSegmentation-DLL-for-Python | ccf21246053bd6a889d9cbbae33bb43e9b0396f5 | [
"MIT"
] | null | null | null | src/GraphSeg.cpp | Shengzi99/GraphSegmentation-DLL-for-Python | ccf21246053bd6a889d9cbbae33bb43e9b0396f5 | [
"MIT"
] | null | null | null | #include <pybind11/pybind11.h>
#include <pybind11/numpy.h>
#include <iostream>
#include <set>
#include <string>
#include <assert.h>
#include "segAlgorithm.h"
#include "gaussianFilter.h"
namespace py = pybind11;
class GraphSeg {
public:
GraphSeg(py::array_t<double, py::array::c_style | py::array::forcecast> inImg);
~GraphSeg();
void segment(double k, double sigma, long min_size);
py::array_t<long> getSeg();
py::array_t<double> getFilteredImage();
py::array_t<long> getSupPixelGraph(long edge_method);
long getRegionNum() { return region_num; };
py::array_t<long> getRegionSize();
private:
const double* img;
double* img_filtered;
long* seg;
long* supEdges;
long ch;
long w;
long h;
long region_num;
long* region_size;
long* segImage(const double* img, long ch, long h, long w, double k, long min_size);
void gaussianFilter(double sigma);
};
GraphSeg::GraphSeg(py::array_t<double, py::array::c_style | py::array::forcecast> inImg) {
const long ndim = (long)inImg.ndim();
if (ndim != 3) {
throw std::invalid_argument("expected input shape [channel, height, width]. for gray scale image input shape should be [1, height, width]");
}
else {
py::buffer_info buff_inf = inImg.request();
std::vector<pybind11::ssize_t> shape = buff_inf.shape;
this->img = (const double*)buff_inf.ptr;
this->ch = shape[0];
this->h = shape[1];
this->w = shape[2];
this->img_filtered = new double[ch * h * w];
this->seg = new long[this->w * this->h];
this->region_num = this->w * this->h;
this->region_size = NULL;
this->supEdges = NULL;
}
}
GraphSeg::~GraphSeg() {
delete[] seg;
delete[] img_filtered;
delete[] supEdges;
delete[] region_size;
}
void GraphSeg::segment(double k, double sigma, long min_size) {
if (sigma != -1) {
gaussianFilter(sigma);
this->seg = segImage(this->img_filtered, ch, h, w, k, min_size);
}
else {
this->seg = segImage(this->img, ch, h, w, k, min_size);
}
}
py::array_t<long> GraphSeg::getSeg() {
return py::array_t<long>(
{ h, w },
{ w * sizeof(long), sizeof(long) },
seg);
}
py::array_t<double> GraphSeg::getFilteredImage() {
return py::array_t<double>(
{ch, h, w},
{ h * w * sizeof(double), w * sizeof(double), sizeof(double) },
img_filtered);
}
py::array_t<long> GraphSeg::getRegionSize() {
return py::array_t<long>(
{ region_num },
{ sizeof(long) },
region_size);
}
py::array_t<long> GraphSeg::getSupPixelGraph(long edge_method) {
delete[] supEdges;
long edgeNum = 0;
if (edge_method == 0) {
set<long>* nb = new set<long>[region_num];
for (long i = 0; i < h; i++) {
for (long j = 0; j < w; j++) {
if ((i<h-1)&&(seg[(i + 1)*w + j] > seg[i * w + j])) {
nb[seg[i * w + j]].insert(seg[(i + 1) * w + j]);
}
if ((i>0)&&(seg[(i - 1) * w + j] > seg[i * w + j])) {
nb[seg[i * w + j]].insert(seg[(i - 1) * w + j]);
}
if ((j<w-1)&&(seg[i * w + j + 1] > seg[i * w + j])) {
nb[seg[i * w + j]].insert(seg[i * w + j + 1]);
}
if ((j>0)&&(seg[i * w + j - 1] > seg[i * w + j])) {
nb[seg[i * w + j]].insert(seg[i * w + j - 1]);
}
}
}
for (long i = 0; i < region_num; i++) {
edgeNum += nb[i].size();
}
supEdges = new long[2 * edgeNum];
long curIndex = 0;
for (long i = 0; i < region_num; i++) {
for (auto it = nb[i].begin(); it != nb[i].end();it++) {
supEdges[curIndex] = i;
curIndex++;
supEdges[curIndex] = *it;
curIndex++;
}
}
delete[] nb;
}
else if (edge_method == 1){
edgeNum = region_num * (region_num - 1) / 2;
supEdges = new long[2 * edgeNum];
long curIndex = 0;
for (long i = 0; i < region_num; i++){
for (long j = i + 1; j < region_num; j++){
supEdges[curIndex] = i;
curIndex++;
supEdges[curIndex] = j;
curIndex++;
}
}
// assert((2 * edgeNum) == curIndex);
}
else {assert(0);}
return py::array_t<long>(
{ edgeNum, 2L},
{ 2 * sizeof(long), sizeof(long) },
supEdges);
}
void GraphSeg::gaussianFilter(double sigma) {
gaussian_filter(img, img_filtered, ch, h, w, sigma);
}
// segent an [channel, height, width] shaped image
long* GraphSeg::segImage(const double* img, long ch, long h, long w, double k, long min_size) {
delete[] region_size;
region_size = NULL;
long pixNum = h * w;
edge* edges = new edge[pixNum * 4];
long eNum = 0;
for (long y = 0; y < h; y++) {
for (long x = 0; x < w; x++) {
if (x < w - 1) {
edges[eNum].a = y * w + x;
edges[eNum].b = y * w + (x + 1);
edges[eNum].w = diff(img, ch, h, w, y, x, y, x + 1);
eNum++;
}
if (y < h - 1) {
edges[eNum].a = y * w + x;
edges[eNum].b = (y + 1) * w + x;
edges[eNum].w = diff(img, ch, h, w, y, x, y + 1, x);
eNum++;
}
if ((x < w - 1) && (y < h - 1)) {
edges[eNum].a = y * w + x;
edges[eNum].b = (y + 1) * w + (x + 1);
edges[eNum].w = diff(img, ch, h, w, y, x, y + 1, x + 1);
eNum++;
}
if ((x < w - 1) && (y > 0)) {
edges[eNum].a = y * w + x;
edges[eNum].b = (y - 1) * w + (x + 1);
edges[eNum].w = diff(img, ch, h, w, y, x, y - 1, x + 1);
eNum++;
}
}
}
forest* F = segGraph(pixNum, eNum, edges, k);
// merge region smaller than min_size
for (long i = 0; i < eNum; i++) {
long a = F->find(edges[i].a);
long b = F->find(edges[i].b);
if ((a != b) && ((F->size(a) < min_size) || (F->size(b) < min_size))) {
F->join(a, b);
}
}
delete[] edges;
// get root index of every node
long* result = new long[pixNum];
for (long i = 0; i < pixNum; i++) {
result[i] = F->find(i);
}
long* match = new long[pixNum];
long* res_copy = new long[pixNum];
// get a copy of result, and sort the copy
for (long i = 0; i < pixNum; i++) {
res_copy[i] = result[i];
}
sort(res_copy, res_copy + pixNum);
// count the number of unique value in res_copy, and get the initial root number to ordered number map
long count = 0;
for (long i = 0; i < pixNum; i++) {
match[res_copy[i]] = count;
if ((i < pixNum -1 ) && (res_copy[i + 1] > res_copy[i]))
count++;
}
// map result value to ordered number
for (long i = 0; i < pixNum; i++) {
result[i] = match[result[i]];
}
region_num = count + 1;
region_size = new long[region_num];
for (long i = 0; i < pixNum; i++) {
long root = F->find(i);
region_size[match[root]] = F->size(root);
}
delete F;
delete[] match;
delete[] res_copy;
return result;
}
PYBIND11_MODULE(GraphSeg, m) {
py::class_<GraphSeg>(m, ("GraphSeg"))
.def(py::init< py::array_t<double, py::array::c_style | py::array::forcecast>>())
.def("segment", &GraphSeg::segment)
.def("getSeg", &GraphSeg::getSeg, py::return_value_policy::copy)
.def("getFilteredImage", &GraphSeg::getFilteredImage, py::return_value_policy::copy)
.def("getSupPixelGraph", &GraphSeg::getSupPixelGraph, py::return_value_policy::copy)
.def("getRegionNum", &GraphSeg::getRegionNum)
.def("getRegionSize", &GraphSeg::getRegionSize, py::return_value_policy::copy);
} | 25.951128 | 142 | 0.583804 | [
"shape",
"vector"
] |
bfa0c0b133adf3321545dbda1775af961c37c8ae | 5,798 | cpp | C++ | toolkits/graphical_models/deprecated/gibbs_sampling/image.cpp | RealM10/package | 3bcec9b677226ee0395e82e908f542aba0ecaad7 | [
"ECL-2.0",
"Apache-2.0"
] | 333 | 2016-07-29T19:22:07.000Z | 2022-03-30T02:40:34.000Z | toolkits/graphical_models/deprecated/gibbs_sampling/image.cpp | HybridGraph/GraphLab-PowerGraph | ba333c1cd82325ab2bfc6dd7ebb871b3fff64a94 | [
"ECL-2.0",
"Apache-2.0"
] | 17 | 2016-09-15T00:31:59.000Z | 2022-02-08T07:51:07.000Z | toolkits/graphical_models/deprecated/gibbs_sampling/image.cpp | HybridGraph/GraphLab-PowerGraph | ba333c1cd82325ab2bfc6dd7ebb871b3fff64a94 | [
"ECL-2.0",
"Apache-2.0"
] | 163 | 2016-07-29T19:22:11.000Z | 2022-03-07T07:15:24.000Z | /**
* Copyright (c) 2009 Carnegie Mellon University.
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an "AS
* IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*
*
*/
#include <cassert>
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <limits>
#include <cmath>
#include <boost/random.hpp>
#include <graphlab.hpp>
#include "image.hpp"
#include <graphlab/macros_def.hpp>
void image::save_vec(const char* filename) const {
std::ofstream os(filename);
ASSERT_TRUE(os.good());
for(size_t i = 0; i < pixels(); ++i) {
os << pixel(i) << "\n";
}
os.flush();
os.close();
}
double image::min() const {
return *std::min_element(data.begin(), data.end());
}
double image::max() const {
return *std::max_element(data.begin(), data.end());
}
void image::save(graphlab::oarchive &oarc) const {
oarc << _rows;
oarc << _cols;
oarc << data;
}
void image::load(graphlab::iarchive &iarc) {
iarc >> _rows;
iarc >> _cols;
iarc >> data;
}
/** Generate a normally distributed random number N(mu, sigma^2) */
// std::pair<double, double> randn(double mu = 0, double sigma = 1 );
// IMPLEMENTATION =============================================================>
void image::resize(size_t rows, size_t cols) {
_rows = rows;
_cols = cols;
data.resize(rows * cols, 0);
}
/** Get the vertex id of a pixel */
size_t image::vertid(size_t i, size_t j) const {
ASSERT_LT(i, _rows);
ASSERT_LT(j, _cols);
return i * _cols + j;
}
// static size_t image::vertid(size_t rows, size_t cols, size_t i, size_t j) {
// assert(i < rows);
// assert(j < cols);
// return i * cols + j;
// }
/** Get the vertex id of a pixel */
std::pair<size_t, size_t> image::loc(size_t vertexid) const {
ASSERT_LT(vertexid, _rows * _cols);
return std::make_pair( vertexid / _cols, vertexid % _cols);
}
void image::save(const char* filename) const {
std::ofstream os(filename);
os << "P2" << std::endl
<< _cols << " " << _rows << std::endl
<< 255 << std::endl;
// Compute min and max pixel intensities
double min = data[0]; double max = data[0];
for(size_t i = 0; i < _rows * _cols; ++i) {
min = std::min(min, data[i]);
max = std::max(max, data[i]);
}
// Save the image (rescaled)
for(size_t r = 0; r < _rows; ++r) {
for(size_t c = 0; c < _cols; c++) {
if(min != max) {
int color =
static_cast<int>(255.0 * (pixel(r,c) - min)/(max-min));
os << color;
} else { os << min; }
if(c != _cols-1) os << "\t";
}
os << std::endl;
}
os.flush();
os.close();
} // end of save
void image::paint_sunset(size_t states) {
const double center_r = rows() / 2.0;
const double center_c = cols() / 2.0;
const double max_radius = std::min(rows(), cols()) / 2.0;
// Fill out the image
for(size_t r = 0; r < rows(); ++r) {
for(size_t c = 0; c < cols(); ++c) {
double distance = sqrt((r-center_r)*(r-center_r) +
(c-center_c)*(c-center_c));
// If on top of image
if(r < rows() / 2) {
// Compute ring of sunset
size_t ring =
static_cast<size_t>(std::floor(std::min(1.0, distance/max_radius)
* (states - 1) ) );
pixel(r,c) = ring;
} else {
size_t blockx = r / 20;
size_t blocky = (c + 20 * sin(10.0*r/rows())) / 20;
size_t index = blockx + 2*blocky;
pixel(r,c) = index % states;
}
}
}
} // end of paint_beatiful_sunset
void image::paint_checkerboard(size_t states, size_t blocks) {
size_t block_size = std::min(rows(), cols() ) / blocks;
// Fill out the image
for(size_t r = 0; r < rows(); ++r) {
for(size_t c = 0; c < cols(); ++c) {
size_t blockx = r / block_size;
size_t blocky = c / block_size;
size_t index = blockx + blocky * block_size;
pixel(r,c) = index % states;
}
}
} // end of paint_beatiful_sunset
/** corrupt the image with gaussian noise */
void image::gaussian_corrupt(double sigma) {
// boost::mt19937 rng;
boost::lagged_fibonacci607 rng;
boost::normal_distribution<double> noise_model(0, sigma);
for(size_t i = 0; i < rows() * cols(); ) {
// Corrupt two pixels at a time.
pixel(i++) += noise_model(rng);
}
} // end of corrupt_image
/** flip_corrupt */
void image::flip_corrupt(size_t states, double prob_flip) {
boost::mt19937 rng;
boost::uniform_real<double> dist01;
for(size_t i = 0; i < rows() * cols(); ++i) {
double p = dist01(rng);
if(p < prob_flip) pixel(i) = rand() % states;
}
} // end of corrupt_image
// /** generate a normally distributed iid pair */
// std::pair<double, double> randn(double mu , double sigma ) {
// // Generate a N(0,1) from a Unif(0,1) using Box-Muller generator:
// double u1 = static_cast<double>(rand()) / RAND_MAX;
// double u2 = static_cast<double>(rand()) / RAND_MAX;
// double coeff = std::sqrt(-2.0 * std::log(u1));
// double n1 = coeff * std::cos(2.0 * M_PI * u2) ;
// double n2 = coeff * std::sin(2.0 * M_PI * u2) ;
// // Adjust for mean and variance
// n1 = sigma * n1 + mu;
// n2 = sigma * n2 + mu;
// return std::make_pair(n1, n2);
// } // end of randn
#include <graphlab/macros_undef.hpp>
| 25.318777 | 80 | 0.589859 | [
"vector"
] |
bfa0f94b5d4146680883fcad827ae2dfd9c4e3bb | 12,372 | cpp | C++ | exp/Lettvin_Repulsion/cpp/diffuse.cpp | LightStage-Aber/LightStage-Repo | 92f21b1b8a9f701cac3976a8db7034ecfefc58c7 | [
"Apache-2.0"
] | 10 | 2015-10-06T00:14:17.000Z | 2022-02-04T14:03:30.000Z | exp/Lettvin_Repulsion/cpp/diffuse.cpp | LightStage-Aber/LightStage-Repo | 92f21b1b8a9f701cac3976a8db7034ecfefc58c7 | [
"Apache-2.0"
] | 10 | 2017-05-05T11:10:19.000Z | 2019-06-04T15:30:24.000Z | exp/Lettvin_Repulsion/cpp/diffuse.cpp | LightStage-Aber/LightStage-Repo | 92f21b1b8a9f701cac3976a8db7034ecfefc58c7 | [
"Apache-2.0"
] | 2 | 2016-04-16T13:47:54.000Z | 2019-10-09T20:16:41.000Z | //******************************************************************************
// Diffuse.cpp Copyright(c) 2003 Jonathan D. Lettvin, All Rights Reserved.
//******************************************************************************
// Permission to use this code if and only if the first eight lines are first.
// This code is offered under the GPL.
// Please send improvements to the author: jdl@alum.mit.edu
// The User is responsible for errors.
//******************************************************************************
static char *usage_string=
"QUIT because \"%s\"\n"
"Usage: %s {Number} [{Jiggle} [{Rounds}]]\n"
" Number: count of points to distribute over unit sphere\n"
" Jiggle: lower limit of largest movement below which relaxation stops\n"
" Rounds: upper limit of relaxation steps above which relaxation stops\n"
"Fix one charged point at (1,0,0) on a unit sphere.\n"
"Randomly distribute additional charged points over unit sphere.\n"
"Prevent identical positioning.\n"
"Apply formula for charge repulsion to calculate movement vector.\n"
"After all movement vectors have been calculated, apply to charges.\n"
"Normalize resulting vectors to constrain movement to sphere.\n"
"Repeat until movement falls below limit, or rounds rises above limit."
"Output as a C static double array of coordinate triples."
;
//******************************************************************************
// Overview:
// Diffuse a number of points to an approximately stationary position using
// the standard physics formula for charge repulsion (inverse square law)
// over the surface of a sphere. For vertex counts equalling platonic solids,
// the result will be a distribution approximating that platonic solid.
// Otherwise, distributions are sufficiently random to make
// every possible great circle cross the same number of edges,
// give or take a small variation.
// Use the first point as an anchor at (1,0,0) then randomly distribute points.
// Precautions are taken to avoid identical points (a zerodivide, or "pole").
// The expected area of an inscribed circle around any point should converge to
// the area of the sphere divided by the number of points, therefore the radius
// of said circle should be approximately linear with 1/sqrt(N). This program
// arbitrarily uses the default minimum incremental movement value .03/sqrt(N).
//******************************************************************************
// OVERALL SEQUENCE OF OPERATION:
// ----
// main: Sequence of operations:
// 1) gather, constrain, and default command-line arguments
// 2) construct "points" object (vector of spherically constrained coordinates)
// 3) output the coordinates calculated during construction
// 4) quit
// ----
// 2: sequence of operations
// a) Initialize random number generator
// b) construct vector of coordinates fixing the first and randomizing others
// c) relax the vector (cause point-charge forces to push points apart)
// d) calculate nearest neighbor for all points and record that minimum radius
// ----
// 2b: sequence of operations
// e) push (1,0,0) on vector
// f) push random normalized coordinates on vector, pop if another is identical
// g) push slot for per-coordinate minimum radius
// ----
// 2c: sequence of operations
// h) for every point get inverse-square increment from all other points
// i) zero the force on the (1,0,0) point to keep anchor
// j) after acquiring all increments, sum and normalize increments, and apply
// k) repeat until maximum movement falls below a minimum
// ----
// 2be and 2bf: sequence of operations
// l) construct either the (1,0,0) point or a random point
// m) normalize to place the point on the unit sphere
// ----
// 2ch: sequence of operations
// n) calculate distance between indexed point and a specific other point
// o) take inverse square of distance
// p) add directly to increment coordinates
// ----
// 2cj: sequence of operations
// q) keep a copy of the starting coordinates for the point
// r) add increment to move point, and normalize it back onto the sphere
// s) calculate distance to starting coordinates and
// t) remember largest movement on surface of sphere
// ----
// 3: sequence of operations
// u) output all point coordinates as a C style static double array
//******************************************************************************
#include <iostream> // sync_with_stdio
#include <cstdio> // printf
#include <cstdlib> // I believe sqrt is in here
#include <ctime> // Used to salt the random number generator
#include <cmath> // Various mathematical needs
#include <vector> // Used to contain many points
#include <valarray> // Used to implement a true XYZ vector
//******************************************************************************
using namespace std; // Necessary to gain access to many C++ names
//******************************************************************************
typedef valarray<double>coordinates; // To simplify declarations
// A global function to document how to use this program.
void usage(char *program_name,char *quit_reason) {
fprintf(stderr,usage_string,quit_reason,program_name);
exit(1);
}
//******************************************************************************
class XYZ { // This class contains operations for placing and moving points
private:
double change_magnitude;
coordinates xyz; // This holds the coordinates of the point.
coordinates dxyz; // This holds the summed force vectors from other points
inline double random() { return(double((rand()%1000)-500)); } // ordinates
inline double square(const double& n) { return(n*n); }
inline coordinates square(const coordinates& n) { return(n*n); }
inline double inverse(const double& n) { return(1.0/n); }
XYZ& inverse_square() { xyz*=inverse(square(magnitude())); return *this; }
inline double magnitude() { return(sqrt((xyz*xyz).sum())); }
void normalize() { xyz/=magnitude(); } // unit vector
public:
XYZ(): xyz(3), dxyz(3) {
xyz[0]=random(); xyz[1]=random(); xyz[2]=random(); normalize();
}
XYZ(const double& x,const double& y,const double& z) : xyz(3), dxyz(3) {
xyz[0]=x; xyz[1]=y; xyz[2]=z;
}
XYZ(const coordinates& p) : xyz(3), dxyz(3) {
xyz=p;
}
~XYZ() { }
coordinates& array() { return xyz; }
void zero_force() { dxyz=0.0; }
double change() { return(change_magnitude); }
double magnitude(XYZ& b) { // Return length of vector. (not const)
return(sqrt( square(b.array()-xyz).sum() ));
}
void sum_force(XYZ& b) { // Cause force from each point to sum. (not const)
dxyz+=(XYZ(b.array()-xyz).inverse_square().array()); // Calculate and add
}
void move_over_sphere() { // Cause point to move due to force
coordinates before=xyz; // Save previous position
xyz-=dxyz; // Follow movement vector
normalize(); // Project back to sphere
before-=xyz; // Calculate traversal
change_magnitude=sqrt((before*before).sum()); // Record largest
}
void report(const double& d) {
printf(" { %+1.3e,%+1.3e,%+1.3e,%+1.3e }",xyz[0],xyz[1],xyz[2],d);
}
};
//******************************************************************************
class points { // This class organizes expression of relations between points
private:
const size_t N; // Number of point charges on surface of sphere
const size_t R; // Number of rounds after which to stop
const double L; // Threshold of movement below which to stop
char *S; // Name of this vertex set
size_t rounds; // Index of rounds processed
vector<XYZ>V; // List of point charges
vector<double>H; // List of minimum distances
double maximum_change; // The distance traversed by the most moved point
double minimum_radius; // The radius of the smallest circle
time_t T0; // Timing values
void relax() { // Cause all points to sum forces from all other points
size_t i, j;
rounds=0;
do {
maximum_change=0.0;
for(i=1;i<N;i++) { // for all points other than the fixed point
V[i].zero_force(); // Initialize force vector
for(j= 0;j<i;j++) V[i].sum_force(V[j]); // Get contributing forces
// Skip i==j
for(j=i+1;j<N;j++) V[i].sum_force(V[j]); // Get contributing forces
}
for(i=1;i<N;i++) { // React to summed forces except for the fixed point
V[i].move_over_sphere();
if(V[i].change()>maximum_change) maximum_change=V[i].change();
}
++rounds;
} while(maximum_change>L); //&&++rounds<R); // Until small or too much movement
}
public:
points(char *s,const size_t& n,const double& l,const size_t& r) :
N(n), L(l), R(r)
{
S=s;
T0=time(0L); // Get the current time
srand(T0); // Salt the random number generator.
V.push_back(XYZ(1.0,0.0,0.0)); // Create Anchored first point V[0] (1,0,0)
H.push_back(2.0);
while(V.size()<N) { // For all other points, until we have enough
V.push_back(XYZ()); // Create randomized position
H.push_back(2.0);
coordinates& last=V.back().array(); // Remember this position
for(size_t i=V.size()-1;i--;) { // And check to see if it is occupied
coordinates& temp=V[i].array();
if(temp[0]==last[0]&&temp[1]==last[1]&&temp[2]==last[2]) {
V.pop_back(); // Remove the position if it is already occupied
break;
}
}
}
relax(); // After vector construction, start the relaxation process
size_t i, j;
minimum_radius=1.0; // On a unit sphere, the maximum circle radius is 1.0
for(i=0;i<V.size();i++) { // Discover the minimum distance between points.
for(j=0;j<V.size();j++) {
if(j==i) continue;
double rtemp=V[i].magnitude(V[j])/2.0;
if(rtemp<minimum_radius) minimum_radius=rtemp; // Record when smaller.
if(rtemp<H[i]) H[i]=rtemp;
}
}
}
~points() {}
coordinates& operator[](const size_t& i) { // Caller access to positions
return(V[i].array());
}
void report() { // Output run statistics and positions of all points
printf(
"/* Rounds =%d/%d */\n"
"/* Jiggle dV=%+1.2e/%+1.2e */\n"
"/* minimum r=%+1.2e */\n"
"/* elapsed time<=%ld seconds. */\n"
"static size_t points_%s=%d;\n"
"static double vertex_%s[%d][4] = {\n"
"/*{ X , Y , Z , Rmin } */\n"
,
rounds,R,maximum_change,L,minimum_radius,1L+time(0L)-T0,S,N,S,N);
V[0].report(H[0]);
for(size_t i=1;i<N;i++) { printf(",\n"); V[i].report(H[i]); }
printf("\n};\n");
}
};
//******************************************************************************
int main(int argc,char **argv) {
ios::sync_with_stdio(true); // Not needed because iostream is not used.
size_t Number=0; // Cause point count to have a failing value.
size_t Rounds=0; // Stop relaxation after this number of rounds.
double Jiggle; // Stop relaxation when movement drops below.
if(argc<2||argc>4)
usage(argv[0],"Bad argument count");
if((Number=atoi(argv[1]))<2)
usage(argv[0],"Constrain Number>1");
Jiggle=0.03/sqrt(double(Number)); // default Jiggle=.03 of expected radius
if(argc>=3&&((Jiggle=atof(argv[2]))<=0||Jiggle>(0.03/sqrt(double(Number)))))
usage(argv[0],"Constrain 0<Jiggle<0.03/sqrt(Number)");
//if(argc==4&&(Rounds=atoi(argv[3]))<50||Rounds>10000)
// usage(argv[0],"Constrain 50<=Rounds<=10000");
points P("default",Number,Jiggle,Rounds);
// P can now be addressed for specific XYZ values for scaling and reporting
// For instance P[0] should return a valarray& of three elements (1,0,0)
// In this program, the array is simply output as a C static double array
P.report();
return(0);
}
//******************************************************************************
// End of file
//******************************************************************************
| 47.76834 | 85 | 0.589638 | [
"object",
"vector",
"solid"
] |
bfa37c62fa517fba7557963faf964703bdd3614f | 2,239 | cc | C++ | release/src/router/aria2/test/UTMetadataRequestFactoryTest.cc | Clarkmania/ripetomato | 5eda5521468cb9cb7156ae6750cf8229b776d10e | [
"FSFAP"
] | 3 | 2019-01-13T09:19:57.000Z | 2022-01-15T12:16:14.000Z | release/src/router/aria2/test/UTMetadataRequestFactoryTest.cc | Clarkmania/ripetomato | 5eda5521468cb9cb7156ae6750cf8229b776d10e | [
"FSFAP"
] | 1 | 2020-07-28T08:22:45.000Z | 2020-07-28T08:22:45.000Z | release/src/router/aria2/test/UTMetadataRequestFactoryTest.cc | Clarkmania/ripetomato | 5eda5521468cb9cb7156ae6750cf8229b776d10e | [
"FSFAP"
] | 1 | 2020-03-06T21:17:24.000Z | 2020-03-06T21:17:24.000Z | #include "UTMetadataRequestFactory.h"
#include <vector>
#include <deque>
#include <cppunit/extensions/HelperMacros.h>
#include "MockPieceStorage.h"
#include "DownloadContext.h"
#include "Peer.h"
#include "BtMessage.h"
#include "extension_message_test_helper.h"
#include "BtHandshakeMessage.h"
#include "ExtensionMessage.h"
#include "UTMetadataRequestTracker.h"
namespace aria2 {
class UTMetadataRequestFactoryTest:public CppUnit::TestFixture {
CPPUNIT_TEST_SUITE(UTMetadataRequestFactoryTest);
CPPUNIT_TEST(testCreate);
CPPUNIT_TEST_SUITE_END();
public:
void testCreate();
class MockPieceStorage2:public MockPieceStorage {
public:
std::deque<size_t> missingIndexes;
virtual SharedHandle<Piece> getMissingPiece
(const SharedHandle<Peer>& peer,
const std::vector<size_t>& exlucdedIndexes,
cuid_t cuid)
{
if(missingIndexes.empty()) {
return SharedHandle<Piece>();
} else {
size_t index = missingIndexes.front();
missingIndexes.pop_front();
return SharedHandle<Piece>(new Piece(index, 0));
}
}
};
};
CPPUNIT_TEST_SUITE_REGISTRATION(UTMetadataRequestFactoryTest);
void UTMetadataRequestFactoryTest::testCreate()
{
UTMetadataRequestFactory factory;
SharedHandle<DownloadContext> dctx
(new DownloadContext(METADATA_PIECE_SIZE, METADATA_PIECE_SIZE*2));
factory.setDownloadContext(dctx);
SharedHandle<MockPieceStorage2> ps(new MockPieceStorage2());
ps->missingIndexes.push_back(0);
ps->missingIndexes.push_back(1);
SharedHandle<WrapExtBtMessageFactory> messageFactory
(new WrapExtBtMessageFactory());
factory.setBtMessageFactory(messageFactory.get());
SharedHandle<Peer> peer(new Peer("peer", 6880));
peer->allocateSessionResource(0, 0);
factory.setPeer(peer);
SharedHandle<UTMetadataRequestTracker> tracker
(new UTMetadataRequestTracker());
factory.setUTMetadataRequestTracker(tracker.get());
std::vector<SharedHandle<BtMessage> > msgs;
factory.create(msgs, 1, ps);
CPPUNIT_ASSERT_EQUAL((size_t)1, msgs.size());
factory.create(msgs, 1, ps);
CPPUNIT_ASSERT_EQUAL((size_t)2, msgs.size());
factory.create(msgs, 1, ps);
CPPUNIT_ASSERT_EQUAL((size_t)2, msgs.size());
}
} // namespace aria2
| 27.304878 | 70 | 0.747655 | [
"vector"
] |
bfb1c9eb76b4ec5bbd2a49fcb2b2b95b369b5580 | 1,218 | cpp | C++ | LeetCode/889-1.cpp | LauZyHou/- | 66c047fe68409c73a077eae561cf82b081cf8e45 | [
"MIT"
] | 7 | 2019-02-25T13:15:00.000Z | 2021-12-21T22:08:39.000Z | LeetCode/889-1.cpp | LauZyHou/- | 66c047fe68409c73a077eae561cf82b081cf8e45 | [
"MIT"
] | null | null | null | LeetCode/889-1.cpp | LauZyHou/- | 66c047fe68409c73a077eae561cf82b081cf8e45 | [
"MIT"
] | 1 | 2019-04-03T06:12:46.000Z | 2019-04-03T06:12:46.000Z | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* traceback(vector<int>& pre,int e1,int e2,
vector<int>& rpost,int t1,int t2) {
if(e1>e2)
return nullptr;
TreeNode* t = new TreeNode(pre[e1]);//pre[e1]==rpost[t1]
if(e1==e2)
return t;
else if(pre[e1+1]==rpost[t1+1]) {//说明有一边是null,不妨都放到左子树
t->left = traceback(pre,e1+1,e2,rpost,t1+1,t2);
} else {
//还是找左右子树分割点
//在"中左右"中找"右"的开始点
int rBgnZZY=e1+2;
for(;rBgnZZY<=e2;rBgnZZY++)
if(pre[rBgnZZY]==rpost[t1+1])
break;
//在"中右左"中找"左"的开始点
int lBgnZYZ=t1+2;
for(;lBgnZYZ<=t2;lBgnZYZ++)
if(rpost[lBgnZYZ]==pre[e1+1])
break;
t->left = traceback(pre,e1+1,rBgnZZY-1,rpost,lBgnZYZ,t2);
t->right = traceback(pre,rBgnZZY,e2,rpost,t1+1,lBgnZYZ-1);
}
return t;
}
TreeNode* constructFromPrePost(vector<int>& pre, vector<int>& post) {
int elen = pre.size();
int tlen = post.size();
if(elen!=tlen || elen==0)
return nullptr;
reverse(post.begin(),post.end());
return traceback(pre,0,elen-1,post,0,tlen-1);
}
}; | 25.914894 | 73 | 0.604269 | [
"vector"
] |
bfb3bb6dc03b656c564583c6517304f6266dd9d7 | 40,625 | cpp | C++ | VSBin/make_steering.cpp | sfegan/ChiLA | 916bdd95348c2df2ecc736511d5f5b2bfb4a831e | [
"BSD-3-Clause"
] | 1 | 2018-04-17T14:03:36.000Z | 2018-04-17T14:03:36.000Z | VSBin/make_steering.cpp | sfegan/ChiLA | 916bdd95348c2df2ecc736511d5f5b2bfb4a831e | [
"BSD-3-Clause"
] | null | null | null | VSBin/make_steering.cpp | sfegan/ChiLA | 916bdd95348c2df2ecc736511d5f5b2bfb4a831e | [
"BSD-3-Clause"
] | null | null | null | //-*-mode:c++; mode:font-lock;-*-
/*! \file make_steering.cpp
Make the steering file for CORSIKA
\author Stephen Fegan \n
UCLA \n
sfegan@astro.ucla.edu \n
\version 1.0
\date 03/02/2005
*/
#ifndef NO_CEFFIC
#ifndef CEFFIC
#define CEFFIC
#endif
#endif
#ifndef NO_QGSJET
#ifndef QGSJET
#define QGSJET
#endif
#endif
#ifndef NO_FLUKA
#ifndef FLUKA
#define FLUKA
#endif
#endif
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <vector>
#include <cstdlib>
#include <cmath>
#include <limits>
#include <sys/time.h>
#include <unistd.h>
#include <VSOptions.hpp>
#include <VSDataConverter.hpp>
#include <xytohex.h>
#include <xytosquare.h>
#include <VSDBFactory.hpp>
#include <VSDBParameterTable.hpp>
#include <VSSimDB.hpp>
#include <VSOTelescopeArray.hpp>
#include <VSTargeting.hpp>
#include <VSSimDBCORSIKADatasets.hpp>
#include "make_steering_help.h"
using namespace VERITAS;
struct DataFile
{
const char* filename;
const char* data;
unsigned data_len;
};
void writeCORSIKADataFile(bool test_only, const DataFile& df)
{
if(!test_only)
{
FILE* fp = fopen(df.filename,"w");
fwrite(df.data, 1, df.data_len, fp);
fclose(fp);
}
}
void writeDataOrDie(bool test_only,
const std::map<std::string, const DataFile*>& datafiles,
const std::string& choice,
const std::string& blurb)
{
std::map<std::string, const DataFile*>::const_iterator idata =
datafiles.find(choice);
if(idata == datafiles.end())
{
std::cerr << "Unknown " << blurb << " choice: \"" << choice << '"'
<< std::endl
<< "Valid choices are:";
for(idata=datafiles.begin(); idata!=datafiles.end(); idata++)
std::cerr << " \"" << idata->first << '"';
std::cerr << std::endl;
exit(EXIT_FAILURE);
}
else if(idata->second)
{
writeCORSIKADataFile(test_only,*idata->second);
}
}
void writeAllCORSIKADataFiles(bool test_only,
const std::string& choice_modtran,
const std::string& choice_qeff,
const std::string& choice_atmo,
const std::string& choice_mirror)
{
#include "bern_atmprof1_dat.h"
#include "bern_atmprof2_dat.h"
#include "bern_atmprof3_dat.h"
#include "bern_atmprof4_dat.h"
#include "bern_atmprof5_dat.h"
#include "bern_atmprof6_dat.h"
#include "bern_atmprof9_dat.h"
std::map<std::string, const DataFile*> Modtran;
Modtran["none"] = 0;
Modtran["corsika1"] = &BERN_ATMPROF1_DAT;
Modtran["corsika2"] = &BERN_ATMPROF2_DAT;
Modtran["corsika3"] = &BERN_ATMPROF3_DAT;
Modtran["corsika4"] = &BERN_ATMPROF4_DAT;
Modtran["corsika5"] = &BERN_ATMPROF5_DAT;
Modtran["corsika6"] = &BERN_ATMPROF6_DAT;
Modtran["corsika9"] = &BERN_ATMPROF9_DAT;
writeDataOrDie(test_only,Modtran,choice_modtran,"paramterized atmosphere");
#ifdef CEFFIC
#include "cors_quanteff_dat.h"
std::map<std::string, const DataFile*> Qeff;
Qeff["none"] = 0;
Qeff["corsika"] = &CORS_QUANTEFF_DAT;
writeDataOrDie(test_only,Qeff,choice_qeff,"quantum efficiency");
#include "cors_atmabs_dat.h"
std::map<std::string, const DataFile*> Atmo;
Atmo["none"] = 0;
Atmo["corsika"] = &CORS_ATMABS_DAT;
writeDataOrDie(test_only,Atmo,choice_atmo,"atmospheric absorption");
#include "cors_mirreff_corsika_dat.h"
#include "cors_mirreff_falcone_dat.h"
#include "cors_mirreff_falcone_squared_dat.h"
std::map<std::string, const DataFile*> Mirror;
Mirror["none"] = 0;
Mirror["corsika"] = &CORS_MIRREFF_CORSIKA_DAT;
Mirror["double"] = &CORS_MIRREFF_FALCONE_SQUARED_DAT;
Mirror["falcone"] = &CORS_MIRREFF_FALCONE_DAT;
writeDataOrDie(test_only,Mirror,choice_mirror,"mirror reflectivity");
#else
choice_qeff.empty(); // so that we don't get an unused argument warning.
choice_atmo.empty(); // so that we don't get an unused argument warning.
choice_mirror.empty(); // so that we don't get an unused argument warning.
#endif
#include "cors_nucnuccs.h"
#include "cors_egsdat5_005.h"
#include "cors_egsdat5_015.h"
#include "cors_egsdat5_025.h"
#include "cors_egsdat5_040.h"
#include "cors_egsdat5_100.h"
#include "cors_egsdat5_300.h"
writeCORSIKADataFile(test_only,CORS_NUCNUCCS);
writeCORSIKADataFile(test_only,CORS_EGSDAT5_005);
writeCORSIKADataFile(test_only,CORS_EGSDAT5_015);
writeCORSIKADataFile(test_only,CORS_EGSDAT5_025);
writeCORSIKADataFile(test_only,CORS_EGSDAT5_040);
writeCORSIKADataFile(test_only,CORS_EGSDAT5_100);
writeCORSIKADataFile(test_only,CORS_EGSDAT5_300);
#ifdef QGSJET
#include "cors_qgsdat.h"
#include "cors_sectnu.h"
writeCORSIKADataFile(test_only,CORS_QGSDAT);
writeCORSIKADataFile(test_only,CORS_SECTNU);
#endif
#ifdef DPMJET
#include "cors_glaubtar_dat.h"
#include "cors_nuclear_bin.h"
writeCORSIKADataFile(test_only,CORS_GLAUBTAR_DAT);
writeCORSIKADataFile(test_only,CORS_NUCLEAR_BIN);
#endif
#ifdef VENUS
#include "cors_venusdat.h"
writeCORSIKADataFile(test_only,CORS_VENUSDAT);
#endif
#ifdef FLUKA
#include "fluka_elasct_bin.h"
#include "fluka_nuclear_bin.h"
#include "fluka_sigmapi_bin.h"
writeCORSIKADataFile(test_only,FLUKA_ELASCT_BIN);
writeCORSIKADataFile(test_only,FLUKA_NUCLEAR_BIN);
writeCORSIKADataFile(test_only,FLUKA_SIGMAPI_BIN);
#endif
}
void write_card_option(std::ostream& stream, const std::string& opt)
{
stream << std::setw(10) << std::left << opt << std::endl;
}
template<typename T> void write_card_option(std::ostream& stream,
const std::string& opt,
const T& value)
{
stream << std::setw(10) << std::left << opt << ' '
<< VSDataConverter::toString(value) << std::endl;
}
template<> void write_card_option<>(std::ostream& stream,
const std::string& opt,
const bool& value)
{
stream << std::setw(10) << std::left << opt << ' '
<< (value?'T':'F') << std::endl;
}
template<> void write_card_option<>(std::ostream& stream,
const std::string& opt,
const std::string& value)
{
stream << std::setw(10) << std::left << opt << ' ' << '\''
<< VSDataConverter::toString(value) << '\'' << std::endl;
}
struct CSCAT_Struct
{
unsigned event_use;
float sampling_radius;
};
template<> void write_card_option<>(std::ostream& stream,
const std::string& opt,
const CSCAT_Struct& value)
{
stream << std::setw(10) << std::left << opt << ' '
<< VSDataConverter::toString(unsigned(value.event_use)) << ' '
<< VSDataConverter::toString(value.sampling_radius) << ' '
<< VSDataConverter::toString((float)0.0) << std::endl;
}
#ifdef QGSJET
struct QGSJET_Struct
{
unsigned debug;
};
template<> void write_card_option<>(std::ostream& stream,
const std::string& opt,
const QGSJET_Struct& value)
{
stream << std::setw(10) << std::left << opt << ' '
<< 'T' << ' ' << value.debug << std::endl;
}
#endif
struct Modtran_Struct
{
unsigned atmosphere;
bool refraction;
};
template<> void write_card_option<>(std::ostream& stream,
const std::string& opt,
const Modtran_Struct& value)
{
stream << std::setw(10) << std::left << opt << ' '
<< VSDataConverter::toString(value.atmosphere) << ' '
<< (value.refraction?'T':'F') << std::endl;
}
template<typename T> void write_card_option(std::ostream& stream,
const std::string& opt,
const std::vector<T>& value)
{
stream << std::setw(10) << std::left << opt;
for(typename std::vector<T>::const_iterator i=value.begin();
i!=value.end(); i++)
stream << ' ' << VSDataConverter::toString(*i);
stream << std::endl;
}
template<> void write_card_option<>(std::ostream& stream,
const std::string& opt,
const std::vector<bool>& value)
{
stream << std::setw(10) << std::left << opt;
for(std::vector<bool>::const_iterator i=value.begin(); i!=value.end(); i++)
stream << ' ' << ((*i)?'T':'F');
stream << std::endl;
}
template<> void write_card_option<>(std::ostream& stream,
const std::string& opt,
const std::vector<std::string>& value)
{
stream << std::setw(10) << std::left << opt;
for(std::vector<std::string>::const_iterator i=value.begin(); i
!=value.end(); i++)
stream << ' ' << '\'' << VSDataConverter::toString(*i) << '\'';
stream << std::endl;
}
#define NUMOF(x) (sizeof(x)/sizeof(*(x)))
int main(int argc, char** argv)
{
std::string progname(*argv);
VSOptions options(argc, argv, true);
bool usage_error = false;
if(options.find("h")!=VSOptions::FS_NOT_FOUND)usage_error=true;
if(options.find("help")!=VSOptions::FS_NOT_FOUND)usage_error=true;
// --------------------------------------------------------------------------
// DATABASE FACTORY CONFIGURATION
// --------------------------------------------------------------------------
VSDBFactory::configure(&options);
// --------------------------------------------------------------------------
// SOME INITIALIZATION OPTIONS
// --------------------------------------------------------------------------
bool ctl_init = false;
bool ctl_load = true;
bool ctl_save = false;
if(options.find("INIT",HELP_INIT)!=VSOptions::FS_NOT_FOUND)ctl_init=true;
if(options.find("no_load",HELP_NO_LOAD)!=VSOptions::FS_NOT_FOUND)
ctl_load=false;
if(options.find("SAVE",HELP_SAVE)!=VSOptions::FS_NOT_FOUND)ctl_save=true;
// --------------------------------------------------------------------------
// CHECK FOR OPTION TO USE DATABASE
// --------------------------------------------------------------------------
bool ctl_db_use = false;
std::string ctl_db_name = "";
bool ctl_table_use = false;
std::string ctl_table_name = "";
switch(options.findWithValue("db",ctl_db_name,HELP_DB))
{
case VSOptions::FS_FOUND:
ctl_db_use = true;
break;
case VSOptions::FS_NOT_FOUND:
ctl_db_use = false;
break;
case VSOptions::FS_FOUND_BUT_WITHOUT_VALUE:
std::cerr << progname
<< ": database option used but no database specified"
<< std::endl;
usage_error = true;
break;
case VSOptions::FS_FOUND_BUT_COULD_NOT_CONVERT_VALUE:
case VSOptions::FS_FOUND_WITH_UNDESIRED_VALUE:
default:
// Should not happen... we can always convert to string and we
// explicitly asked for a value
assert(0);
};
switch(options.findWithValue("table",ctl_table_name,HELP_TABLE))
{
case VSOptions::FS_FOUND:
ctl_table_use = true;
break;
case VSOptions::FS_NOT_FOUND:
ctl_table_use = false;
break;
case VSOptions::FS_FOUND_BUT_WITHOUT_VALUE:
std::cerr << progname << ": table option used but no table specified"
<< std::endl;
usage_error = true;
break;
case VSOptions::FS_FOUND_BUT_COULD_NOT_CONVERT_VALUE:
case VSOptions::FS_FOUND_WITH_UNDESIRED_VALUE:
default:
// Should not happen... we can always convert to string and we
// explicitly asked for a value
assert(0);
};
// --------------------------------------------------------------------------
// CONNECT TO DATABASE
// --------------------------------------------------------------------------
VSDatabase* db(0);
VSDBParameterTable* db_param(0);
if(ctl_db_use)
{
db = VSDBFactory::getInstance()->createVSDB();
if(db->useDatabase(ctl_db_name) < 0)
{
std::cerr << progname << ": could not connect to database "
<< ctl_db_name << std::endl;
return EXIT_FAILURE;
}
db_param = new VSDBParameterTable(db);
}
VSSimDB* db_sim(0);
if(ctl_table_use)
{
db_sim = new VSSimDB(db);
}
// --------------------------------------------------------------------------
// LOAD COMMAND LINE OPTIONS FROM DATABASE
// --------------------------------------------------------------------------
if((ctl_db_use)&&(ctl_load))
{
VSDBParameterSet parameters;
db_param->retrieveParameterSet("MakeSteering",parameters);
for(VSDBParameterSet::const_iterator iopt = parameters.begin();
iopt != parameters.end(); iopt++)
{
if(iopt->second.empty())options.addOption(iopt->first);
else options.addOptionWithValue(iopt->first,iopt->second);
}
}
// --------------------------------------------------------------------------
// SET UP SOME OF THE DEFAULTS FOR THE STEERING FILE
// --------------------------------------------------------------------------
char init_host_buffer[256];
gethostname(init_host_buffer, NUMOF(init_host_buffer));
for(unsigned i=0; i<NUMOF(init_host_buffer); i++)
if((init_host_buffer[i]=='.')||(i==255))init_host_buffer[i]='\0';
struct timeval init_tv;
gettimeofday(&init_tv,0);
srandom(init_tv.tv_usec^init_tv.tv_sec);
for(unsigned i=0;i<100000;i++)random();
unsigned init_seed1 = random();
unsigned init_seed2 = random();
unsigned init_seed3 = random();
unsigned init_seed4 = random();
while((init_seed1>900000000)||(init_seed1<1))init_seed1 = random();
while((init_seed2>900000000)||(init_seed2<1))init_seed2 = random();
while((init_seed3>900000000)||(init_seed3<1))init_seed3 = random();
while((init_seed4>900000000)||(init_seed4<1))init_seed4 = random();
char init_user_buffer[256];
if(getlogin() == NULL)
sprintf(init_user_buffer,"UID_%d",getuid());
else
strcpy(init_user_buffer,getlogin());
// --------------------------------------------------------------------------
// DEFINE ALL VARIABLES TO HOLD STEERING FILE OPTIONS
// --------------------------------------------------------------------------
unsigned cor_debug = 0;
bool cor_no_qgs = false;
bool cor_no_ceffic = false;
bool cor_no_fluka = false;
bool cor_no_modtran = false;
std::string run_hostname = init_host_buffer;
std::string run_username = init_user_buffer;
unsigned run_seed1 = init_seed1;
unsigned run_seed2 = init_seed2;
unsigned run_seed3 = init_seed3;
unsigned run_seed4 = init_seed4;
unsigned run_runno = 1;
unsigned run_eventno = 1;
unsigned run_num_shower = 100;
uint32_t tel_optics_id = 0;
unsigned tel_rings = 0;
float tel_spacing = 80.0;
float tel_elevation = 3500.0;
float tel_aperture = 7.0;
float tel_max_dist = std::numeric_limits<float>::infinity();
std::string tel_layout = "hex";
unsigned pri_species = 1;
float pri_zenith_lo = 20.0;
float pri_zenith_hi = 20.0;
float pri_azimuth_lo = 0.0;
float pri_azimuth_hi = 360.0;
float pri_viewcone_lo = 0.0;
float pri_viewcone_hi = 0.0;
float pri_sampling_radius = 0.0;
float pri_energy = 100.0;
float pri_start_depth = 0.0;
unsigned sim_atmosphere = 6;
std::string sim_modtran_data = "corsika6";
float sim_transition_energy = 80.0;
float sim_bx = 25.2;
float sim_bz = 40.83;
float sim_elec_mul_scat_fac = 1.0;
#ifdef CORSIKA_THINNING
float sim_thinning_energy = 0.01;
#endif
float sim_cutoff_hadron = 0.10;
float sim_cutoff_muon = 0.30;
float sim_cutoff_electron = 0.020;
float sim_cutoff_gamma = 0.020;
unsigned cer_event_use = 1;
float cer_lambda_lo = 180.0;
float cer_lambda_hi = 700.0;
unsigned cer_bunch = 1;
bool cer_qeff = true;
bool cer_atmo = true;
bool cer_mirror = true;
std::string cer_choice_qeff = "corsika";
std::string cer_choice_atmo = "corsika";
std::string cer_choice_mirror = "falcone";
unsigned out_max_event_print = 0;
float out_min_print_energy = 0.0;
std::string out_particle_file = "corsika_particle_NNNNN.dat";
bool out_particle_enable = false;
bool out_table_enable = false;
std::string out_cerenkov_file = "corsika_cerenkov_NNNNN.dat";
bool iact_no_impact_corr = false;
#if 0
int iact_max_print_tel = 10;
int iact_max_print_evt = 100;
int iact_skip_print = 1;
int iact_skip_print2 = 100;
int iact_skip_offset2 = 1;
int iact_max_int_bunches = 1000000;
int iact_io_buffer = 200000000;
#endif
// --------------------------------------------------------------------------
// PARSE COMMAND LINE OPTIONS AND SET VARIABLES
// --------------------------------------------------------------------------
// CORSIKA OPTIONS
options.findWithValue("debug", cor_debug, HELP_DEBUG);
if(options.find("no_qgs", HELP_NO_QGS)!=VSOptions::FS_NOT_FOUND)
cor_no_qgs = true;
if(options.find("no_fluka", HELP_NO_FLUKA)!=VSOptions::FS_NOT_FOUND)
cor_no_fluka = true;
if(options.find("no_ceffic", HELP_NO_CEFFIC)!=VSOptions::FS_NOT_FOUND)
cor_no_ceffic = true;
if(options.find("no_modtran", HELP_NO_MODTRAN)!=VSOptions::FS_NOT_FOUND)
cor_no_modtran = true, sim_atmosphere=1, sim_modtran_data="none";
// RUN OPTIONS
options.findWithValue("host",run_hostname,HELP_HOST);
options.findWithValue("user",run_username,HELP_USER);
options.findWithValue("seed1",run_seed1,HELP_SEED1);
options.findWithValue("seed2",run_seed2,HELP_SEED2);
options.findWithValue("seed3",run_seed3,HELP_SEED3);
options.findWithValue("seed4",run_seed4,HELP_SEED4);
options.findWithValue("runno",run_runno,HELP_RUNNO);
options.findWithValue("eventno",run_eventno,HELP_EVENTNO);
options.findWithValue("n",run_num_shower,HELP_N);
// TELESCOPE (OPTICS) OPTIONS
options.findWithValue("tel_optics_id",tel_optics_id,HELP_TEL_OPTICS_ID);
options.findWithValue("tel_rings",tel_rings,HELP_TEL_RINGS);
options.findWithValue("tel_spacing",tel_spacing,HELP_TEL_SPACING);
options.findWithValue("tel_elevation",tel_elevation,HELP_TEL_ELEVATION);
options.findWithValue("tel_aperture",tel_aperture,HELP_TEL_APERTURE);
options.findWithValue("tel_max_dist",tel_max_dist,HELP_TEL_MAX_DIST);
options.findWithValue("tel_layout",tel_layout,HELP_TEL_LAYOUT);
pri_sampling_radius = tel_spacing/sqrt(3.0)*1.01;
if(tel_layout == "square")
pri_sampling_radius = tel_spacing/sqrt(2.0)*1.01;
// PRIMARY OPTIONS
#define NUCLEUS(A,Z) ((A)*100+(Z))
if(options.find("gamma",HELP_GAMMA)!=VSOptions::FS_NOT_FOUND)
pri_species=1;
if(options.find("proton",HELP_PROTON)!=VSOptions::FS_NOT_FOUND)
pri_species=14;
if(options.find("electron",HELP_ELECTRON)!=VSOptions::FS_NOT_FOUND)
pri_species=3;
if(options.find("muon",HELP_MUON)!=VSOptions::FS_NOT_FOUND)
pri_species=6;
if(options.find("helium",HELP_HELIUM)!=VSOptions::FS_NOT_FOUND)
pri_species=NUCLEUS(4,2);
if(options.find("iron",HELP_IRON)!=VSOptions::FS_NOT_FOUND)
pri_species=NUCLEUS(56,26);
options.findWithValue("primary",pri_species,HELP_PRIMARY);
if(options.findWithValue("zenith",pri_zenith_lo,HELP_ZENITH)
!=VSOptions::FS_NOT_FOUND)pri_zenith_hi=pri_zenith_lo;
options.findWithValue("zenith_lo",pri_zenith_lo,HELP_ZENITH_LO);
options.findWithValue("zenith_hi",pri_zenith_hi,HELP_ZENITH_HI);
if(options.findWithValue("azimuth",pri_azimuth_lo,HELP_AZIMUTH)
!=VSOptions::FS_NOT_FOUND)
pri_azimuth_hi=pri_azimuth_lo;
options.findWithValue("azimuth_lo",pri_azimuth_lo,HELP_AZIMUTH_LO);
options.findWithValue("azimuth_hi",pri_azimuth_hi,HELP_AZIMUTH_HI);
if(options.findWithValue("viewcone",pri_viewcone_hi,HELP_VIEWCONE)
!=VSOptions::FS_NOT_FOUND)pri_viewcone_lo=0;
options.findWithValue("viewcone_lo",pri_viewcone_lo,HELP_VIEWCONE_LO);
options.findWithValue("viewcone_hi",pri_viewcone_hi,HELP_VIEWCONE_HI);
options.findWithValue("sampling_radius",pri_sampling_radius,
HELP_SAMPLING_RADIUS);
options.findWithValue("e",pri_energy,HELP_ENERGY);
options.findWithValue("starting_depth",pri_start_depth,HELP_STARTING_DEPTH);
// SIMULATION OPTIONS
options.findWithValue("atmosphere",sim_atmosphere,HELP_ATMOSPHERE);
sim_modtran_data =
std::string("corsika") + VSDataConverter::toString(sim_atmosphere);
options.findWithValue("modtran_data",sim_modtran_data,HELP_MODTRAN_DATA);
options.findWithValue("transition_energy",sim_transition_energy,
HELP_TRANSITION_ENERGY);
if(options.find("magnetic_arizona",HELP_MAGNETIC_ARIZONA)
!=VSOptions::FS_NOT_FOUND)sim_bx = 25.2, sim_bz = 40.83;
if(options.find("magnetic_argentina",HELP_MAGNETIC_ARGENTINA)
!=VSOptions::FS_NOT_FOUND)sim_bx = 31.7, sim_bz = -14.8;
if(options.find("magnetic_equator",HELP_MAGNETIC_EQUATOR)
!=VSOptions::FS_NOT_FOUND)sim_bx = 40.0, sim_bz = 0.01;
options.findWithValue("magnetic_bx",sim_bx,HELP_MAGNETIC_BX);
options.findWithValue("magnetic_bz",sim_bz,HELP_MAGNETIC_BZ);
options.findWithValue("elec_mult_scat_factor",sim_elec_mul_scat_fac,
HELP_ELEC_MULT_SCAT_FACT);
#ifdef CORSIKA_THINNING
options.findWithValue("thinning_energy",sim_thinning_energy,
HELP_THINNING_ENERGY);
#endif
options.findWithValue("cutoff_hadron",sim_cutoff_hadron,
HELP_CUTOFF_HADRON);
options.findWithValue("cutoff_muon",sim_cutoff_muon,
HELP_CUTOFF_MUON);
options.findWithValue("cutoff_electron",sim_cutoff_electron,
HELP_CUTOFF_ELECTRON);
options.findWithValue("cutoff_gamma",sim_cutoff_gamma,
HELP_CUTOFF_GAMMA);
// CERENKOV OPTIONS
options.findWithValue("cerenkov_event_use", cer_event_use,
HELP_CERENKOV_EVENT_USE);
options.findWithValue("cerenkov_lambda_lo", cer_lambda_lo,
HELP_CERENKOV_LAMBDA_LO);
options.findWithValue("cerenkov_lambda_hi", cer_lambda_hi,
HELP_CERENKOV_LAMBDA_HI);
options.findWithValue("cerenkov_bunch", cer_bunch,
HELP_CERENKOV_BUNCH);
#ifdef CEFFIC
options.findWithValue("cerenkov_qeff",cer_qeff,
HELP_CERENKOV_QEFF);
options.findWithValue("cerenkov_atmo",cer_atmo,
HELP_CERENKOV_ATMO);
options.findWithValue("cerenkov_mirror",cer_mirror,
HELP_CERENKOV_MIRROR);
options.findWithValue("qeff_data",cer_choice_qeff,
HELP_QEFF_DATA);
options.findWithValue("atmo_data",cer_choice_atmo,
HELP_ATMO_DATA);
options.findWithValue("mirror_data",cer_choice_mirror,
HELP_MIRROR_DATA);
#endif
// OUTPUT OPTIONS
std::ostringstream of_par_stream;
of_par_stream << "corsika_particle_" << run_runno << ".dat";
out_particle_file = of_par_stream.str();
std::ostringstream of_cer_stream;
of_cer_stream << "corsika_cerenkov_" << run_runno << ".dat";
out_cerenkov_file = of_cer_stream.str();
options.findWithValue("max_event_print",out_max_event_print,
HELP_MAX_EVENT_PRINT);
options.findWithValue("min_print_energy",out_min_print_energy,
HELP_MIN_PRINT_ENERGY);
options.findWithValue("particle_output_enable",out_particle_enable,
HELP_PARTICLE_OUTPUT_ENABLE);
options.findWithValue("table_output_enable",out_table_enable,
HELP_TABLE_OUTPUT_ENABLE);
options.findWithValue("o",out_cerenkov_file,
HELP_O);
if(out_particle_enable == false)out_particle_file="/dev/null";
options.findWithValue("particle_output_file",out_particle_file,
HELP_PARTICLE_OUTPUT_FILE);
// IACT OPTIONS
if(options.find("no_impact_correction",HELP_NO_IMPACT_CORRECTION)!=
VSOptions::FS_NOT_FOUND)
iact_no_impact_corr = true;
// --------------------------------------------------------------------------
// ALL KNOWN OPTIONS HAVE BEEN PROCESSED
// --------------------------------------------------------------------------
if(argc>1)
{
std::cerr << progname << ": Unknown command line options:";
argc--,argv++;
while(argc)
{
std::cerr << ' ' << *argv;
argc--,argv++;
}
std::cerr << std::endl;
usage_error=true;
}
if(usage_error)
{
std::cerr << "Usage: " << progname << " [options]" << std::endl
<< "Options:" << std::endl;
options.printUsage(std::cerr);
return EXIT_FAILURE;
}
// --------------------------------------------------------------------------
// OVERRIDE COMMAND LINE OPTIONS OR DEFAULTS WITH VALUES FROM DATABASE
// --------------------------------------------------------------------------
if((ctl_db_use)&&(ctl_table_use)&&(!ctl_save))
{
VSSimDBTableParam* param = db_sim->getDataTableByName(ctl_table_name);
if(param==0)
{
std::cerr << progname
<< ": could not find table " << ctl_table_name
<< std::endl;
return EXIT_FAILURE;
}
pri_species = param->fPrimaryID;
pri_energy = param->fEnergyGeV;
pri_zenith_lo = param->fZenithMinRad/M_PI*180.0;
pri_zenith_hi = param->fZenithMaxRad/M_PI*180.0;
pri_azimuth_lo = param->fAzimuthMinRad/M_PI*180.0;
pri_azimuth_hi = param->fAzimuthMaxRad/M_PI*180.0;
pri_sampling_radius = param->fSamplingRadiusM;
tel_optics_id = param->fOpticsID;
run_num_shower = param->fWorkunitEventCount;
if(cer_event_use > 1) run_num_shower /= cer_event_use;
delete param;
}
if((ctl_db_use)&&(!ctl_save))
{
VSPrimaryArrivalDistribution* pad =
VSPADFactory::getInstance()->getPrimaryArrivalDistribution(db_param);
if(pad)pad->setCORSIKAParameters(pri_zenith_lo, pri_zenith_hi,
pri_azimuth_lo, pri_azimuth_hi,
pri_viewcone_lo, pri_viewcone_hi);
delete pad;
}
// --------------------------------------------------------------------------
// VALIDATE STEERING FILE PARAMETERS
// --------------------------------------------------------------------------
if(pri_zenith_hi < pri_zenith_lo)
{
std::cerr << progname << ": Upper bound on zenith range ("
<< pri_zenith_hi
<< ") must not be smaller than lower bound ("
<< pri_zenith_lo
<< ")" << std::endl;
return EXIT_FAILURE;
}
if(pri_azimuth_hi < pri_azimuth_lo)
{
std::cerr << progname << ": Upper bound on azimuth range ("
<< pri_azimuth_hi
<< ") must not be smaller than lower bound ("
<< pri_azimuth_lo
<< ")" << std::endl;
return EXIT_FAILURE;
}
// --------------------------------------------------------------------------
// WRITE OPTIONS TO DATABASE IF REQUESTED
// --------------------------------------------------------------------------
if((ctl_save)&&(ctl_db_use))
{
VSDBParameterSet param;
#define SETPARAM(x,y) param[(x)]=VSDataConverter::toString(y)
SETPARAM("debug",cor_debug);
if(cor_no_qgs)param["no_qgs"]="";
if(cor_no_fluka)param["no_fluka"]="";
if(cor_no_ceffic)param["no_ceffic"]="";
if(cor_no_modtran)param["no_modtran"]="";
SETPARAM("tel_optics_id",tel_optics_id);
SETPARAM("tel_rings",tel_rings);
SETPARAM("tel_spacing",tel_spacing);
SETPARAM("tel_elevation",tel_elevation);
SETPARAM("tel_aperture",tel_aperture);
SETPARAM("tel_max_dist",tel_max_dist);
SETPARAM("tel_layout",tel_layout);
SETPARAM("primary",pri_species);
SETPARAM("zenith_lo",pri_zenith_lo);
SETPARAM("zenith_hi",pri_zenith_hi);
SETPARAM("azimuth_lo",pri_azimuth_lo);
SETPARAM("azimuth_hi",pri_azimuth_hi);
SETPARAM("viewcone_lo",pri_viewcone_lo);
SETPARAM("viewcone_hi",pri_viewcone_hi);
SETPARAM("sampling_radius",pri_sampling_radius);
SETPARAM("e",pri_energy);
SETPARAM("starting_depth",pri_start_depth);
SETPARAM("atmosphere",sim_atmosphere);
SETPARAM("modtran_data",sim_modtran_data);
SETPARAM("transition_energy",sim_transition_energy);
SETPARAM("magnetic_bx",sim_bx);
SETPARAM("magnetic_bz",sim_bz);
SETPARAM("elec_mult_scat_factor",sim_elec_mul_scat_fac);
#ifdef CORSIKA_THINNING
SETPARAM("thinning_energy",sim_thinning_energy);
#endif
SETPARAM("cutoff_hadron",sim_cutoff_hadron);
SETPARAM("cutoff_muon",sim_cutoff_muon);
SETPARAM("cutoff_electron",sim_cutoff_electron);
SETPARAM("cutoff_gamma",sim_cutoff_gamma);
SETPARAM("cerenkov_event_use", cer_event_use);
SETPARAM("cerenkov_lambda_lo", cer_lambda_lo);
SETPARAM("cerenkov_lambda_hi", cer_lambda_hi);
SETPARAM("cerenkov_bunch", cer_bunch);
SETPARAM("cerenkov_qeff",cer_qeff);
SETPARAM("cerenkov_atmo",cer_atmo);
SETPARAM("cerenkov_mirror",cer_mirror);
SETPARAM("qeff_data",cer_choice_qeff);
SETPARAM("atmo_data",cer_choice_atmo);
SETPARAM("mirror_data",cer_choice_mirror);
SETPARAM("max_event_print",out_max_event_print);
SETPARAM("min_print_energy",out_min_print_energy);
SETPARAM("particle_output_enable",out_particle_enable);
SETPARAM("table_output_enable",out_table_enable);
SETPARAM("particle_output_file",out_particle_file);
if(iact_no_impact_corr)param["no_impact_correction"]="";
db_param->deleteParameterSet("MakeSteering");
db_param->storeParameterSet("MakeSteering",param);
}
if(ctl_save)return EXIT_SUCCESS;
// --------------------------------------------------------------------------
// SAMPLE UNIQUE TARGET DIRECTION IF NECESSARY
// --------------------------------------------------------------------------
if(fabs(pri_viewcone_hi - pri_viewcone_lo)>0)
{
float cos_zn_lo = cos(pri_zenith_lo*M_PI/180.0);
float cos_zn_hi = cos(pri_zenith_hi*M_PI/180.0);
float x = float(random())/float(RAND_MAX);
float cos_zn = cos_zn_lo*(1.0-x) + cos_zn_hi*x;
pri_zenith_hi=pri_zenith_lo=acos(cos_zn)/M_PI*180.0;
float y = float(random())/float(RAND_MAX);
float az = pri_azimuth_lo*(1.0-y) + pri_azimuth_hi*y;
pri_azimuth_hi=pri_azimuth_lo=az;
}
// --------------------------------------------------------------------------
// CONVERT UNITS TO THOSE USED BY CORSIKA AND IMPOSE LIMITS ON STRINGS
// --------------------------------------------------------------------------
pri_azimuth_hi = 180 - pri_azimuth_hi;
pri_azimuth_lo = 180 - pri_azimuth_lo;
std::swap(pri_azimuth_hi, pri_azimuth_lo);
if(pri_azimuth_hi-pri_azimuth_lo >= 360.0)
pri_azimuth_hi=180.0, pri_azimuth_lo=-180.0;
if(pri_azimuth_lo < -360.0)
pri_azimuth_hi += floor(fabs(pri_azimuth_lo)/360.0)*360.0,
pri_azimuth_lo += floor(fabs(pri_azimuth_lo)/360.0)*360.0;
if(pri_azimuth_hi > 360.0)
pri_azimuth_lo -= floor(fabs(pri_azimuth_hi)/360.0)*360.0,
pri_azimuth_hi -= floor(fabs(pri_azimuth_hi)/360.0)*360.0;
pri_sampling_radius *= 100.0;
tel_spacing *= 100.0;
tel_elevation *= 100.0;
tel_aperture *= 100.0;
tel_max_dist *= 100.0;
#define LIMIT(x,y) if(x.size()>y)x=x.substr(0,y)
LIMIT(run_hostname,20);
LIMIT(run_username,20);
LIMIT(out_particle_file,100);
LIMIT(out_cerenkov_file,100);
// --------------------------------------------------------------------------
// SET UP VARIOUS ARRAYS AND STRUCTURES USED IN WRITING CORSIKA OPTIONS
// --------------------------------------------------------------------------
std::vector<unsigned> _seed1(3,0); _seed1[0]=run_seed1; _seed1[1]=100000;
std::vector<unsigned> _seed2(3,0); _seed2[0]=run_seed2; _seed2[1]=100000;
std::vector<unsigned> _seed3(3,0); _seed3[0]=run_seed3; _seed3[1]=100000;
std::vector<unsigned> _seed4(3,0); _seed4[0]=run_seed4; _seed4[1]=100000;
std::vector<float> thetap(2);
thetap[0]=pri_zenith_lo;
thetap[1]=pri_zenith_hi;
std::vector<float> phip(2);
phip[0]=pri_azimuth_lo;
phip[1]=pri_azimuth_hi;
std::vector<float> vuecon(2);
vuecon[0]=pri_viewcone_lo;
vuecon[1]=pri_viewcone_hi;
std::vector<float> erange(2,pri_energy);
std::vector<float> magnet;
magnet.push_back(sim_bx);
magnet.push_back(sim_bz);
std::vector<float> cutoff;
cutoff.push_back(sim_cutoff_hadron);
cutoff.push_back(sim_cutoff_muon);
cutoff.push_back(sim_cutoff_electron);
cutoff.push_back(sim_cutoff_gamma);
std::vector<bool> parout;
parout.push_back(out_particle_enable);
parout.push_back(out_table_enable);
std::vector<float> cwavlg;
cwavlg.push_back(cer_lambda_lo);
cwavlg.push_back(cer_lambda_hi);
std::vector<bool> cerqef;
cerqef.push_back(cer_qeff);
cerqef.push_back(cer_atmo);
cerqef.push_back(cer_mirror);
CSCAT_Struct cscat;
cscat.event_use = cer_event_use;
cscat.sampling_radius = pri_sampling_radius;
#ifdef QGSJET
QGSJET_Struct qgs;
qgs.debug=(cor_debug>0)?(cor_debug-1):0;
if(qgs.debug>4)qgs.debug=4;
#endif
Modtran_Struct modtran;
modtran.atmosphere=sim_atmosphere;
modtran.refraction=false;
// --------------------------------------------------------------------------
// SET UP TELESCOPE ARRAY (AUTOMATICALLY GENERATED OR FROM DATABASE)
// --------------------------------------------------------------------------
std::vector<std::vector<float> > telescopes;
if(ctl_db_use)
{
VSOTelescopeArray array;
array.readFromDatabase(db,tel_optics_id);
assert(array.numTelescopes());
tel_elevation =
array.telescope(0)->altitude()-array.telescope(0)->reflectorIP()/2.0;
std::vector<float> telescope;
for(unsigned iscope = 0; iscope<array.numTelescopes(); iscope++)
{
const VSOTelescope* scope = array.telescope(iscope);
Physics::Vec3D pos = scope->position();
std::vector<float> telescope;
// CORSIKA coordinate system is rotated WRT optical simulation
telescope.push_back(pos.y);
telescope.push_back(-pos.x);
telescope.push_back(pos.z);
telescope.push_back(scope->reflectorIP()/2.0);
telescopes.push_back(telescope);
if((pos.z-scope->reflectorIP()/2.0) < tel_elevation)
tel_elevation = pos.z-scope->reflectorIP()/2.0;
}
for(std::vector<std::vector<float> >::iterator itel =
telescopes.begin(); itel != telescopes.end(); itel++)
(*itel)[2]-=tel_elevation;
}
else
{
unsigned ntel = 3*tel_rings*(tel_rings+1)+1;
if(tel_layout=="square")ntel = (2*tel_rings+1)*(2*tel_rings+1);
for(unsigned itel=0; itel<ntel; itel++)
{
double x;
double y;
double z=0;
int n=itel+1;
if(tel_layout=="square")ns_to_xy(n, &x, &y);
else nh_to_xy(&n, &x, &y);
x *= tel_spacing;
y *= tel_spacing;
double r2 = x*x+y*y;
if(std::isfinite(tel_max_dist) && r2>tel_max_dist*tel_max_dist)
continue;
std::vector<float> telescope;
telescope.push_back(x);
telescope.push_back(y);
telescope.push_back(z);
telescope.push_back(tel_aperture/2.0);
telescopes.push_back(telescope);
}
}
// --------------------------------------------------------------------------
// WRITE CORSIKA FILES
// --------------------------------------------------------------------------
if((ctl_init)&&(db))
{
VSSimDBCORSIKADatasets db_datasets(db);
VSSimDBWavelengthDataset* ds_quantum_efficiency(0);
VSSimDBWavelengthDataset* ds_mirror_reflectivity(0);
VSSimDBWavelengthAltitudeDataset* ds_atmospheric_absorption(0);
VSSimDBModtranProfileDataset* ds_modtran_profile(0);
ds_quantum_efficiency =
db_datasets.retrieveWavelengthDataset(VSIMDB_TABLE_NAME_QUANEFF);
ds_mirror_reflectivity =
db_datasets.retrieveWavelengthDataset(VSIMDB_TABLE_NAME_MIRRREF);
ds_atmospheric_absorption =
db_datasets.
retrieveWavelengthAltitudeDataset(VSIMDB_TABLE_NAME_ATMOABS);
ds_modtran_profile =
db_datasets.retrieveModtranProfileDataset(VSIMDB_TABLE_NAME_MODTRAN);
if(ds_quantum_efficiency)
{
ds_quantum_efficiency->writeToCORSIKA("quanteff.dat");
cer_choice_qeff="none";
delete ds_quantum_efficiency;
}
if(ds_mirror_reflectivity)
{
ds_mirror_reflectivity->writeToCORSIKA("mirreff.dat");
cer_choice_mirror="none";
delete ds_mirror_reflectivity;
}
if(ds_atmospheric_absorption)
{
ds_atmospheric_absorption->writeToCORSIKA("atmabs.dat");
cer_choice_atmo="none";
delete ds_atmospheric_absorption;
}
if(ds_modtran_profile)
{
ds_modtran_profile->writeToCORSIKA("atmprof99.dat");
sim_modtran_data="none";
cor_no_modtran=false;
modtran.atmosphere=99;
delete ds_modtran_profile;
}
}
writeAllCORSIKADataFiles(!ctl_init,
sim_modtran_data,
cer_choice_qeff,
cer_choice_atmo,
cer_choice_mirror);
// --------------------------------------------------------------------------
// WRITE CORSIKA STEERING FILE
// --------------------------------------------------------------------------
std::ostream* stream = &std::cout;
write_card_option(*stream, "RUNNR", run_runno); // 4.1
write_card_option(*stream, "EVTNR", run_eventno) ; // 4.2
write_card_option(*stream, "SEED", _seed1); // 4.3
write_card_option(*stream, "SEED", _seed2); // 4.3
write_card_option(*stream, "SEED", _seed3); // 4.3
write_card_option(*stream, "SEED", _seed4); // 4.3
write_card_option(*stream, "NSHOW", run_num_shower); // 4.4
write_card_option(*stream, "PRMPAR", pri_species); // 4.5
write_card_option(*stream, "ERANGE", erange); // 4.6
write_card_option(*stream, "THETAP", thetap); // 4.8
write_card_option(*stream, "PHIP", phip); // 4.9
write_card_option(*stream, "VIEWCONE", vuecon); // 4.10
write_card_option(*stream, "FIXCHI", pri_start_depth); // 4.11
if(cor_no_modtran)
write_card_option(*stream, "ATMOD", sim_atmosphere); // 4.15
else
write_card_option(*stream, "ATMOSPHERE", modtran); // 4.20
write_card_option(*stream, "MAGNET", magnet); // 4.21
#ifdef QGSJET
if(!cor_no_qgs)
write_card_option(*stream, "QGSJET", qgs); // 4.28
#endif
write_card_option(*stream, "HILOW", sim_transition_energy); // 4.36
write_card_option(*stream, "ELMFLG", "F T"); // 4.37
write_card_option(*stream, "STEPFC", sim_elec_mul_scat_fac); // 4.38
#ifdef CORSIKA_THINNING
write_card_option(*stream, "THIN", sim_thinning_energy/erange[1]); // 4.40
#endif
write_card_option(*stream, "ECUTS", cutoff); // 4.43
write_card_option(*stream, "OBSLEV", tel_elevation); // 4.47
write_card_option(*stream, "MAXPRT", out_max_event_print); // 4.50
write_card_option(*stream, "ECTMAP", out_min_print_energy); // 4.51
write_card_option(*stream, "DIRECT", out_particle_file); // 4.52
write_card_option(*stream, "PAROUT", parout); // 4.53
write_card_option(*stream, "CWAVLG", cwavlg); // 4.57
write_card_option(*stream, "CERSIZ", (float)cer_bunch); // 4.58
write_card_option(*stream, "CERFIL", true); // 4.59
#ifdef CEFFIC
if(!cor_no_ceffic)
write_card_option(*stream, "CERQEF", cerqef); // 4.60
#endif
write_card_option(*stream, "CSCAT", cscat); // 4.61
for(std::vector<std::vector<float> >::const_iterator itel =
telescopes.begin(); itel != telescopes.end(); itel++)
write_card_option(*stream, "TELESCOPE", *itel); // 4.62
write_card_option(*stream, "TELFIL", out_cerenkov_file); // 4.63
write_card_option(*stream, "USER", run_username); // 4.65
write_card_option(*stream, "HOST", run_hostname); // 4.66
if(cor_debug>0)
write_card_option(*stream, "DEBUG", "T 6 F 0"); // 4.67
if(cor_debug>1)
write_card_option(*stream, "EGSDEB", unsigned(0)); // 4.68
#ifdef FLUKA
if((!cor_no_fluka)&&(cor_debug>1))
write_card_option(*stream, "FLUDBG", true); // 4.69
#endif
if(iact_no_impact_corr)
write_card_option(*stream, "IACT","impact_correction F"); // IACT
write_card_option(*stream, "EXIT"); // 4.79
// --------------------------------------------------------------------------
// CLEAN UP AND WE ARE FINISHED
// --------------------------------------------------------------------------
delete db_sim;
delete db_param;
delete db;
return(EXIT_SUCCESS);
}
| 34.633419 | 79 | 0.624295 | [
"vector"
] |
bfb7d0b1fbfd257ccc91739f4b60eb0dfa4f55e5 | 2,436 | cpp | C++ | vslib/src/sai_vs_generic_remove.cpp | qiluo-msft/sonic-sairedis | 2059e4580d04dab68b5e15241c366fac9b3eaf30 | [
"Apache-2.0"
] | null | null | null | vslib/src/sai_vs_generic_remove.cpp | qiluo-msft/sonic-sairedis | 2059e4580d04dab68b5e15241c366fac9b3eaf30 | [
"Apache-2.0"
] | null | null | null | vslib/src/sai_vs_generic_remove.cpp | qiluo-msft/sonic-sairedis | 2059e4580d04dab68b5e15241c366fac9b3eaf30 | [
"Apache-2.0"
] | null | null | null | #include "sai_vs.h"
#include "sai_vs_state.h"
sai_status_t internal_vs_generic_remove(
_In_ sai_object_type_t object_type,
_In_ const std::string &serialized_object_id)
{
SWSS_LOG_ENTER();
auto it = g_objectHash.find(serialized_object_id);
if (it == g_objectHash.end())
{
SWSS_LOG_ERROR("Remove failed, object not found, object type: %d: id: %s", object_type, serialized_object_id.c_str());
return SAI_STATUS_ITEM_NOT_FOUND;
}
g_objectHash.erase(it);
SWSS_LOG_DEBUG("Remove succeeded, object type: %d, id: %s", object_type, serialized_object_id.c_str());
return SAI_STATUS_SUCCESS;
}
sai_status_t vs_generic_remove(
_In_ sai_object_type_t object_type,
_In_ sai_object_id_t object_id)
{
SWSS_LOG_ENTER();
std::string str_object_id;
sai_serialize_primitive(object_id, str_object_id);
sai_status_t status = internal_vs_generic_remove(
object_type,
str_object_id);
return status;
}
sai_status_t vs_generic_remove_fdb_entry(
_In_ const sai_fdb_entry_t* fdb_entry)
{
SWSS_LOG_ENTER();
std::string str_fdb_entry;
sai_serialize_primitive(*fdb_entry, str_fdb_entry);
sai_status_t status = internal_vs_generic_remove(
SAI_OBJECT_TYPE_FDB,
str_fdb_entry);
return status;
}
sai_status_t vs_generic_remove_neighbor_entry(
_In_ const sai_neighbor_entry_t* neighbor_entry)
{
SWSS_LOG_ENTER();
std::string str_neighbor_entry;
sai_serialize_neighbor_entry(*neighbor_entry, str_neighbor_entry);
sai_status_t status = internal_vs_generic_remove(
SAI_OBJECT_TYPE_NEIGHBOR,
str_neighbor_entry);
return status;
}
sai_status_t vs_generic_remove_route_entry(
_In_ const sai_unicast_route_entry_t* unicast_route_entry)
{
SWSS_LOG_ENTER();
std::string str_route_entry;
sai_serialize_route_entry(*unicast_route_entry, str_route_entry);
sai_status_t status = internal_vs_generic_remove(
SAI_OBJECT_TYPE_ROUTE,
str_route_entry);
return status;
}
sai_status_t vs_generic_remove_vlan(
_In_ sai_vlan_id_t vlan_id)
{
SWSS_LOG_ENTER();
std::string str_vlan_id;
sai_serialize_primitive(vlan_id, str_vlan_id);
sai_status_t status = internal_vs_generic_remove(
SAI_OBJECT_TYPE_VLAN,
str_vlan_id);
return status;
}
| 24.118812 | 126 | 0.714286 | [
"object"
] |
bfb87085ce87970c0356d4fbba00e4a24cf71be7 | 7,710 | cpp | C++ | src/mapleall/maple_be/src/cg/x86_64/x64_call_conv.cpp | venshine/OpenArkCompiler | 264cd4463834356658154f0d254672ef559f245f | [
"MulanPSL-1.0"
] | 2 | 2019-09-06T07:02:41.000Z | 2019-09-09T12:24:46.000Z | src/mapleall/maple_be/src/cg/x86_64/x64_call_conv.cpp | venshine/OpenArkCompiler | 264cd4463834356658154f0d254672ef559f245f | [
"MulanPSL-1.0"
] | null | null | null | src/mapleall/maple_be/src/cg/x86_64/x64_call_conv.cpp | venshine/OpenArkCompiler | 264cd4463834356658154f0d254672ef559f245f | [
"MulanPSL-1.0"
] | null | null | null | /*
* Copyright (c) [2022] Huawei Technologies Co.,Ltd.All rights reserved.
*
* OpenArkCompiler is licensed under Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR
* FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "x64_cgfunc.h"
#include "becommon.h"
#include "abi.h"
#include "x64_call_conv.h"
namespace maplebe {
using namespace maple;
using namespace x64;
constexpr int kMaxRegCount = 4;
/* X86-64 Function Calling Sequence */
int32 ProcessStructWhenClassifyAggregate(MIRStructType &structType, ArgumentClass classes[kMaxRegCount],
uint64 sizeOfTy) {
uint32 accSize = 0;
uint32 numRegs = 0;
for (uint32 f = 0; f < structType.GetFieldsSize(); ++f) {
TyIdx fieldTyIdx = structType.GetFieldsElemt(f).second.first;
MIRType *fieldType = GlobalTables::GetTypeTable().GetTypeFromTyIdx(fieldTyIdx);
if (fieldType->GetKind() == kTypeArray || fieldType->GetKind() == kTypeStruct) {
CHECK_FATAL(false, "NYI");
return 0;
}
PrimType eleType = fieldType->GetPrimType();
if (IsPrimitivePureScalar(eleType)) {
uint32 curSize = GetPrimTypeSize(eleType);
if (accSize + curSize > k1EightBytesSize) {
numRegs++;
accSize = curSize;
continue;
}
accSize += curSize;
} else {
CHECK_FATAL(false, "NYI");
return 0;
}
}
/* Reg Usage after the last element is processed */
numRegs += (RoundUp(accSize, k8ByteSize) >> k8BitShift);
if (numRegs > kTwoRegister) {
classes[0] = kMemoryClass;
return static_cast<int32>(sizeOfTy);
}
classes[0] = kIntegerClass;
if (numRegs == kTwoRegister) {
classes[1] = kIntegerClass;
}
return numRegs;
}
int32 ClassifyAggregate(MIRType &mirType, uint64 sizeOfTy, ArgumentClass classes[kMaxRegCount]) {
/*
* 1. If the size of an object is larger than four eightbytes, or it contains unaligned
* fields, it has class MEMORY;
* 2. for the processors that do not support the __m256 type, if the size of an object
* is larger than two eightbytes and the first eightbyte is not SSE or any other eightbyte
* is not SSEUP, it still has class MEMORY.
* This in turn ensures that for rocessors that do support the __m256 type, if the size of
* an object is four eightbytes and the first eightbyte is SSE and all other eightbytes are
* SSEUP, it can be passed in a register.
*(Currently, assume that m256 is not supported)
*/
if ((sizeOfTy > k2EightBytesSize)) {
classes[0] = kMemoryClass;
return static_cast<int32>(sizeOfTy);
}
if (mirType.GetKind() == kTypeStruct) {
MIRStructType &structType = static_cast<MIRStructType&>(mirType);
return ProcessStructWhenClassifyAggregate(structType, classes, sizeOfTy);
}
CHECK_FATAL(false, "NYI");
return static_cast<int32>(sizeOfTy);
}
int32 Classification(const BECommon &be, MIRType &mirType, ArgumentClass classes[kMaxRegCount]) {
switch (mirType.GetPrimType()) {
/*
* Arguments of types void, (signed and unsigned) _Bool, char, short, int,
* long, long long, and pointers are in the INTEGER class.
*/
case PTY_void:
case PTY_u1:
case PTY_u8:
case PTY_i8:
case PTY_u16:
case PTY_i16:
case PTY_a32:
case PTY_u32:
case PTY_i32:
case PTY_a64:
case PTY_ptr:
case PTY_ref:
case PTY_u64:
case PTY_i64:
classes[0] = kIntegerClass;
return kOneRegister;
/*
* Arguments of type __int128 offer the same operations as INTEGERs,
* yet they do not fit into one general purpose register but require
* two registers.
*/
case PTY_i128:
case PTY_u128:
classes[0] = kIntegerClass;
classes[1] = kIntegerClass;
return kTwoRegister;
case PTY_agg: {
/*
* The size of each argument gets rounded up to eightbytes,
* Therefore the stack will always be eightbyte aligned.
*/
uint64 sizeOfTy = RoundUp(be.GetTypeSize(mirType.GetTypeIndex()), k8ByteSize);
CHECK_FATAL(sizeOfTy != 0, "NIY");
/* If the size of an object is larger than four eightbytes, it has class MEMORY */
if ((sizeOfTy > k4EightBytesSize)) {
classes[0] = kMemoryClass;
return static_cast<int32>(sizeOfTy);
}
return ClassifyAggregate(mirType, sizeOfTy, classes);
}
default:
CHECK_FATAL(false, "NYI");
}
return 0;
}
void X64CallConvImpl::InitCCLocInfo(CCLocInfo &pLoc) const {
pLoc.reg0 = kRinvalid;
pLoc.reg1 = kRinvalid;
pLoc.reg2 = kRinvalid;
pLoc.reg3 = kRinvalid;
pLoc.memOffset = nextStackArgAdress;
pLoc.fpSize = 0;
pLoc.numFpPureRegs = 0;
}
int32 X64CallConvImpl::LocateNextParm(MIRType &mirType, CCLocInfo &pLoc, bool isFirst, MIRFunction *tFunc) {
InitCCLocInfo(pLoc);
ArgumentClass classes[kMaxRegCount] = { kNoClass }; /* Max of four Regs. */
int32 alignedTySize = Classification(beCommon, mirType, classes);
if (alignedTySize == 0) {
return 0;
}
pLoc.memSize = alignedTySize;
++paramNum;
if (classes[0] == kIntegerClass) {
if(alignedTySize == kOneRegister) {
pLoc.reg0 = AllocateGPParmRegister();
ASSERT(nextGeneralParmRegNO <= kNumIntParmRegs, "RegNo should be pramRegNO");
} else if (alignedTySize == kTwoRegister) {
AllocateTwoGPParmRegisters(pLoc);
ASSERT(nextGeneralParmRegNO <= kNumIntParmRegs, "RegNo should be pramRegNO");
}
}
if (pLoc.reg0 == kRinvalid || classes[0] == kMemoryClass) {
/* being passed in memory */
nextStackArgAdress = pLoc.memOffset + alignedTySize * k8ByteSize;
}
return 0;
}
int32 X64CallConvImpl::LocateRetVal(MIRType &retType, CCLocInfo &pLoc) {
InitCCLocInfo(pLoc);
ArgumentClass classes[kMaxRegCount] = { kNoClass }; /* Max of four Regs. */
int32 alignedTySize = Classification(beCommon, retType, classes);
if (alignedTySize == 0) {
return 0; /* size 0 ret val */
}
if (classes[0] == kIntegerClass) {
/* If the class is INTEGER, the next available register of the sequence %rax, */
/* %rdx is used. */
CHECK_FATAL(alignedTySize <= kTwoRegister, "LocateRetVal: illegal number of regs");
pLoc.regCount = alignedTySize;
if(alignedTySize == kOneRegister) {
pLoc.reg0 = AllocateGPReturnRegister();
ASSERT(nextGeneralReturnRegNO <= kNumIntReturnRegs, "RegNo should be pramRegNO");
} else if (alignedTySize == kTwoRegister) {
AllocateTwoGPReturnRegisters(pLoc);
ASSERT(nextGeneralReturnRegNO <= kNumIntReturnRegs, "RegNo should be pramRegNO");
}
if (nextGeneralReturnRegNO == kOneRegister) {
pLoc.primTypeOfReg0 = retType.GetPrimType();
} else if (nextGeneralReturnRegNO == kTwoRegister) {
pLoc.primTypeOfReg1 = retType.GetPrimType();
}
return 0;
}
if (pLoc.reg0 == kRinvalid || classes[0] == kMemoryClass) {
/*
* the caller provides space for the return value and passes
* the address of this storage in %rdi as if it were the first
* argument to the function. In effect, this address becomes a
* “hidden” first argument.
* On return %rax will contain the address that has been passed
* in by the caller in %rdi.
* Currently, this scenario is not fully supported.
*/
pLoc.reg0 = AllocateGPReturnRegister();
return 0;
}
CHECK_FATAL(false, "NYI");
return 0;
}
} /* namespace maplebe */
| 35.205479 | 108 | 0.679248 | [
"object"
] |
bfbdb7bcdf886485ebc4d29d2d9227c06cee000e | 345 | cpp | C++ | LeetCode/Palindrome Permutation/main.cpp | Code-With-Aagam/competitive-programming | 610520cc396fb13a03c606b5fb6739cfd68cc444 | [
"MIT"
] | 2 | 2022-02-08T12:37:41.000Z | 2022-03-09T03:48:56.000Z | LeetCode/Palindrome Permutation/main.cpp | ShubhamJagtap2000/competitive-programming-1 | 3a9a2e3dd08f8fa8ab823f295cd020d08d3bff84 | [
"MIT"
] | null | null | null | LeetCode/Palindrome Permutation/main.cpp | ShubhamJagtap2000/competitive-programming-1 | 3a9a2e3dd08f8fa8ab823f295cd020d08d3bff84 | [
"MIT"
] | null | null | null | class Solution {
public:
bool canPermutePalindrome(string s) {
vector<int> freq(257, 0);
for (const auto &ch : s) {
freq[ch]++;
}
int odd = 0;
for (const auto &ele : freq) {
if (ele % 2 == 1) {
odd++;
}
}
return odd <= 1;
}
}; | 21.5625 | 41 | 0.388406 | [
"vector"
] |
bfd726b2050311929a035a1f56bff04c3c765f2c | 2,753 | cpp | C++ | ABC/ABC033/D.cpp | rajyan/AtCoder | 2c1187994016d4c19b95489d2f2d2c0eab43dd8e | [
"MIT"
] | 1 | 2021-06-01T17:13:44.000Z | 2021-06-01T17:13:44.000Z | ABC/ABC033/D.cpp | rajyan/AtCoder | 2c1187994016d4c19b95489d2f2d2c0eab43dd8e | [
"MIT"
] | null | null | null | ABC/ABC033/D.cpp | rajyan/AtCoder | 2c1187994016d4c19b95489d2f2d2c0eab43dd8e | [
"MIT"
] | null | null | null | //#pragma GCC optimize ("-O3", "unroll-loops")
//#pragma GCC target ("arch=ivybridge")
//
//#include <cassert>
//#include <cstdio>
//#include <cmath>
//#include <iostream>
//#include <iomanip>
//#include <sstream>
//#include <vector>
//#include <set>
//#include <map>
//#include <queue>
//#include <numeric>
//#include <algorithm>
//
//using namespace std;
//using lint = long long;
//constexpr int MOD = 1000000007, INF = 1010101010;
//constexpr lint LINF = 1LL << 60;
//
//template <class T>
//ostream &operator<<(ostream &os, const vector<T> &vec) {
// for (const auto &e : vec) os << e << (&e == &vec.back() ? "" : " ");
// return os;
//}
//
//#ifdef _DEBUG
//template <class T>
//void dump(const char* str, T &&h) { cerr << str << " = " << h << "\n"; };
//template <class Head, class... Tail>
//void dump(const char* str, Head &&h, Tail &&... t) {
// while (*str != ',') cerr << *str++; cerr << " = " << h << "\n";
// dump(str + (*(str + 1) == ' ' ? 2 : 1), t...);
//}
//#define DMP(...) dump(#__VA_ARGS__, __VA_ARGS__)
//#else
//#define DMP(...) ((void)0)
//#endif
//
//struct pnt {
// int x, y;
// constexpr pnt(int x = 0, int y = 0) : x(x), y(y) {};
// constexpr bool operator==(const pnt &rhs) const noexcept { return x == rhs.x && y == rhs.y; }
// constexpr bool operator<(const pnt & rhs) const noexcept { return x < rhs.x || x == rhs.x && y < rhs.y; }
// constexpr pnt operator+(const pnt &rhs) const noexcept { return pnt(x + rhs.x, y + rhs.y); }
// constexpr pnt operator-(const pnt &rhs) const noexcept { return pnt(x - rhs.x, y - rhs.y); }
// constexpr int operator*(const pnt &rhs) const noexcept { return x * rhs.x + y * rhs.y; }
// constexpr pnt operator*(const int &rhs) const noexcept { return pnt(x * rhs, y * rhs); }
// friend istream& operator>>(istream& is, pnt &p) { is >> p.x >> p.y; return is; }
// template<class T> T& operator[](vector<vector<T>> &v) { return v[x][y]; }
//};
//
//pnt point[2000];
//int len_pow[2000][2000];
//int inner[3];
//
//int main() {
//
// cin.tie(nullptr);
// ios::sync_with_stdio(false);
//
// int N;
// cin >> N;
//
// for (int i = 0; i < N; i++) cin >> point[i];
// for (int i = 0; i < N - 1; i++) {
// for (int j = i + 1; j < N; j++) {
// pnt sub = point[i] - point[j];
// len_pow[i][j] = sub * sub;
// }
// }
//
// vector<int> ans(3);
// for (int i = 0; i < N - 2; i++) {
// for (int j = i + 1; j < N - 1; j++) {
// for (int k = j + 1; k < N; k++) {
//
// int a = len_pow[i][j];
// int b = len_pow[i][k];
// int c = len_pow[j][k];
//
// int max_e = max({ a,b,c });
// int sub_e = a + b + c - 2 * max_e;
//
// if (sub_e > 0) ans[0]++;
// else if (sub_e == 0) ans[1]++;
// else ans[2]++;
//
// }
// }
// }
//
// cout << ans << "\n";
//
// return 0;
//}
| 28.091837 | 108 | 0.525972 | [
"vector"
] |
bfddebac0292fd57612e32996b77f227944efcc4 | 303,393 | cpp | C++ | pywinrt/winsdk/src/py.Windows.ApplicationModel.Email.cpp | pywinrt/python-winsdk | 1e2958a712949579f5e84d38220062b2cec12511 | [
"MIT"
] | 3 | 2022-02-14T14:53:08.000Z | 2022-03-29T20:48:54.000Z | pywinrt/winsdk/src/py.Windows.ApplicationModel.Email.cpp | pywinrt/python-winsdk | 1e2958a712949579f5e84d38220062b2cec12511 | [
"MIT"
] | 4 | 2022-01-28T02:53:52.000Z | 2022-02-26T18:10:05.000Z | pywinrt/winsdk/src/py.Windows.ApplicationModel.Email.cpp | pywinrt/python-winsdk | 1e2958a712949579f5e84d38220062b2cec12511 | [
"MIT"
] | null | null | null | // WARNING: Please don't edit this file. It was generated by Python/WinRT v1.0.0-beta.4
#include "pybase.h"
#include "py.Windows.ApplicationModel.Email.h"
PyTypeObject* py::winrt_type<winrt::Windows::ApplicationModel::Email::EmailAttachment>::python_type;
PyTypeObject* py::winrt_type<winrt::Windows::ApplicationModel::Email::EmailConversation>::python_type;
PyTypeObject* py::winrt_type<winrt::Windows::ApplicationModel::Email::EmailConversationBatch>::python_type;
PyTypeObject* py::winrt_type<winrt::Windows::ApplicationModel::Email::EmailConversationReader>::python_type;
PyTypeObject* py::winrt_type<winrt::Windows::ApplicationModel::Email::EmailFolder>::python_type;
PyTypeObject* py::winrt_type<winrt::Windows::ApplicationModel::Email::EmailIrmInfo>::python_type;
PyTypeObject* py::winrt_type<winrt::Windows::ApplicationModel::Email::EmailIrmTemplate>::python_type;
PyTypeObject* py::winrt_type<winrt::Windows::ApplicationModel::Email::EmailItemCounts>::python_type;
PyTypeObject* py::winrt_type<winrt::Windows::ApplicationModel::Email::EmailMailbox>::python_type;
PyTypeObject* py::winrt_type<winrt::Windows::ApplicationModel::Email::EmailMailboxAction>::python_type;
PyTypeObject* py::winrt_type<winrt::Windows::ApplicationModel::Email::EmailMailboxAutoReply>::python_type;
PyTypeObject* py::winrt_type<winrt::Windows::ApplicationModel::Email::EmailMailboxAutoReplySettings>::python_type;
PyTypeObject* py::winrt_type<winrt::Windows::ApplicationModel::Email::EmailMailboxCapabilities>::python_type;
PyTypeObject* py::winrt_type<winrt::Windows::ApplicationModel::Email::EmailMailboxChange>::python_type;
PyTypeObject* py::winrt_type<winrt::Windows::ApplicationModel::Email::EmailMailboxChangeReader>::python_type;
PyTypeObject* py::winrt_type<winrt::Windows::ApplicationModel::Email::EmailMailboxChangeTracker>::python_type;
PyTypeObject* py::winrt_type<winrt::Windows::ApplicationModel::Email::EmailMailboxChangedDeferral>::python_type;
PyTypeObject* py::winrt_type<winrt::Windows::ApplicationModel::Email::EmailMailboxChangedEventArgs>::python_type;
PyTypeObject* py::winrt_type<winrt::Windows::ApplicationModel::Email::EmailMailboxCreateFolderResult>::python_type;
PyTypeObject* py::winrt_type<winrt::Windows::ApplicationModel::Email::EmailMailboxPolicies>::python_type;
PyTypeObject* py::winrt_type<winrt::Windows::ApplicationModel::Email::EmailMailboxSyncManager>::python_type;
PyTypeObject* py::winrt_type<winrt::Windows::ApplicationModel::Email::EmailManager>::python_type;
PyTypeObject* py::winrt_type<winrt::Windows::ApplicationModel::Email::EmailManagerForUser>::python_type;
PyTypeObject* py::winrt_type<winrt::Windows::ApplicationModel::Email::EmailMeetingInfo>::python_type;
PyTypeObject* py::winrt_type<winrt::Windows::ApplicationModel::Email::EmailMessage>::python_type;
PyTypeObject* py::winrt_type<winrt::Windows::ApplicationModel::Email::EmailMessageBatch>::python_type;
PyTypeObject* py::winrt_type<winrt::Windows::ApplicationModel::Email::EmailMessageReader>::python_type;
PyTypeObject* py::winrt_type<winrt::Windows::ApplicationModel::Email::EmailQueryOptions>::python_type;
PyTypeObject* py::winrt_type<winrt::Windows::ApplicationModel::Email::EmailQueryTextSearch>::python_type;
PyTypeObject* py::winrt_type<winrt::Windows::ApplicationModel::Email::EmailRecipient>::python_type;
PyTypeObject* py::winrt_type<winrt::Windows::ApplicationModel::Email::EmailRecipientResolutionResult>::python_type;
PyTypeObject* py::winrt_type<winrt::Windows::ApplicationModel::Email::EmailStore>::python_type;
PyTypeObject* py::winrt_type<winrt::Windows::ApplicationModel::Email::EmailStoreNotificationTriggerDetails>::python_type;
namespace py::cpp::Windows::ApplicationModel::Email
{
// ----- EmailAttachment class --------------------
constexpr const char* const _type_name_EmailAttachment = "EmailAttachment";
static PyObject* _new_EmailAttachment(PyTypeObject* type, PyObject* args, PyObject* kwds) noexcept
{
if (kwds != nullptr)
{
py::set_invalid_kwd_args_error();
return nullptr;
}
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 3)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
auto param1 = py::convert_to<winrt::Windows::Storage::Streams::IRandomAccessStreamReference>(args, 1);
auto param2 = py::convert_to<winrt::hstring>(args, 2);
winrt::Windows::ApplicationModel::Email::EmailAttachment instance{ param0, param1, param2 };
return py::wrap(instance, type);
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
auto param1 = py::convert_to<winrt::Windows::Storage::Streams::IRandomAccessStreamReference>(args, 1);
winrt::Windows::ApplicationModel::Email::EmailAttachment instance{ param0, param1 };
return py::wrap(instance, type);
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else if (arg_count == 0)
{
try
{
winrt::Windows::ApplicationModel::Email::EmailAttachment instance{ };
return py::wrap(instance, type);
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static void _dealloc_EmailAttachment(py::wrapper::Windows::ApplicationModel::Email::EmailAttachment* self)
{
auto hash_value = std::hash<winrt::Windows::Foundation::IInspectable>{}(self->obj);
py::wrapped_instance(hash_value, nullptr);
self->obj = nullptr;
}
static PyObject* EmailAttachment_get_FileName(py::wrapper::Windows::ApplicationModel::Email::EmailAttachment* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.FileName());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailAttachment_put_FileName(py::wrapper::Windows::ApplicationModel::Email::EmailAttachment* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::hstring>(arg);
self->obj.FileName(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailAttachment_get_Data(py::wrapper::Windows::ApplicationModel::Email::EmailAttachment* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Data());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailAttachment_put_Data(py::wrapper::Windows::ApplicationModel::Email::EmailAttachment* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::Windows::Storage::Streams::IRandomAccessStreamReference>(arg);
self->obj.Data(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailAttachment_get_MimeType(py::wrapper::Windows::ApplicationModel::Email::EmailAttachment* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.MimeType());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailAttachment_put_MimeType(py::wrapper::Windows::ApplicationModel::Email::EmailAttachment* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::hstring>(arg);
self->obj.MimeType(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailAttachment_get_IsInline(py::wrapper::Windows::ApplicationModel::Email::EmailAttachment* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.IsInline());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailAttachment_put_IsInline(py::wrapper::Windows::ApplicationModel::Email::EmailAttachment* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<bool>(arg);
self->obj.IsInline(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailAttachment_get_EstimatedDownloadSizeInBytes(py::wrapper::Windows::ApplicationModel::Email::EmailAttachment* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.EstimatedDownloadSizeInBytes());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailAttachment_put_EstimatedDownloadSizeInBytes(py::wrapper::Windows::ApplicationModel::Email::EmailAttachment* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<uint64_t>(arg);
self->obj.EstimatedDownloadSizeInBytes(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailAttachment_get_DownloadState(py::wrapper::Windows::ApplicationModel::Email::EmailAttachment* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.DownloadState());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailAttachment_put_DownloadState(py::wrapper::Windows::ApplicationModel::Email::EmailAttachment* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::Windows::ApplicationModel::Email::EmailAttachmentDownloadState>(arg);
self->obj.DownloadState(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailAttachment_get_ContentLocation(py::wrapper::Windows::ApplicationModel::Email::EmailAttachment* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.ContentLocation());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailAttachment_put_ContentLocation(py::wrapper::Windows::ApplicationModel::Email::EmailAttachment* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::hstring>(arg);
self->obj.ContentLocation(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailAttachment_get_ContentId(py::wrapper::Windows::ApplicationModel::Email::EmailAttachment* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.ContentId());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailAttachment_put_ContentId(py::wrapper::Windows::ApplicationModel::Email::EmailAttachment* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::hstring>(arg);
self->obj.ContentId(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailAttachment_get_Id(py::wrapper::Windows::ApplicationModel::Email::EmailAttachment* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Id());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* EmailAttachment_get_IsFromBaseMessage(py::wrapper::Windows::ApplicationModel::Email::EmailAttachment* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.IsFromBaseMessage());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* _from_EmailAttachment(PyObject* /*unused*/, PyObject* arg) noexcept
{
try
{
auto return_value = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg);
return py::convert(return_value.as<winrt::Windows::ApplicationModel::Email::EmailAttachment>());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyMethodDef _methods_EmailAttachment[] = {
{ "_from", reinterpret_cast<PyCFunction>(_from_EmailAttachment), METH_O | METH_STATIC, nullptr },
{ }
};
static PyGetSetDef _getset_EmailAttachment[] = {
{ "file_name", reinterpret_cast<getter>(EmailAttachment_get_FileName), reinterpret_cast<setter>(EmailAttachment_put_FileName), nullptr, nullptr },
{ "data", reinterpret_cast<getter>(EmailAttachment_get_Data), reinterpret_cast<setter>(EmailAttachment_put_Data), nullptr, nullptr },
{ "mime_type", reinterpret_cast<getter>(EmailAttachment_get_MimeType), reinterpret_cast<setter>(EmailAttachment_put_MimeType), nullptr, nullptr },
{ "is_inline", reinterpret_cast<getter>(EmailAttachment_get_IsInline), reinterpret_cast<setter>(EmailAttachment_put_IsInline), nullptr, nullptr },
{ "estimated_download_size_in_bytes", reinterpret_cast<getter>(EmailAttachment_get_EstimatedDownloadSizeInBytes), reinterpret_cast<setter>(EmailAttachment_put_EstimatedDownloadSizeInBytes), nullptr, nullptr },
{ "download_state", reinterpret_cast<getter>(EmailAttachment_get_DownloadState), reinterpret_cast<setter>(EmailAttachment_put_DownloadState), nullptr, nullptr },
{ "content_location", reinterpret_cast<getter>(EmailAttachment_get_ContentLocation), reinterpret_cast<setter>(EmailAttachment_put_ContentLocation), nullptr, nullptr },
{ "content_id", reinterpret_cast<getter>(EmailAttachment_get_ContentId), reinterpret_cast<setter>(EmailAttachment_put_ContentId), nullptr, nullptr },
{ "id", reinterpret_cast<getter>(EmailAttachment_get_Id), nullptr, nullptr, nullptr },
{ "is_from_base_message", reinterpret_cast<getter>(EmailAttachment_get_IsFromBaseMessage), nullptr, nullptr, nullptr },
{ }
};
static PyType_Slot _type_slots_EmailAttachment[] =
{
{ Py_tp_new, _new_EmailAttachment },
{ Py_tp_dealloc, _dealloc_EmailAttachment },
{ Py_tp_methods, _methods_EmailAttachment },
{ Py_tp_getset, _getset_EmailAttachment },
{ },
};
static PyType_Spec _type_spec_EmailAttachment =
{
"_winsdk_Windows_ApplicationModel_Email.EmailAttachment",
sizeof(py::wrapper::Windows::ApplicationModel::Email::EmailAttachment),
0,
Py_TPFLAGS_DEFAULT,
_type_slots_EmailAttachment
};
// ----- EmailConversation class --------------------
constexpr const char* const _type_name_EmailConversation = "EmailConversation";
static PyObject* _new_EmailConversation(PyTypeObject* type, PyObject* args, PyObject* kwds) noexcept
{
py::set_invalid_activation_error(_type_name_EmailConversation);
return nullptr;
}
static void _dealloc_EmailConversation(py::wrapper::Windows::ApplicationModel::Email::EmailConversation* self)
{
auto hash_value = std::hash<winrt::Windows::Foundation::IInspectable>{}(self->obj);
py::wrapped_instance(hash_value, nullptr);
self->obj = nullptr;
}
static PyObject* EmailConversation_FindMessagesAsync(py::wrapper::Windows::ApplicationModel::Email::EmailConversation* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 0)
{
try
{
return py::convert(self->obj.FindMessagesAsync());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<uint32_t>(args, 0);
return py::convert(self->obj.FindMessagesAsync(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* EmailConversation_get_FlagState(py::wrapper::Windows::ApplicationModel::Email::EmailConversation* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.FlagState());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* EmailConversation_get_HasAttachment(py::wrapper::Windows::ApplicationModel::Email::EmailConversation* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.HasAttachment());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* EmailConversation_get_Id(py::wrapper::Windows::ApplicationModel::Email::EmailConversation* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Id());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* EmailConversation_get_Importance(py::wrapper::Windows::ApplicationModel::Email::EmailConversation* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Importance());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* EmailConversation_get_LastEmailResponseKind(py::wrapper::Windows::ApplicationModel::Email::EmailConversation* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.LastEmailResponseKind());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* EmailConversation_get_LatestSender(py::wrapper::Windows::ApplicationModel::Email::EmailConversation* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.LatestSender());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* EmailConversation_get_MailboxId(py::wrapper::Windows::ApplicationModel::Email::EmailConversation* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.MailboxId());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* EmailConversation_get_MessageCount(py::wrapper::Windows::ApplicationModel::Email::EmailConversation* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.MessageCount());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* EmailConversation_get_MostRecentMessageId(py::wrapper::Windows::ApplicationModel::Email::EmailConversation* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.MostRecentMessageId());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* EmailConversation_get_MostRecentMessageTime(py::wrapper::Windows::ApplicationModel::Email::EmailConversation* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.MostRecentMessageTime());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* EmailConversation_get_Preview(py::wrapper::Windows::ApplicationModel::Email::EmailConversation* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Preview());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* EmailConversation_get_Subject(py::wrapper::Windows::ApplicationModel::Email::EmailConversation* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Subject());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* EmailConversation_get_UnreadMessageCount(py::wrapper::Windows::ApplicationModel::Email::EmailConversation* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.UnreadMessageCount());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* _from_EmailConversation(PyObject* /*unused*/, PyObject* arg) noexcept
{
try
{
auto return_value = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg);
return py::convert(return_value.as<winrt::Windows::ApplicationModel::Email::EmailConversation>());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyMethodDef _methods_EmailConversation[] = {
{ "find_messages_async", reinterpret_cast<PyCFunction>(EmailConversation_FindMessagesAsync), METH_VARARGS, nullptr },
{ "_from", reinterpret_cast<PyCFunction>(_from_EmailConversation), METH_O | METH_STATIC, nullptr },
{ }
};
static PyGetSetDef _getset_EmailConversation[] = {
{ "flag_state", reinterpret_cast<getter>(EmailConversation_get_FlagState), nullptr, nullptr, nullptr },
{ "has_attachment", reinterpret_cast<getter>(EmailConversation_get_HasAttachment), nullptr, nullptr, nullptr },
{ "id", reinterpret_cast<getter>(EmailConversation_get_Id), nullptr, nullptr, nullptr },
{ "importance", reinterpret_cast<getter>(EmailConversation_get_Importance), nullptr, nullptr, nullptr },
{ "last_email_response_kind", reinterpret_cast<getter>(EmailConversation_get_LastEmailResponseKind), nullptr, nullptr, nullptr },
{ "latest_sender", reinterpret_cast<getter>(EmailConversation_get_LatestSender), nullptr, nullptr, nullptr },
{ "mailbox_id", reinterpret_cast<getter>(EmailConversation_get_MailboxId), nullptr, nullptr, nullptr },
{ "message_count", reinterpret_cast<getter>(EmailConversation_get_MessageCount), nullptr, nullptr, nullptr },
{ "most_recent_message_id", reinterpret_cast<getter>(EmailConversation_get_MostRecentMessageId), nullptr, nullptr, nullptr },
{ "most_recent_message_time", reinterpret_cast<getter>(EmailConversation_get_MostRecentMessageTime), nullptr, nullptr, nullptr },
{ "preview", reinterpret_cast<getter>(EmailConversation_get_Preview), nullptr, nullptr, nullptr },
{ "subject", reinterpret_cast<getter>(EmailConversation_get_Subject), nullptr, nullptr, nullptr },
{ "unread_message_count", reinterpret_cast<getter>(EmailConversation_get_UnreadMessageCount), nullptr, nullptr, nullptr },
{ }
};
static PyType_Slot _type_slots_EmailConversation[] =
{
{ Py_tp_new, _new_EmailConversation },
{ Py_tp_dealloc, _dealloc_EmailConversation },
{ Py_tp_methods, _methods_EmailConversation },
{ Py_tp_getset, _getset_EmailConversation },
{ },
};
static PyType_Spec _type_spec_EmailConversation =
{
"_winsdk_Windows_ApplicationModel_Email.EmailConversation",
sizeof(py::wrapper::Windows::ApplicationModel::Email::EmailConversation),
0,
Py_TPFLAGS_DEFAULT,
_type_slots_EmailConversation
};
// ----- EmailConversationBatch class --------------------
constexpr const char* const _type_name_EmailConversationBatch = "EmailConversationBatch";
static PyObject* _new_EmailConversationBatch(PyTypeObject* type, PyObject* args, PyObject* kwds) noexcept
{
py::set_invalid_activation_error(_type_name_EmailConversationBatch);
return nullptr;
}
static void _dealloc_EmailConversationBatch(py::wrapper::Windows::ApplicationModel::Email::EmailConversationBatch* self)
{
auto hash_value = std::hash<winrt::Windows::Foundation::IInspectable>{}(self->obj);
py::wrapped_instance(hash_value, nullptr);
self->obj = nullptr;
}
static PyObject* EmailConversationBatch_get_Conversations(py::wrapper::Windows::ApplicationModel::Email::EmailConversationBatch* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Conversations());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* EmailConversationBatch_get_Status(py::wrapper::Windows::ApplicationModel::Email::EmailConversationBatch* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Status());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* _from_EmailConversationBatch(PyObject* /*unused*/, PyObject* arg) noexcept
{
try
{
auto return_value = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg);
return py::convert(return_value.as<winrt::Windows::ApplicationModel::Email::EmailConversationBatch>());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyMethodDef _methods_EmailConversationBatch[] = {
{ "_from", reinterpret_cast<PyCFunction>(_from_EmailConversationBatch), METH_O | METH_STATIC, nullptr },
{ }
};
static PyGetSetDef _getset_EmailConversationBatch[] = {
{ "conversations", reinterpret_cast<getter>(EmailConversationBatch_get_Conversations), nullptr, nullptr, nullptr },
{ "status", reinterpret_cast<getter>(EmailConversationBatch_get_Status), nullptr, nullptr, nullptr },
{ }
};
static PyType_Slot _type_slots_EmailConversationBatch[] =
{
{ Py_tp_new, _new_EmailConversationBatch },
{ Py_tp_dealloc, _dealloc_EmailConversationBatch },
{ Py_tp_methods, _methods_EmailConversationBatch },
{ Py_tp_getset, _getset_EmailConversationBatch },
{ },
};
static PyType_Spec _type_spec_EmailConversationBatch =
{
"_winsdk_Windows_ApplicationModel_Email.EmailConversationBatch",
sizeof(py::wrapper::Windows::ApplicationModel::Email::EmailConversationBatch),
0,
Py_TPFLAGS_DEFAULT,
_type_slots_EmailConversationBatch
};
// ----- EmailConversationReader class --------------------
constexpr const char* const _type_name_EmailConversationReader = "EmailConversationReader";
static PyObject* _new_EmailConversationReader(PyTypeObject* type, PyObject* args, PyObject* kwds) noexcept
{
py::set_invalid_activation_error(_type_name_EmailConversationReader);
return nullptr;
}
static void _dealloc_EmailConversationReader(py::wrapper::Windows::ApplicationModel::Email::EmailConversationReader* self)
{
auto hash_value = std::hash<winrt::Windows::Foundation::IInspectable>{}(self->obj);
py::wrapped_instance(hash_value, nullptr);
self->obj = nullptr;
}
static PyObject* EmailConversationReader_ReadBatchAsync(py::wrapper::Windows::ApplicationModel::Email::EmailConversationReader* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 0)
{
try
{
return py::convert(self->obj.ReadBatchAsync());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* _from_EmailConversationReader(PyObject* /*unused*/, PyObject* arg) noexcept
{
try
{
auto return_value = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg);
return py::convert(return_value.as<winrt::Windows::ApplicationModel::Email::EmailConversationReader>());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyMethodDef _methods_EmailConversationReader[] = {
{ "read_batch_async", reinterpret_cast<PyCFunction>(EmailConversationReader_ReadBatchAsync), METH_VARARGS, nullptr },
{ "_from", reinterpret_cast<PyCFunction>(_from_EmailConversationReader), METH_O | METH_STATIC, nullptr },
{ }
};
static PyGetSetDef _getset_EmailConversationReader[] = {
{ }
};
static PyType_Slot _type_slots_EmailConversationReader[] =
{
{ Py_tp_new, _new_EmailConversationReader },
{ Py_tp_dealloc, _dealloc_EmailConversationReader },
{ Py_tp_methods, _methods_EmailConversationReader },
{ Py_tp_getset, _getset_EmailConversationReader },
{ },
};
static PyType_Spec _type_spec_EmailConversationReader =
{
"_winsdk_Windows_ApplicationModel_Email.EmailConversationReader",
sizeof(py::wrapper::Windows::ApplicationModel::Email::EmailConversationReader),
0,
Py_TPFLAGS_DEFAULT,
_type_slots_EmailConversationReader
};
// ----- EmailFolder class --------------------
constexpr const char* const _type_name_EmailFolder = "EmailFolder";
static PyObject* _new_EmailFolder(PyTypeObject* type, PyObject* args, PyObject* kwds) noexcept
{
py::set_invalid_activation_error(_type_name_EmailFolder);
return nullptr;
}
static void _dealloc_EmailFolder(py::wrapper::Windows::ApplicationModel::Email::EmailFolder* self)
{
auto hash_value = std::hash<winrt::Windows::Foundation::IInspectable>{}(self->obj);
py::wrapped_instance(hash_value, nullptr);
self->obj = nullptr;
}
static PyObject* EmailFolder_CreateFolderAsync(py::wrapper::Windows::ApplicationModel::Email::EmailFolder* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
return py::convert(self->obj.CreateFolderAsync(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* EmailFolder_DeleteAsync(py::wrapper::Windows::ApplicationModel::Email::EmailFolder* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 0)
{
try
{
return py::convert(self->obj.DeleteAsync());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* EmailFolder_FindChildFoldersAsync(py::wrapper::Windows::ApplicationModel::Email::EmailFolder* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 0)
{
try
{
return py::convert(self->obj.FindChildFoldersAsync());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* EmailFolder_GetConversationReader(py::wrapper::Windows::ApplicationModel::Email::EmailFolder* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 0)
{
try
{
return py::convert(self->obj.GetConversationReader());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::Windows::ApplicationModel::Email::EmailQueryOptions>(args, 0);
return py::convert(self->obj.GetConversationReader(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* EmailFolder_GetMessageAsync(py::wrapper::Windows::ApplicationModel::Email::EmailFolder* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
return py::convert(self->obj.GetMessageAsync(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* EmailFolder_GetMessageCountsAsync(py::wrapper::Windows::ApplicationModel::Email::EmailFolder* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 0)
{
try
{
return py::convert(self->obj.GetMessageCountsAsync());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* EmailFolder_GetMessageReader(py::wrapper::Windows::ApplicationModel::Email::EmailFolder* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 0)
{
try
{
return py::convert(self->obj.GetMessageReader());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::Windows::ApplicationModel::Email::EmailQueryOptions>(args, 0);
return py::convert(self->obj.GetMessageReader(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* EmailFolder_SaveMessageAsync(py::wrapper::Windows::ApplicationModel::Email::EmailFolder* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::Windows::ApplicationModel::Email::EmailMessage>(args, 0);
return py::convert(self->obj.SaveMessageAsync(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* EmailFolder_TryMoveAsync(py::wrapper::Windows::ApplicationModel::Email::EmailFolder* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::Windows::ApplicationModel::Email::EmailFolder>(args, 0);
return py::convert(self->obj.TryMoveAsync(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::Windows::ApplicationModel::Email::EmailFolder>(args, 0);
auto param1 = py::convert_to<winrt::hstring>(args, 1);
return py::convert(self->obj.TryMoveAsync(param0, param1));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* EmailFolder_TrySaveAsync(py::wrapper::Windows::ApplicationModel::Email::EmailFolder* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 0)
{
try
{
return py::convert(self->obj.TrySaveAsync());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* EmailFolder_get_RemoteId(py::wrapper::Windows::ApplicationModel::Email::EmailFolder* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.RemoteId());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailFolder_put_RemoteId(py::wrapper::Windows::ApplicationModel::Email::EmailFolder* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::hstring>(arg);
self->obj.RemoteId(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailFolder_get_LastSuccessfulSyncTime(py::wrapper::Windows::ApplicationModel::Email::EmailFolder* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.LastSuccessfulSyncTime());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailFolder_put_LastSuccessfulSyncTime(py::wrapper::Windows::ApplicationModel::Email::EmailFolder* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::Windows::Foundation::DateTime>(arg);
self->obj.LastSuccessfulSyncTime(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailFolder_get_IsSyncEnabled(py::wrapper::Windows::ApplicationModel::Email::EmailFolder* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.IsSyncEnabled());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailFolder_put_IsSyncEnabled(py::wrapper::Windows::ApplicationModel::Email::EmailFolder* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<bool>(arg);
self->obj.IsSyncEnabled(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailFolder_get_DisplayName(py::wrapper::Windows::ApplicationModel::Email::EmailFolder* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.DisplayName());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailFolder_put_DisplayName(py::wrapper::Windows::ApplicationModel::Email::EmailFolder* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::hstring>(arg);
self->obj.DisplayName(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailFolder_get_Id(py::wrapper::Windows::ApplicationModel::Email::EmailFolder* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Id());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* EmailFolder_get_Kind(py::wrapper::Windows::ApplicationModel::Email::EmailFolder* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Kind());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* EmailFolder_get_MailboxId(py::wrapper::Windows::ApplicationModel::Email::EmailFolder* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.MailboxId());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* EmailFolder_get_ParentFolderId(py::wrapper::Windows::ApplicationModel::Email::EmailFolder* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.ParentFolderId());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* _from_EmailFolder(PyObject* /*unused*/, PyObject* arg) noexcept
{
try
{
auto return_value = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg);
return py::convert(return_value.as<winrt::Windows::ApplicationModel::Email::EmailFolder>());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyMethodDef _methods_EmailFolder[] = {
{ "create_folder_async", reinterpret_cast<PyCFunction>(EmailFolder_CreateFolderAsync), METH_VARARGS, nullptr },
{ "delete_async", reinterpret_cast<PyCFunction>(EmailFolder_DeleteAsync), METH_VARARGS, nullptr },
{ "find_child_folders_async", reinterpret_cast<PyCFunction>(EmailFolder_FindChildFoldersAsync), METH_VARARGS, nullptr },
{ "get_conversation_reader", reinterpret_cast<PyCFunction>(EmailFolder_GetConversationReader), METH_VARARGS, nullptr },
{ "get_message_async", reinterpret_cast<PyCFunction>(EmailFolder_GetMessageAsync), METH_VARARGS, nullptr },
{ "get_message_counts_async", reinterpret_cast<PyCFunction>(EmailFolder_GetMessageCountsAsync), METH_VARARGS, nullptr },
{ "get_message_reader", reinterpret_cast<PyCFunction>(EmailFolder_GetMessageReader), METH_VARARGS, nullptr },
{ "save_message_async", reinterpret_cast<PyCFunction>(EmailFolder_SaveMessageAsync), METH_VARARGS, nullptr },
{ "try_move_async", reinterpret_cast<PyCFunction>(EmailFolder_TryMoveAsync), METH_VARARGS, nullptr },
{ "try_save_async", reinterpret_cast<PyCFunction>(EmailFolder_TrySaveAsync), METH_VARARGS, nullptr },
{ "_from", reinterpret_cast<PyCFunction>(_from_EmailFolder), METH_O | METH_STATIC, nullptr },
{ }
};
static PyGetSetDef _getset_EmailFolder[] = {
{ "remote_id", reinterpret_cast<getter>(EmailFolder_get_RemoteId), reinterpret_cast<setter>(EmailFolder_put_RemoteId), nullptr, nullptr },
{ "last_successful_sync_time", reinterpret_cast<getter>(EmailFolder_get_LastSuccessfulSyncTime), reinterpret_cast<setter>(EmailFolder_put_LastSuccessfulSyncTime), nullptr, nullptr },
{ "is_sync_enabled", reinterpret_cast<getter>(EmailFolder_get_IsSyncEnabled), reinterpret_cast<setter>(EmailFolder_put_IsSyncEnabled), nullptr, nullptr },
{ "display_name", reinterpret_cast<getter>(EmailFolder_get_DisplayName), reinterpret_cast<setter>(EmailFolder_put_DisplayName), nullptr, nullptr },
{ "id", reinterpret_cast<getter>(EmailFolder_get_Id), nullptr, nullptr, nullptr },
{ "kind", reinterpret_cast<getter>(EmailFolder_get_Kind), nullptr, nullptr, nullptr },
{ "mailbox_id", reinterpret_cast<getter>(EmailFolder_get_MailboxId), nullptr, nullptr, nullptr },
{ "parent_folder_id", reinterpret_cast<getter>(EmailFolder_get_ParentFolderId), nullptr, nullptr, nullptr },
{ }
};
static PyType_Slot _type_slots_EmailFolder[] =
{
{ Py_tp_new, _new_EmailFolder },
{ Py_tp_dealloc, _dealloc_EmailFolder },
{ Py_tp_methods, _methods_EmailFolder },
{ Py_tp_getset, _getset_EmailFolder },
{ },
};
static PyType_Spec _type_spec_EmailFolder =
{
"_winsdk_Windows_ApplicationModel_Email.EmailFolder",
sizeof(py::wrapper::Windows::ApplicationModel::Email::EmailFolder),
0,
Py_TPFLAGS_DEFAULT,
_type_slots_EmailFolder
};
// ----- EmailIrmInfo class --------------------
constexpr const char* const _type_name_EmailIrmInfo = "EmailIrmInfo";
static PyObject* _new_EmailIrmInfo(PyTypeObject* type, PyObject* args, PyObject* kwds) noexcept
{
if (kwds != nullptr)
{
py::set_invalid_kwd_args_error();
return nullptr;
}
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::Windows::Foundation::DateTime>(args, 0);
auto param1 = py::convert_to<winrt::Windows::ApplicationModel::Email::EmailIrmTemplate>(args, 1);
winrt::Windows::ApplicationModel::Email::EmailIrmInfo instance{ param0, param1 };
return py::wrap(instance, type);
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else if (arg_count == 0)
{
try
{
winrt::Windows::ApplicationModel::Email::EmailIrmInfo instance{ };
return py::wrap(instance, type);
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static void _dealloc_EmailIrmInfo(py::wrapper::Windows::ApplicationModel::Email::EmailIrmInfo* self)
{
auto hash_value = std::hash<winrt::Windows::Foundation::IInspectable>{}(self->obj);
py::wrapped_instance(hash_value, nullptr);
self->obj = nullptr;
}
static PyObject* EmailIrmInfo_get_CanRemoveIrmOnResponse(py::wrapper::Windows::ApplicationModel::Email::EmailIrmInfo* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.CanRemoveIrmOnResponse());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailIrmInfo_put_CanRemoveIrmOnResponse(py::wrapper::Windows::ApplicationModel::Email::EmailIrmInfo* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<bool>(arg);
self->obj.CanRemoveIrmOnResponse(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailIrmInfo_get_CanPrintData(py::wrapper::Windows::ApplicationModel::Email::EmailIrmInfo* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.CanPrintData());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailIrmInfo_put_CanPrintData(py::wrapper::Windows::ApplicationModel::Email::EmailIrmInfo* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<bool>(arg);
self->obj.CanPrintData(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailIrmInfo_get_CanModifyRecipientsOnResponse(py::wrapper::Windows::ApplicationModel::Email::EmailIrmInfo* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.CanModifyRecipientsOnResponse());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailIrmInfo_put_CanModifyRecipientsOnResponse(py::wrapper::Windows::ApplicationModel::Email::EmailIrmInfo* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<bool>(arg);
self->obj.CanModifyRecipientsOnResponse(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailIrmInfo_get_CanForward(py::wrapper::Windows::ApplicationModel::Email::EmailIrmInfo* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.CanForward());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailIrmInfo_put_CanForward(py::wrapper::Windows::ApplicationModel::Email::EmailIrmInfo* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<bool>(arg);
self->obj.CanForward(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailIrmInfo_get_CanExtractData(py::wrapper::Windows::ApplicationModel::Email::EmailIrmInfo* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.CanExtractData());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailIrmInfo_put_CanExtractData(py::wrapper::Windows::ApplicationModel::Email::EmailIrmInfo* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<bool>(arg);
self->obj.CanExtractData(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailIrmInfo_get_CanReply(py::wrapper::Windows::ApplicationModel::Email::EmailIrmInfo* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.CanReply());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailIrmInfo_put_CanReply(py::wrapper::Windows::ApplicationModel::Email::EmailIrmInfo* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<bool>(arg);
self->obj.CanReply(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailIrmInfo_get_CanEdit(py::wrapper::Windows::ApplicationModel::Email::EmailIrmInfo* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.CanEdit());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailIrmInfo_put_CanEdit(py::wrapper::Windows::ApplicationModel::Email::EmailIrmInfo* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<bool>(arg);
self->obj.CanEdit(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailIrmInfo_get_Template(py::wrapper::Windows::ApplicationModel::Email::EmailIrmInfo* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Template());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailIrmInfo_put_Template(py::wrapper::Windows::ApplicationModel::Email::EmailIrmInfo* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::Windows::ApplicationModel::Email::EmailIrmTemplate>(arg);
self->obj.Template(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailIrmInfo_get_IsProgramaticAccessAllowed(py::wrapper::Windows::ApplicationModel::Email::EmailIrmInfo* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.IsProgramaticAccessAllowed());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailIrmInfo_put_IsProgramaticAccessAllowed(py::wrapper::Windows::ApplicationModel::Email::EmailIrmInfo* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<bool>(arg);
self->obj.IsProgramaticAccessAllowed(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailIrmInfo_get_IsIrmOriginator(py::wrapper::Windows::ApplicationModel::Email::EmailIrmInfo* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.IsIrmOriginator());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailIrmInfo_put_IsIrmOriginator(py::wrapper::Windows::ApplicationModel::Email::EmailIrmInfo* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<bool>(arg);
self->obj.IsIrmOriginator(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailIrmInfo_get_ExpirationDate(py::wrapper::Windows::ApplicationModel::Email::EmailIrmInfo* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.ExpirationDate());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailIrmInfo_put_ExpirationDate(py::wrapper::Windows::ApplicationModel::Email::EmailIrmInfo* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::Windows::Foundation::DateTime>(arg);
self->obj.ExpirationDate(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailIrmInfo_get_CanReplyAll(py::wrapper::Windows::ApplicationModel::Email::EmailIrmInfo* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.CanReplyAll());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailIrmInfo_put_CanReplyAll(py::wrapper::Windows::ApplicationModel::Email::EmailIrmInfo* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<bool>(arg);
self->obj.CanReplyAll(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* _from_EmailIrmInfo(PyObject* /*unused*/, PyObject* arg) noexcept
{
try
{
auto return_value = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg);
return py::convert(return_value.as<winrt::Windows::ApplicationModel::Email::EmailIrmInfo>());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyMethodDef _methods_EmailIrmInfo[] = {
{ "_from", reinterpret_cast<PyCFunction>(_from_EmailIrmInfo), METH_O | METH_STATIC, nullptr },
{ }
};
static PyGetSetDef _getset_EmailIrmInfo[] = {
{ "can_remove_irm_on_response", reinterpret_cast<getter>(EmailIrmInfo_get_CanRemoveIrmOnResponse), reinterpret_cast<setter>(EmailIrmInfo_put_CanRemoveIrmOnResponse), nullptr, nullptr },
{ "can_print_data", reinterpret_cast<getter>(EmailIrmInfo_get_CanPrintData), reinterpret_cast<setter>(EmailIrmInfo_put_CanPrintData), nullptr, nullptr },
{ "can_modify_recipients_on_response", reinterpret_cast<getter>(EmailIrmInfo_get_CanModifyRecipientsOnResponse), reinterpret_cast<setter>(EmailIrmInfo_put_CanModifyRecipientsOnResponse), nullptr, nullptr },
{ "can_forward", reinterpret_cast<getter>(EmailIrmInfo_get_CanForward), reinterpret_cast<setter>(EmailIrmInfo_put_CanForward), nullptr, nullptr },
{ "can_extract_data", reinterpret_cast<getter>(EmailIrmInfo_get_CanExtractData), reinterpret_cast<setter>(EmailIrmInfo_put_CanExtractData), nullptr, nullptr },
{ "can_reply", reinterpret_cast<getter>(EmailIrmInfo_get_CanReply), reinterpret_cast<setter>(EmailIrmInfo_put_CanReply), nullptr, nullptr },
{ "can_edit", reinterpret_cast<getter>(EmailIrmInfo_get_CanEdit), reinterpret_cast<setter>(EmailIrmInfo_put_CanEdit), nullptr, nullptr },
{ "template", reinterpret_cast<getter>(EmailIrmInfo_get_Template), reinterpret_cast<setter>(EmailIrmInfo_put_Template), nullptr, nullptr },
{ "is_programatic_access_allowed", reinterpret_cast<getter>(EmailIrmInfo_get_IsProgramaticAccessAllowed), reinterpret_cast<setter>(EmailIrmInfo_put_IsProgramaticAccessAllowed), nullptr, nullptr },
{ "is_irm_originator", reinterpret_cast<getter>(EmailIrmInfo_get_IsIrmOriginator), reinterpret_cast<setter>(EmailIrmInfo_put_IsIrmOriginator), nullptr, nullptr },
{ "expiration_date", reinterpret_cast<getter>(EmailIrmInfo_get_ExpirationDate), reinterpret_cast<setter>(EmailIrmInfo_put_ExpirationDate), nullptr, nullptr },
{ "can_reply_all", reinterpret_cast<getter>(EmailIrmInfo_get_CanReplyAll), reinterpret_cast<setter>(EmailIrmInfo_put_CanReplyAll), nullptr, nullptr },
{ }
};
static PyType_Slot _type_slots_EmailIrmInfo[] =
{
{ Py_tp_new, _new_EmailIrmInfo },
{ Py_tp_dealloc, _dealloc_EmailIrmInfo },
{ Py_tp_methods, _methods_EmailIrmInfo },
{ Py_tp_getset, _getset_EmailIrmInfo },
{ },
};
static PyType_Spec _type_spec_EmailIrmInfo =
{
"_winsdk_Windows_ApplicationModel_Email.EmailIrmInfo",
sizeof(py::wrapper::Windows::ApplicationModel::Email::EmailIrmInfo),
0,
Py_TPFLAGS_DEFAULT,
_type_slots_EmailIrmInfo
};
// ----- EmailIrmTemplate class --------------------
constexpr const char* const _type_name_EmailIrmTemplate = "EmailIrmTemplate";
static PyObject* _new_EmailIrmTemplate(PyTypeObject* type, PyObject* args, PyObject* kwds) noexcept
{
if (kwds != nullptr)
{
py::set_invalid_kwd_args_error();
return nullptr;
}
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 3)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
auto param1 = py::convert_to<winrt::hstring>(args, 1);
auto param2 = py::convert_to<winrt::hstring>(args, 2);
winrt::Windows::ApplicationModel::Email::EmailIrmTemplate instance{ param0, param1, param2 };
return py::wrap(instance, type);
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else if (arg_count == 0)
{
try
{
winrt::Windows::ApplicationModel::Email::EmailIrmTemplate instance{ };
return py::wrap(instance, type);
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static void _dealloc_EmailIrmTemplate(py::wrapper::Windows::ApplicationModel::Email::EmailIrmTemplate* self)
{
auto hash_value = std::hash<winrt::Windows::Foundation::IInspectable>{}(self->obj);
py::wrapped_instance(hash_value, nullptr);
self->obj = nullptr;
}
static PyObject* EmailIrmTemplate_get_Name(py::wrapper::Windows::ApplicationModel::Email::EmailIrmTemplate* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Name());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailIrmTemplate_put_Name(py::wrapper::Windows::ApplicationModel::Email::EmailIrmTemplate* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::hstring>(arg);
self->obj.Name(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailIrmTemplate_get_Id(py::wrapper::Windows::ApplicationModel::Email::EmailIrmTemplate* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Id());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailIrmTemplate_put_Id(py::wrapper::Windows::ApplicationModel::Email::EmailIrmTemplate* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::hstring>(arg);
self->obj.Id(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailIrmTemplate_get_Description(py::wrapper::Windows::ApplicationModel::Email::EmailIrmTemplate* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Description());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailIrmTemplate_put_Description(py::wrapper::Windows::ApplicationModel::Email::EmailIrmTemplate* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::hstring>(arg);
self->obj.Description(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* _from_EmailIrmTemplate(PyObject* /*unused*/, PyObject* arg) noexcept
{
try
{
auto return_value = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg);
return py::convert(return_value.as<winrt::Windows::ApplicationModel::Email::EmailIrmTemplate>());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyMethodDef _methods_EmailIrmTemplate[] = {
{ "_from", reinterpret_cast<PyCFunction>(_from_EmailIrmTemplate), METH_O | METH_STATIC, nullptr },
{ }
};
static PyGetSetDef _getset_EmailIrmTemplate[] = {
{ "name", reinterpret_cast<getter>(EmailIrmTemplate_get_Name), reinterpret_cast<setter>(EmailIrmTemplate_put_Name), nullptr, nullptr },
{ "id", reinterpret_cast<getter>(EmailIrmTemplate_get_Id), reinterpret_cast<setter>(EmailIrmTemplate_put_Id), nullptr, nullptr },
{ "description", reinterpret_cast<getter>(EmailIrmTemplate_get_Description), reinterpret_cast<setter>(EmailIrmTemplate_put_Description), nullptr, nullptr },
{ }
};
static PyType_Slot _type_slots_EmailIrmTemplate[] =
{
{ Py_tp_new, _new_EmailIrmTemplate },
{ Py_tp_dealloc, _dealloc_EmailIrmTemplate },
{ Py_tp_methods, _methods_EmailIrmTemplate },
{ Py_tp_getset, _getset_EmailIrmTemplate },
{ },
};
static PyType_Spec _type_spec_EmailIrmTemplate =
{
"_winsdk_Windows_ApplicationModel_Email.EmailIrmTemplate",
sizeof(py::wrapper::Windows::ApplicationModel::Email::EmailIrmTemplate),
0,
Py_TPFLAGS_DEFAULT,
_type_slots_EmailIrmTemplate
};
// ----- EmailItemCounts class --------------------
constexpr const char* const _type_name_EmailItemCounts = "EmailItemCounts";
static PyObject* _new_EmailItemCounts(PyTypeObject* type, PyObject* args, PyObject* kwds) noexcept
{
py::set_invalid_activation_error(_type_name_EmailItemCounts);
return nullptr;
}
static void _dealloc_EmailItemCounts(py::wrapper::Windows::ApplicationModel::Email::EmailItemCounts* self)
{
auto hash_value = std::hash<winrt::Windows::Foundation::IInspectable>{}(self->obj);
py::wrapped_instance(hash_value, nullptr);
self->obj = nullptr;
}
static PyObject* EmailItemCounts_get_Flagged(py::wrapper::Windows::ApplicationModel::Email::EmailItemCounts* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Flagged());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* EmailItemCounts_get_Important(py::wrapper::Windows::ApplicationModel::Email::EmailItemCounts* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Important());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* EmailItemCounts_get_Total(py::wrapper::Windows::ApplicationModel::Email::EmailItemCounts* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Total());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* EmailItemCounts_get_Unread(py::wrapper::Windows::ApplicationModel::Email::EmailItemCounts* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Unread());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* _from_EmailItemCounts(PyObject* /*unused*/, PyObject* arg) noexcept
{
try
{
auto return_value = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg);
return py::convert(return_value.as<winrt::Windows::ApplicationModel::Email::EmailItemCounts>());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyMethodDef _methods_EmailItemCounts[] = {
{ "_from", reinterpret_cast<PyCFunction>(_from_EmailItemCounts), METH_O | METH_STATIC, nullptr },
{ }
};
static PyGetSetDef _getset_EmailItemCounts[] = {
{ "flagged", reinterpret_cast<getter>(EmailItemCounts_get_Flagged), nullptr, nullptr, nullptr },
{ "important", reinterpret_cast<getter>(EmailItemCounts_get_Important), nullptr, nullptr, nullptr },
{ "total", reinterpret_cast<getter>(EmailItemCounts_get_Total), nullptr, nullptr, nullptr },
{ "unread", reinterpret_cast<getter>(EmailItemCounts_get_Unread), nullptr, nullptr, nullptr },
{ }
};
static PyType_Slot _type_slots_EmailItemCounts[] =
{
{ Py_tp_new, _new_EmailItemCounts },
{ Py_tp_dealloc, _dealloc_EmailItemCounts },
{ Py_tp_methods, _methods_EmailItemCounts },
{ Py_tp_getset, _getset_EmailItemCounts },
{ },
};
static PyType_Spec _type_spec_EmailItemCounts =
{
"_winsdk_Windows_ApplicationModel_Email.EmailItemCounts",
sizeof(py::wrapper::Windows::ApplicationModel::Email::EmailItemCounts),
0,
Py_TPFLAGS_DEFAULT,
_type_slots_EmailItemCounts
};
// ----- EmailMailbox class --------------------
constexpr const char* const _type_name_EmailMailbox = "EmailMailbox";
static PyObject* _new_EmailMailbox(PyTypeObject* type, PyObject* args, PyObject* kwds) noexcept
{
py::set_invalid_activation_error(_type_name_EmailMailbox);
return nullptr;
}
static void _dealloc_EmailMailbox(py::wrapper::Windows::ApplicationModel::Email::EmailMailbox* self)
{
auto hash_value = std::hash<winrt::Windows::Foundation::IInspectable>{}(self->obj);
py::wrapped_instance(hash_value, nullptr);
self->obj = nullptr;
}
static PyObject* EmailMailbox_ChangeMessageFlagStateAsync(py::wrapper::Windows::ApplicationModel::Email::EmailMailbox* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
auto param1 = py::convert_to<winrt::Windows::ApplicationModel::Email::EmailFlagState>(args, 1);
return py::convert(self->obj.ChangeMessageFlagStateAsync(param0, param1));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* EmailMailbox_CreateResponseMessageAsync(py::wrapper::Windows::ApplicationModel::Email::EmailMailbox* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 5)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
auto param1 = py::convert_to<winrt::Windows::ApplicationModel::Email::EmailMessageResponseKind>(args, 1);
auto param2 = py::convert_to<winrt::hstring>(args, 2);
auto param3 = py::convert_to<winrt::Windows::ApplicationModel::Email::EmailMessageBodyKind>(args, 3);
auto param4 = py::convert_to<winrt::hstring>(args, 4);
return py::convert(self->obj.CreateResponseMessageAsync(param0, param1, param2, param3, param4));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* EmailMailbox_DeleteAsync(py::wrapper::Windows::ApplicationModel::Email::EmailMailbox* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 0)
{
try
{
return py::convert(self->obj.DeleteAsync());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* EmailMailbox_DeleteMessageAsync(py::wrapper::Windows::ApplicationModel::Email::EmailMailbox* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
return py::convert(self->obj.DeleteMessageAsync(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* EmailMailbox_DownloadAttachmentAsync(py::wrapper::Windows::ApplicationModel::Email::EmailMailbox* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
return py::convert(self->obj.DownloadAttachmentAsync(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* EmailMailbox_DownloadMessageAsync(py::wrapper::Windows::ApplicationModel::Email::EmailMailbox* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
return py::convert(self->obj.DownloadMessageAsync(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* EmailMailbox_GetChangeTracker(py::wrapper::Windows::ApplicationModel::Email::EmailMailbox* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
return py::convert(self->obj.GetChangeTracker(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* EmailMailbox_GetConversationAsync(py::wrapper::Windows::ApplicationModel::Email::EmailMailbox* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
return py::convert(self->obj.GetConversationAsync(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* EmailMailbox_GetConversationReader(py::wrapper::Windows::ApplicationModel::Email::EmailMailbox* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 0)
{
try
{
return py::convert(self->obj.GetConversationReader());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::Windows::ApplicationModel::Email::EmailQueryOptions>(args, 0);
return py::convert(self->obj.GetConversationReader(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* EmailMailbox_GetFolderAsync(py::wrapper::Windows::ApplicationModel::Email::EmailMailbox* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
return py::convert(self->obj.GetFolderAsync(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* EmailMailbox_GetMessageAsync(py::wrapper::Windows::ApplicationModel::Email::EmailMailbox* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
return py::convert(self->obj.GetMessageAsync(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* EmailMailbox_GetMessageReader(py::wrapper::Windows::ApplicationModel::Email::EmailMailbox* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 0)
{
try
{
return py::convert(self->obj.GetMessageReader());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::Windows::ApplicationModel::Email::EmailQueryOptions>(args, 0);
return py::convert(self->obj.GetMessageReader(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* EmailMailbox_GetSpecialFolderAsync(py::wrapper::Windows::ApplicationModel::Email::EmailMailbox* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::Windows::ApplicationModel::Email::EmailSpecialFolderKind>(args, 0);
return py::convert(self->obj.GetSpecialFolderAsync(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* EmailMailbox_MarkFolderAsSeenAsync(py::wrapper::Windows::ApplicationModel::Email::EmailMailbox* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
return py::convert(self->obj.MarkFolderAsSeenAsync(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* EmailMailbox_MarkFolderSyncEnabledAsync(py::wrapper::Windows::ApplicationModel::Email::EmailMailbox* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
auto param1 = py::convert_to<bool>(args, 1);
return py::convert(self->obj.MarkFolderSyncEnabledAsync(param0, param1));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* EmailMailbox_MarkMessageAsSeenAsync(py::wrapper::Windows::ApplicationModel::Email::EmailMailbox* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
return py::convert(self->obj.MarkMessageAsSeenAsync(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* EmailMailbox_MarkMessageReadAsync(py::wrapper::Windows::ApplicationModel::Email::EmailMailbox* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
auto param1 = py::convert_to<bool>(args, 1);
return py::convert(self->obj.MarkMessageReadAsync(param0, param1));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* EmailMailbox_RegisterSyncManagerAsync(py::wrapper::Windows::ApplicationModel::Email::EmailMailbox* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 0)
{
try
{
return py::convert(self->obj.RegisterSyncManagerAsync());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* EmailMailbox_ResolveRecipientsAsync(py::wrapper::Windows::ApplicationModel::Email::EmailMailbox* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::Windows::Foundation::Collections::IIterable<winrt::hstring>>(args, 0);
return py::convert(self->obj.ResolveRecipientsAsync(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* EmailMailbox_SaveAsync(py::wrapper::Windows::ApplicationModel::Email::EmailMailbox* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 0)
{
try
{
return py::convert(self->obj.SaveAsync());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* EmailMailbox_SaveDraftAsync(py::wrapper::Windows::ApplicationModel::Email::EmailMailbox* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::Windows::ApplicationModel::Email::EmailMessage>(args, 0);
return py::convert(self->obj.SaveDraftAsync(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* EmailMailbox_SendMessageAsync(py::wrapper::Windows::ApplicationModel::Email::EmailMailbox* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::Windows::ApplicationModel::Email::EmailMessage>(args, 0);
return py::convert(self->obj.SendMessageAsync(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::Windows::ApplicationModel::Email::EmailMessage>(args, 0);
auto param1 = py::convert_to<bool>(args, 1);
return py::convert(self->obj.SendMessageAsync(param0, param1));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* EmailMailbox_TryCreateFolderAsync(py::wrapper::Windows::ApplicationModel::Email::EmailMailbox* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
auto param1 = py::convert_to<winrt::hstring>(args, 1);
return py::convert(self->obj.TryCreateFolderAsync(param0, param1));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* EmailMailbox_TryDeleteFolderAsync(py::wrapper::Windows::ApplicationModel::Email::EmailMailbox* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
return py::convert(self->obj.TryDeleteFolderAsync(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* EmailMailbox_TryEmptyFolderAsync(py::wrapper::Windows::ApplicationModel::Email::EmailMailbox* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
return py::convert(self->obj.TryEmptyFolderAsync(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* EmailMailbox_TryForwardMeetingAsync(py::wrapper::Windows::ApplicationModel::Email::EmailMailbox* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 6)
{
try
{
auto param0 = py::convert_to<winrt::Windows::ApplicationModel::Email::EmailMessage>(args, 0);
auto param1 = py::convert_to<winrt::Windows::Foundation::Collections::IIterable<winrt::Windows::ApplicationModel::Email::EmailRecipient>>(args, 1);
auto param2 = py::convert_to<winrt::hstring>(args, 2);
auto param3 = py::convert_to<winrt::Windows::ApplicationModel::Email::EmailMessageBodyKind>(args, 3);
auto param4 = py::convert_to<winrt::hstring>(args, 4);
auto param5 = py::convert_to<winrt::hstring>(args, 5);
return py::convert(self->obj.TryForwardMeetingAsync(param0, param1, param2, param3, param4, param5));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* EmailMailbox_TryGetAutoReplySettingsAsync(py::wrapper::Windows::ApplicationModel::Email::EmailMailbox* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::Windows::ApplicationModel::Email::EmailMailboxAutoReplyMessageResponseKind>(args, 0);
return py::convert(self->obj.TryGetAutoReplySettingsAsync(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* EmailMailbox_TryMoveFolderAsync(py::wrapper::Windows::ApplicationModel::Email::EmailMailbox* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
auto param1 = py::convert_to<winrt::hstring>(args, 1);
return py::convert(self->obj.TryMoveFolderAsync(param0, param1));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else if (arg_count == 3)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
auto param1 = py::convert_to<winrt::hstring>(args, 1);
auto param2 = py::convert_to<winrt::hstring>(args, 2);
return py::convert(self->obj.TryMoveFolderAsync(param0, param1, param2));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* EmailMailbox_TryMoveMessageAsync(py::wrapper::Windows::ApplicationModel::Email::EmailMailbox* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
auto param1 = py::convert_to<winrt::hstring>(args, 1);
return py::convert(self->obj.TryMoveMessageAsync(param0, param1));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* EmailMailbox_TryProposeNewTimeForMeetingAsync(py::wrapper::Windows::ApplicationModel::Email::EmailMailbox* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 5)
{
try
{
auto param0 = py::convert_to<winrt::Windows::ApplicationModel::Email::EmailMessage>(args, 0);
auto param1 = py::convert_to<winrt::Windows::Foundation::DateTime>(args, 1);
auto param2 = py::convert_to<winrt::Windows::Foundation::TimeSpan>(args, 2);
auto param3 = py::convert_to<winrt::hstring>(args, 3);
auto param4 = py::convert_to<winrt::hstring>(args, 4);
return py::convert(self->obj.TryProposeNewTimeForMeetingAsync(param0, param1, param2, param3, param4));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* EmailMailbox_TrySetAutoReplySettingsAsync(py::wrapper::Windows::ApplicationModel::Email::EmailMailbox* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::Windows::ApplicationModel::Email::EmailMailboxAutoReplySettings>(args, 0);
return py::convert(self->obj.TrySetAutoReplySettingsAsync(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* EmailMailbox_TryUpdateMeetingResponseAsync(py::wrapper::Windows::ApplicationModel::Email::EmailMailbox* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 5)
{
try
{
auto param0 = py::convert_to<winrt::Windows::ApplicationModel::Email::EmailMessage>(args, 0);
auto param1 = py::convert_to<winrt::Windows::ApplicationModel::Email::EmailMeetingResponseType>(args, 1);
auto param2 = py::convert_to<winrt::hstring>(args, 2);
auto param3 = py::convert_to<winrt::hstring>(args, 3);
auto param4 = py::convert_to<bool>(args, 4);
return py::convert(self->obj.TryUpdateMeetingResponseAsync(param0, param1, param2, param3, param4));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* EmailMailbox_ValidateCertificatesAsync(py::wrapper::Windows::ApplicationModel::Email::EmailMailbox* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::Windows::Foundation::Collections::IIterable<winrt::Windows::Security::Cryptography::Certificates::Certificate>>(args, 0);
return py::convert(self->obj.ValidateCertificatesAsync(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* EmailMailbox_get_OtherAppWriteAccess(py::wrapper::Windows::ApplicationModel::Email::EmailMailbox* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.OtherAppWriteAccess());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailMailbox_put_OtherAppWriteAccess(py::wrapper::Windows::ApplicationModel::Email::EmailMailbox* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::Windows::ApplicationModel::Email::EmailMailboxOtherAppWriteAccess>(arg);
self->obj.OtherAppWriteAccess(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailMailbox_get_MailAddress(py::wrapper::Windows::ApplicationModel::Email::EmailMailbox* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.MailAddress());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailMailbox_put_MailAddress(py::wrapper::Windows::ApplicationModel::Email::EmailMailbox* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::hstring>(arg);
self->obj.MailAddress(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailMailbox_get_OtherAppReadAccess(py::wrapper::Windows::ApplicationModel::Email::EmailMailbox* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.OtherAppReadAccess());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailMailbox_put_OtherAppReadAccess(py::wrapper::Windows::ApplicationModel::Email::EmailMailbox* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::Windows::ApplicationModel::Email::EmailMailboxOtherAppReadAccess>(arg);
self->obj.OtherAppReadAccess(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailMailbox_get_DisplayName(py::wrapper::Windows::ApplicationModel::Email::EmailMailbox* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.DisplayName());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailMailbox_put_DisplayName(py::wrapper::Windows::ApplicationModel::Email::EmailMailbox* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::hstring>(arg);
self->obj.DisplayName(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailMailbox_get_Id(py::wrapper::Windows::ApplicationModel::Email::EmailMailbox* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Id());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* EmailMailbox_get_IsDataEncryptedUnderLock(py::wrapper::Windows::ApplicationModel::Email::EmailMailbox* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.IsDataEncryptedUnderLock());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* EmailMailbox_get_IsOwnedByCurrentApp(py::wrapper::Windows::ApplicationModel::Email::EmailMailbox* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.IsOwnedByCurrentApp());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* EmailMailbox_get_MailAddressAliases(py::wrapper::Windows::ApplicationModel::Email::EmailMailbox* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.MailAddressAliases());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* EmailMailbox_get_Capabilities(py::wrapper::Windows::ApplicationModel::Email::EmailMailbox* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Capabilities());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* EmailMailbox_get_ChangeTracker(py::wrapper::Windows::ApplicationModel::Email::EmailMailbox* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.ChangeTracker());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* EmailMailbox_get_Policies(py::wrapper::Windows::ApplicationModel::Email::EmailMailbox* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Policies());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* EmailMailbox_get_SourceDisplayName(py::wrapper::Windows::ApplicationModel::Email::EmailMailbox* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.SourceDisplayName());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* EmailMailbox_get_SyncManager(py::wrapper::Windows::ApplicationModel::Email::EmailMailbox* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.SyncManager());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* EmailMailbox_get_UserDataAccountId(py::wrapper::Windows::ApplicationModel::Email::EmailMailbox* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.UserDataAccountId());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* EmailMailbox_get_LinkedMailboxId(py::wrapper::Windows::ApplicationModel::Email::EmailMailbox* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.LinkedMailboxId());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* EmailMailbox_get_NetworkAccountId(py::wrapper::Windows::ApplicationModel::Email::EmailMailbox* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.NetworkAccountId());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* EmailMailbox_get_NetworkId(py::wrapper::Windows::ApplicationModel::Email::EmailMailbox* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.NetworkId());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* EmailMailbox_add_MailboxChanged(py::wrapper::Windows::ApplicationModel::Email::EmailMailbox* self, PyObject* arg) noexcept
{
try
{
auto param0 = py::convert_to<winrt::Windows::Foundation::TypedEventHandler<winrt::Windows::ApplicationModel::Email::EmailMailbox, winrt::Windows::ApplicationModel::Email::EmailMailboxChangedEventArgs>>(arg);
return py::convert(self->obj.MailboxChanged(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* EmailMailbox_remove_MailboxChanged(py::wrapper::Windows::ApplicationModel::Email::EmailMailbox* self, PyObject* arg) noexcept
{
try
{
auto param0 = py::convert_to<winrt::event_token>(arg);
self->obj.MailboxChanged(param0);
Py_RETURN_NONE;
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* _from_EmailMailbox(PyObject* /*unused*/, PyObject* arg) noexcept
{
try
{
auto return_value = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg);
return py::convert(return_value.as<winrt::Windows::ApplicationModel::Email::EmailMailbox>());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyMethodDef _methods_EmailMailbox[] = {
{ "change_message_flag_state_async", reinterpret_cast<PyCFunction>(EmailMailbox_ChangeMessageFlagStateAsync), METH_VARARGS, nullptr },
{ "create_response_message_async", reinterpret_cast<PyCFunction>(EmailMailbox_CreateResponseMessageAsync), METH_VARARGS, nullptr },
{ "delete_async", reinterpret_cast<PyCFunction>(EmailMailbox_DeleteAsync), METH_VARARGS, nullptr },
{ "delete_message_async", reinterpret_cast<PyCFunction>(EmailMailbox_DeleteMessageAsync), METH_VARARGS, nullptr },
{ "download_attachment_async", reinterpret_cast<PyCFunction>(EmailMailbox_DownloadAttachmentAsync), METH_VARARGS, nullptr },
{ "download_message_async", reinterpret_cast<PyCFunction>(EmailMailbox_DownloadMessageAsync), METH_VARARGS, nullptr },
{ "get_change_tracker", reinterpret_cast<PyCFunction>(EmailMailbox_GetChangeTracker), METH_VARARGS, nullptr },
{ "get_conversation_async", reinterpret_cast<PyCFunction>(EmailMailbox_GetConversationAsync), METH_VARARGS, nullptr },
{ "get_conversation_reader", reinterpret_cast<PyCFunction>(EmailMailbox_GetConversationReader), METH_VARARGS, nullptr },
{ "get_folder_async", reinterpret_cast<PyCFunction>(EmailMailbox_GetFolderAsync), METH_VARARGS, nullptr },
{ "get_message_async", reinterpret_cast<PyCFunction>(EmailMailbox_GetMessageAsync), METH_VARARGS, nullptr },
{ "get_message_reader", reinterpret_cast<PyCFunction>(EmailMailbox_GetMessageReader), METH_VARARGS, nullptr },
{ "get_special_folder_async", reinterpret_cast<PyCFunction>(EmailMailbox_GetSpecialFolderAsync), METH_VARARGS, nullptr },
{ "mark_folder_as_seen_async", reinterpret_cast<PyCFunction>(EmailMailbox_MarkFolderAsSeenAsync), METH_VARARGS, nullptr },
{ "mark_folder_sync_enabled_async", reinterpret_cast<PyCFunction>(EmailMailbox_MarkFolderSyncEnabledAsync), METH_VARARGS, nullptr },
{ "mark_message_as_seen_async", reinterpret_cast<PyCFunction>(EmailMailbox_MarkMessageAsSeenAsync), METH_VARARGS, nullptr },
{ "mark_message_read_async", reinterpret_cast<PyCFunction>(EmailMailbox_MarkMessageReadAsync), METH_VARARGS, nullptr },
{ "register_sync_manager_async", reinterpret_cast<PyCFunction>(EmailMailbox_RegisterSyncManagerAsync), METH_VARARGS, nullptr },
{ "resolve_recipients_async", reinterpret_cast<PyCFunction>(EmailMailbox_ResolveRecipientsAsync), METH_VARARGS, nullptr },
{ "save_async", reinterpret_cast<PyCFunction>(EmailMailbox_SaveAsync), METH_VARARGS, nullptr },
{ "save_draft_async", reinterpret_cast<PyCFunction>(EmailMailbox_SaveDraftAsync), METH_VARARGS, nullptr },
{ "send_message_async", reinterpret_cast<PyCFunction>(EmailMailbox_SendMessageAsync), METH_VARARGS, nullptr },
{ "try_create_folder_async", reinterpret_cast<PyCFunction>(EmailMailbox_TryCreateFolderAsync), METH_VARARGS, nullptr },
{ "try_delete_folder_async", reinterpret_cast<PyCFunction>(EmailMailbox_TryDeleteFolderAsync), METH_VARARGS, nullptr },
{ "try_empty_folder_async", reinterpret_cast<PyCFunction>(EmailMailbox_TryEmptyFolderAsync), METH_VARARGS, nullptr },
{ "try_forward_meeting_async", reinterpret_cast<PyCFunction>(EmailMailbox_TryForwardMeetingAsync), METH_VARARGS, nullptr },
{ "try_get_auto_reply_settings_async", reinterpret_cast<PyCFunction>(EmailMailbox_TryGetAutoReplySettingsAsync), METH_VARARGS, nullptr },
{ "try_move_folder_async", reinterpret_cast<PyCFunction>(EmailMailbox_TryMoveFolderAsync), METH_VARARGS, nullptr },
{ "try_move_message_async", reinterpret_cast<PyCFunction>(EmailMailbox_TryMoveMessageAsync), METH_VARARGS, nullptr },
{ "try_propose_new_time_for_meeting_async", reinterpret_cast<PyCFunction>(EmailMailbox_TryProposeNewTimeForMeetingAsync), METH_VARARGS, nullptr },
{ "try_set_auto_reply_settings_async", reinterpret_cast<PyCFunction>(EmailMailbox_TrySetAutoReplySettingsAsync), METH_VARARGS, nullptr },
{ "try_update_meeting_response_async", reinterpret_cast<PyCFunction>(EmailMailbox_TryUpdateMeetingResponseAsync), METH_VARARGS, nullptr },
{ "validate_certificates_async", reinterpret_cast<PyCFunction>(EmailMailbox_ValidateCertificatesAsync), METH_VARARGS, nullptr },
{ "add_mailbox_changed", reinterpret_cast<PyCFunction>(EmailMailbox_add_MailboxChanged), METH_O, nullptr },
{ "remove_mailbox_changed", reinterpret_cast<PyCFunction>(EmailMailbox_remove_MailboxChanged), METH_O, nullptr },
{ "_from", reinterpret_cast<PyCFunction>(_from_EmailMailbox), METH_O | METH_STATIC, nullptr },
{ }
};
static PyGetSetDef _getset_EmailMailbox[] = {
{ "other_app_write_access", reinterpret_cast<getter>(EmailMailbox_get_OtherAppWriteAccess), reinterpret_cast<setter>(EmailMailbox_put_OtherAppWriteAccess), nullptr, nullptr },
{ "mail_address", reinterpret_cast<getter>(EmailMailbox_get_MailAddress), reinterpret_cast<setter>(EmailMailbox_put_MailAddress), nullptr, nullptr },
{ "other_app_read_access", reinterpret_cast<getter>(EmailMailbox_get_OtherAppReadAccess), reinterpret_cast<setter>(EmailMailbox_put_OtherAppReadAccess), nullptr, nullptr },
{ "display_name", reinterpret_cast<getter>(EmailMailbox_get_DisplayName), reinterpret_cast<setter>(EmailMailbox_put_DisplayName), nullptr, nullptr },
{ "id", reinterpret_cast<getter>(EmailMailbox_get_Id), nullptr, nullptr, nullptr },
{ "is_data_encrypted_under_lock", reinterpret_cast<getter>(EmailMailbox_get_IsDataEncryptedUnderLock), nullptr, nullptr, nullptr },
{ "is_owned_by_current_app", reinterpret_cast<getter>(EmailMailbox_get_IsOwnedByCurrentApp), nullptr, nullptr, nullptr },
{ "mail_address_aliases", reinterpret_cast<getter>(EmailMailbox_get_MailAddressAliases), nullptr, nullptr, nullptr },
{ "capabilities", reinterpret_cast<getter>(EmailMailbox_get_Capabilities), nullptr, nullptr, nullptr },
{ "change_tracker", reinterpret_cast<getter>(EmailMailbox_get_ChangeTracker), nullptr, nullptr, nullptr },
{ "policies", reinterpret_cast<getter>(EmailMailbox_get_Policies), nullptr, nullptr, nullptr },
{ "source_display_name", reinterpret_cast<getter>(EmailMailbox_get_SourceDisplayName), nullptr, nullptr, nullptr },
{ "sync_manager", reinterpret_cast<getter>(EmailMailbox_get_SyncManager), nullptr, nullptr, nullptr },
{ "user_data_account_id", reinterpret_cast<getter>(EmailMailbox_get_UserDataAccountId), nullptr, nullptr, nullptr },
{ "linked_mailbox_id", reinterpret_cast<getter>(EmailMailbox_get_LinkedMailboxId), nullptr, nullptr, nullptr },
{ "network_account_id", reinterpret_cast<getter>(EmailMailbox_get_NetworkAccountId), nullptr, nullptr, nullptr },
{ "network_id", reinterpret_cast<getter>(EmailMailbox_get_NetworkId), nullptr, nullptr, nullptr },
{ }
};
static PyType_Slot _type_slots_EmailMailbox[] =
{
{ Py_tp_new, _new_EmailMailbox },
{ Py_tp_dealloc, _dealloc_EmailMailbox },
{ Py_tp_methods, _methods_EmailMailbox },
{ Py_tp_getset, _getset_EmailMailbox },
{ },
};
static PyType_Spec _type_spec_EmailMailbox =
{
"_winsdk_Windows_ApplicationModel_Email.EmailMailbox",
sizeof(py::wrapper::Windows::ApplicationModel::Email::EmailMailbox),
0,
Py_TPFLAGS_DEFAULT,
_type_slots_EmailMailbox
};
// ----- EmailMailboxAction class --------------------
constexpr const char* const _type_name_EmailMailboxAction = "EmailMailboxAction";
static PyObject* _new_EmailMailboxAction(PyTypeObject* type, PyObject* args, PyObject* kwds) noexcept
{
py::set_invalid_activation_error(_type_name_EmailMailboxAction);
return nullptr;
}
static void _dealloc_EmailMailboxAction(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxAction* self)
{
auto hash_value = std::hash<winrt::Windows::Foundation::IInspectable>{}(self->obj);
py::wrapped_instance(hash_value, nullptr);
self->obj = nullptr;
}
static PyObject* EmailMailboxAction_get_ChangeNumber(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxAction* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.ChangeNumber());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* EmailMailboxAction_get_Kind(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxAction* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Kind());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* _from_EmailMailboxAction(PyObject* /*unused*/, PyObject* arg) noexcept
{
try
{
auto return_value = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg);
return py::convert(return_value.as<winrt::Windows::ApplicationModel::Email::EmailMailboxAction>());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyMethodDef _methods_EmailMailboxAction[] = {
{ "_from", reinterpret_cast<PyCFunction>(_from_EmailMailboxAction), METH_O | METH_STATIC, nullptr },
{ }
};
static PyGetSetDef _getset_EmailMailboxAction[] = {
{ "change_number", reinterpret_cast<getter>(EmailMailboxAction_get_ChangeNumber), nullptr, nullptr, nullptr },
{ "kind", reinterpret_cast<getter>(EmailMailboxAction_get_Kind), nullptr, nullptr, nullptr },
{ }
};
static PyType_Slot _type_slots_EmailMailboxAction[] =
{
{ Py_tp_new, _new_EmailMailboxAction },
{ Py_tp_dealloc, _dealloc_EmailMailboxAction },
{ Py_tp_methods, _methods_EmailMailboxAction },
{ Py_tp_getset, _getset_EmailMailboxAction },
{ },
};
static PyType_Spec _type_spec_EmailMailboxAction =
{
"_winsdk_Windows_ApplicationModel_Email.EmailMailboxAction",
sizeof(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxAction),
0,
Py_TPFLAGS_DEFAULT,
_type_slots_EmailMailboxAction
};
// ----- EmailMailboxAutoReply class --------------------
constexpr const char* const _type_name_EmailMailboxAutoReply = "EmailMailboxAutoReply";
static PyObject* _new_EmailMailboxAutoReply(PyTypeObject* type, PyObject* args, PyObject* kwds) noexcept
{
py::set_invalid_activation_error(_type_name_EmailMailboxAutoReply);
return nullptr;
}
static void _dealloc_EmailMailboxAutoReply(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxAutoReply* self)
{
auto hash_value = std::hash<winrt::Windows::Foundation::IInspectable>{}(self->obj);
py::wrapped_instance(hash_value, nullptr);
self->obj = nullptr;
}
static PyObject* EmailMailboxAutoReply_get_Response(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxAutoReply* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Response());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailMailboxAutoReply_put_Response(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxAutoReply* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::hstring>(arg);
self->obj.Response(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailMailboxAutoReply_get_IsEnabled(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxAutoReply* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.IsEnabled());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailMailboxAutoReply_put_IsEnabled(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxAutoReply* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<bool>(arg);
self->obj.IsEnabled(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* _from_EmailMailboxAutoReply(PyObject* /*unused*/, PyObject* arg) noexcept
{
try
{
auto return_value = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg);
return py::convert(return_value.as<winrt::Windows::ApplicationModel::Email::EmailMailboxAutoReply>());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyMethodDef _methods_EmailMailboxAutoReply[] = {
{ "_from", reinterpret_cast<PyCFunction>(_from_EmailMailboxAutoReply), METH_O | METH_STATIC, nullptr },
{ }
};
static PyGetSetDef _getset_EmailMailboxAutoReply[] = {
{ "response", reinterpret_cast<getter>(EmailMailboxAutoReply_get_Response), reinterpret_cast<setter>(EmailMailboxAutoReply_put_Response), nullptr, nullptr },
{ "is_enabled", reinterpret_cast<getter>(EmailMailboxAutoReply_get_IsEnabled), reinterpret_cast<setter>(EmailMailboxAutoReply_put_IsEnabled), nullptr, nullptr },
{ }
};
static PyType_Slot _type_slots_EmailMailboxAutoReply[] =
{
{ Py_tp_new, _new_EmailMailboxAutoReply },
{ Py_tp_dealloc, _dealloc_EmailMailboxAutoReply },
{ Py_tp_methods, _methods_EmailMailboxAutoReply },
{ Py_tp_getset, _getset_EmailMailboxAutoReply },
{ },
};
static PyType_Spec _type_spec_EmailMailboxAutoReply =
{
"_winsdk_Windows_ApplicationModel_Email.EmailMailboxAutoReply",
sizeof(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxAutoReply),
0,
Py_TPFLAGS_DEFAULT,
_type_slots_EmailMailboxAutoReply
};
// ----- EmailMailboxAutoReplySettings class --------------------
constexpr const char* const _type_name_EmailMailboxAutoReplySettings = "EmailMailboxAutoReplySettings";
static PyObject* _new_EmailMailboxAutoReplySettings(PyTypeObject* type, PyObject* args, PyObject* kwds) noexcept
{
if (kwds != nullptr)
{
py::set_invalid_kwd_args_error();
return nullptr;
}
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 0)
{
try
{
winrt::Windows::ApplicationModel::Email::EmailMailboxAutoReplySettings instance{ };
return py::wrap(instance, type);
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static void _dealloc_EmailMailboxAutoReplySettings(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxAutoReplySettings* self)
{
auto hash_value = std::hash<winrt::Windows::Foundation::IInspectable>{}(self->obj);
py::wrapped_instance(hash_value, nullptr);
self->obj = nullptr;
}
static PyObject* EmailMailboxAutoReplySettings_get_StartTime(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxAutoReplySettings* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.StartTime());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailMailboxAutoReplySettings_put_StartTime(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxAutoReplySettings* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::Windows::Foundation::IReference<winrt::Windows::Foundation::DateTime>>(arg);
self->obj.StartTime(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailMailboxAutoReplySettings_get_ResponseKind(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxAutoReplySettings* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.ResponseKind());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailMailboxAutoReplySettings_put_ResponseKind(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxAutoReplySettings* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::Windows::ApplicationModel::Email::EmailMailboxAutoReplyMessageResponseKind>(arg);
self->obj.ResponseKind(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailMailboxAutoReplySettings_get_IsEnabled(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxAutoReplySettings* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.IsEnabled());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailMailboxAutoReplySettings_put_IsEnabled(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxAutoReplySettings* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<bool>(arg);
self->obj.IsEnabled(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailMailboxAutoReplySettings_get_EndTime(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxAutoReplySettings* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.EndTime());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailMailboxAutoReplySettings_put_EndTime(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxAutoReplySettings* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::Windows::Foundation::IReference<winrt::Windows::Foundation::DateTime>>(arg);
self->obj.EndTime(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailMailboxAutoReplySettings_get_InternalReply(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxAutoReplySettings* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.InternalReply());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* EmailMailboxAutoReplySettings_get_KnownExternalReply(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxAutoReplySettings* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.KnownExternalReply());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* EmailMailboxAutoReplySettings_get_UnknownExternalReply(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxAutoReplySettings* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.UnknownExternalReply());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* _from_EmailMailboxAutoReplySettings(PyObject* /*unused*/, PyObject* arg) noexcept
{
try
{
auto return_value = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg);
return py::convert(return_value.as<winrt::Windows::ApplicationModel::Email::EmailMailboxAutoReplySettings>());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyMethodDef _methods_EmailMailboxAutoReplySettings[] = {
{ "_from", reinterpret_cast<PyCFunction>(_from_EmailMailboxAutoReplySettings), METH_O | METH_STATIC, nullptr },
{ }
};
static PyGetSetDef _getset_EmailMailboxAutoReplySettings[] = {
{ "start_time", reinterpret_cast<getter>(EmailMailboxAutoReplySettings_get_StartTime), reinterpret_cast<setter>(EmailMailboxAutoReplySettings_put_StartTime), nullptr, nullptr },
{ "response_kind", reinterpret_cast<getter>(EmailMailboxAutoReplySettings_get_ResponseKind), reinterpret_cast<setter>(EmailMailboxAutoReplySettings_put_ResponseKind), nullptr, nullptr },
{ "is_enabled", reinterpret_cast<getter>(EmailMailboxAutoReplySettings_get_IsEnabled), reinterpret_cast<setter>(EmailMailboxAutoReplySettings_put_IsEnabled), nullptr, nullptr },
{ "end_time", reinterpret_cast<getter>(EmailMailboxAutoReplySettings_get_EndTime), reinterpret_cast<setter>(EmailMailboxAutoReplySettings_put_EndTime), nullptr, nullptr },
{ "internal_reply", reinterpret_cast<getter>(EmailMailboxAutoReplySettings_get_InternalReply), nullptr, nullptr, nullptr },
{ "known_external_reply", reinterpret_cast<getter>(EmailMailboxAutoReplySettings_get_KnownExternalReply), nullptr, nullptr, nullptr },
{ "unknown_external_reply", reinterpret_cast<getter>(EmailMailboxAutoReplySettings_get_UnknownExternalReply), nullptr, nullptr, nullptr },
{ }
};
static PyType_Slot _type_slots_EmailMailboxAutoReplySettings[] =
{
{ Py_tp_new, _new_EmailMailboxAutoReplySettings },
{ Py_tp_dealloc, _dealloc_EmailMailboxAutoReplySettings },
{ Py_tp_methods, _methods_EmailMailboxAutoReplySettings },
{ Py_tp_getset, _getset_EmailMailboxAutoReplySettings },
{ },
};
static PyType_Spec _type_spec_EmailMailboxAutoReplySettings =
{
"_winsdk_Windows_ApplicationModel_Email.EmailMailboxAutoReplySettings",
sizeof(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxAutoReplySettings),
0,
Py_TPFLAGS_DEFAULT,
_type_slots_EmailMailboxAutoReplySettings
};
// ----- EmailMailboxCapabilities class --------------------
constexpr const char* const _type_name_EmailMailboxCapabilities = "EmailMailboxCapabilities";
static PyObject* _new_EmailMailboxCapabilities(PyTypeObject* type, PyObject* args, PyObject* kwds) noexcept
{
py::set_invalid_activation_error(_type_name_EmailMailboxCapabilities);
return nullptr;
}
static void _dealloc_EmailMailboxCapabilities(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxCapabilities* self)
{
auto hash_value = std::hash<winrt::Windows::Foundation::IInspectable>{}(self->obj);
py::wrapped_instance(hash_value, nullptr);
self->obj = nullptr;
}
static PyObject* EmailMailboxCapabilities_get_CanSmartSend(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxCapabilities* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.CanSmartSend());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailMailboxCapabilities_put_CanSmartSend(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxCapabilities* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<bool>(arg);
self->obj.CanSmartSend(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailMailboxCapabilities_get_CanUpdateMeetingResponses(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxCapabilities* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.CanUpdateMeetingResponses());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailMailboxCapabilities_put_CanUpdateMeetingResponses(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxCapabilities* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<bool>(arg);
self->obj.CanUpdateMeetingResponses(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailMailboxCapabilities_get_CanServerSearchMailbox(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxCapabilities* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.CanServerSearchMailbox());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailMailboxCapabilities_put_CanServerSearchMailbox(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxCapabilities* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<bool>(arg);
self->obj.CanServerSearchMailbox(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailMailboxCapabilities_get_CanServerSearchFolders(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxCapabilities* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.CanServerSearchFolders());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailMailboxCapabilities_put_CanServerSearchFolders(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxCapabilities* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<bool>(arg);
self->obj.CanServerSearchFolders(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailMailboxCapabilities_get_CanForwardMeetings(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxCapabilities* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.CanForwardMeetings());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailMailboxCapabilities_put_CanForwardMeetings(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxCapabilities* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<bool>(arg);
self->obj.CanForwardMeetings(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailMailboxCapabilities_get_CanProposeNewTimeForMeetings(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxCapabilities* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.CanProposeNewTimeForMeetings());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailMailboxCapabilities_put_CanProposeNewTimeForMeetings(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxCapabilities* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<bool>(arg);
self->obj.CanProposeNewTimeForMeetings(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailMailboxCapabilities_get_CanGetAndSetInternalAutoReplies(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxCapabilities* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.CanGetAndSetInternalAutoReplies());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailMailboxCapabilities_put_CanGetAndSetInternalAutoReplies(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxCapabilities* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<bool>(arg);
self->obj.CanGetAndSetInternalAutoReplies(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailMailboxCapabilities_get_CanGetAndSetExternalAutoReplies(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxCapabilities* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.CanGetAndSetExternalAutoReplies());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailMailboxCapabilities_put_CanGetAndSetExternalAutoReplies(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxCapabilities* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<bool>(arg);
self->obj.CanGetAndSetExternalAutoReplies(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailMailboxCapabilities_get_CanValidateCertificates(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxCapabilities* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.CanValidateCertificates());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailMailboxCapabilities_put_CanValidateCertificates(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxCapabilities* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<bool>(arg);
self->obj.CanValidateCertificates(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailMailboxCapabilities_get_CanResolveRecipients(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxCapabilities* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.CanResolveRecipients());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailMailboxCapabilities_put_CanResolveRecipients(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxCapabilities* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<bool>(arg);
self->obj.CanResolveRecipients(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailMailboxCapabilities_get_CanMoveFolder(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxCapabilities* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.CanMoveFolder());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailMailboxCapabilities_put_CanMoveFolder(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxCapabilities* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<bool>(arg);
self->obj.CanMoveFolder(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailMailboxCapabilities_get_CanEmptyFolder(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxCapabilities* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.CanEmptyFolder());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailMailboxCapabilities_put_CanEmptyFolder(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxCapabilities* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<bool>(arg);
self->obj.CanEmptyFolder(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailMailboxCapabilities_get_CanDeleteFolder(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxCapabilities* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.CanDeleteFolder());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailMailboxCapabilities_put_CanDeleteFolder(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxCapabilities* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<bool>(arg);
self->obj.CanDeleteFolder(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailMailboxCapabilities_get_CanCreateFolder(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxCapabilities* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.CanCreateFolder());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailMailboxCapabilities_put_CanCreateFolder(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxCapabilities* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<bool>(arg);
self->obj.CanCreateFolder(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* _from_EmailMailboxCapabilities(PyObject* /*unused*/, PyObject* arg) noexcept
{
try
{
auto return_value = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg);
return py::convert(return_value.as<winrt::Windows::ApplicationModel::Email::EmailMailboxCapabilities>());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyMethodDef _methods_EmailMailboxCapabilities[] = {
{ "_from", reinterpret_cast<PyCFunction>(_from_EmailMailboxCapabilities), METH_O | METH_STATIC, nullptr },
{ }
};
static PyGetSetDef _getset_EmailMailboxCapabilities[] = {
{ "can_smart_send", reinterpret_cast<getter>(EmailMailboxCapabilities_get_CanSmartSend), reinterpret_cast<setter>(EmailMailboxCapabilities_put_CanSmartSend), nullptr, nullptr },
{ "can_update_meeting_responses", reinterpret_cast<getter>(EmailMailboxCapabilities_get_CanUpdateMeetingResponses), reinterpret_cast<setter>(EmailMailboxCapabilities_put_CanUpdateMeetingResponses), nullptr, nullptr },
{ "can_server_search_mailbox", reinterpret_cast<getter>(EmailMailboxCapabilities_get_CanServerSearchMailbox), reinterpret_cast<setter>(EmailMailboxCapabilities_put_CanServerSearchMailbox), nullptr, nullptr },
{ "can_server_search_folders", reinterpret_cast<getter>(EmailMailboxCapabilities_get_CanServerSearchFolders), reinterpret_cast<setter>(EmailMailboxCapabilities_put_CanServerSearchFolders), nullptr, nullptr },
{ "can_forward_meetings", reinterpret_cast<getter>(EmailMailboxCapabilities_get_CanForwardMeetings), reinterpret_cast<setter>(EmailMailboxCapabilities_put_CanForwardMeetings), nullptr, nullptr },
{ "can_propose_new_time_for_meetings", reinterpret_cast<getter>(EmailMailboxCapabilities_get_CanProposeNewTimeForMeetings), reinterpret_cast<setter>(EmailMailboxCapabilities_put_CanProposeNewTimeForMeetings), nullptr, nullptr },
{ "can_get_and_set_internal_auto_replies", reinterpret_cast<getter>(EmailMailboxCapabilities_get_CanGetAndSetInternalAutoReplies), reinterpret_cast<setter>(EmailMailboxCapabilities_put_CanGetAndSetInternalAutoReplies), nullptr, nullptr },
{ "can_get_and_set_external_auto_replies", reinterpret_cast<getter>(EmailMailboxCapabilities_get_CanGetAndSetExternalAutoReplies), reinterpret_cast<setter>(EmailMailboxCapabilities_put_CanGetAndSetExternalAutoReplies), nullptr, nullptr },
{ "can_validate_certificates", reinterpret_cast<getter>(EmailMailboxCapabilities_get_CanValidateCertificates), reinterpret_cast<setter>(EmailMailboxCapabilities_put_CanValidateCertificates), nullptr, nullptr },
{ "can_resolve_recipients", reinterpret_cast<getter>(EmailMailboxCapabilities_get_CanResolveRecipients), reinterpret_cast<setter>(EmailMailboxCapabilities_put_CanResolveRecipients), nullptr, nullptr },
{ "can_move_folder", reinterpret_cast<getter>(EmailMailboxCapabilities_get_CanMoveFolder), reinterpret_cast<setter>(EmailMailboxCapabilities_put_CanMoveFolder), nullptr, nullptr },
{ "can_empty_folder", reinterpret_cast<getter>(EmailMailboxCapabilities_get_CanEmptyFolder), reinterpret_cast<setter>(EmailMailboxCapabilities_put_CanEmptyFolder), nullptr, nullptr },
{ "can_delete_folder", reinterpret_cast<getter>(EmailMailboxCapabilities_get_CanDeleteFolder), reinterpret_cast<setter>(EmailMailboxCapabilities_put_CanDeleteFolder), nullptr, nullptr },
{ "can_create_folder", reinterpret_cast<getter>(EmailMailboxCapabilities_get_CanCreateFolder), reinterpret_cast<setter>(EmailMailboxCapabilities_put_CanCreateFolder), nullptr, nullptr },
{ }
};
static PyType_Slot _type_slots_EmailMailboxCapabilities[] =
{
{ Py_tp_new, _new_EmailMailboxCapabilities },
{ Py_tp_dealloc, _dealloc_EmailMailboxCapabilities },
{ Py_tp_methods, _methods_EmailMailboxCapabilities },
{ Py_tp_getset, _getset_EmailMailboxCapabilities },
{ },
};
static PyType_Spec _type_spec_EmailMailboxCapabilities =
{
"_winsdk_Windows_ApplicationModel_Email.EmailMailboxCapabilities",
sizeof(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxCapabilities),
0,
Py_TPFLAGS_DEFAULT,
_type_slots_EmailMailboxCapabilities
};
// ----- EmailMailboxChange class --------------------
constexpr const char* const _type_name_EmailMailboxChange = "EmailMailboxChange";
static PyObject* _new_EmailMailboxChange(PyTypeObject* type, PyObject* args, PyObject* kwds) noexcept
{
py::set_invalid_activation_error(_type_name_EmailMailboxChange);
return nullptr;
}
static void _dealloc_EmailMailboxChange(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxChange* self)
{
auto hash_value = std::hash<winrt::Windows::Foundation::IInspectable>{}(self->obj);
py::wrapped_instance(hash_value, nullptr);
self->obj = nullptr;
}
static PyObject* EmailMailboxChange_get_ChangeType(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxChange* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.ChangeType());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* EmailMailboxChange_get_Folder(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxChange* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Folder());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* EmailMailboxChange_get_MailboxActions(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxChange* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.MailboxActions());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* EmailMailboxChange_get_Message(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxChange* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Message());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* _from_EmailMailboxChange(PyObject* /*unused*/, PyObject* arg) noexcept
{
try
{
auto return_value = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg);
return py::convert(return_value.as<winrt::Windows::ApplicationModel::Email::EmailMailboxChange>());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyMethodDef _methods_EmailMailboxChange[] = {
{ "_from", reinterpret_cast<PyCFunction>(_from_EmailMailboxChange), METH_O | METH_STATIC, nullptr },
{ }
};
static PyGetSetDef _getset_EmailMailboxChange[] = {
{ "change_type", reinterpret_cast<getter>(EmailMailboxChange_get_ChangeType), nullptr, nullptr, nullptr },
{ "folder", reinterpret_cast<getter>(EmailMailboxChange_get_Folder), nullptr, nullptr, nullptr },
{ "mailbox_actions", reinterpret_cast<getter>(EmailMailboxChange_get_MailboxActions), nullptr, nullptr, nullptr },
{ "message", reinterpret_cast<getter>(EmailMailboxChange_get_Message), nullptr, nullptr, nullptr },
{ }
};
static PyType_Slot _type_slots_EmailMailboxChange[] =
{
{ Py_tp_new, _new_EmailMailboxChange },
{ Py_tp_dealloc, _dealloc_EmailMailboxChange },
{ Py_tp_methods, _methods_EmailMailboxChange },
{ Py_tp_getset, _getset_EmailMailboxChange },
{ },
};
static PyType_Spec _type_spec_EmailMailboxChange =
{
"_winsdk_Windows_ApplicationModel_Email.EmailMailboxChange",
sizeof(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxChange),
0,
Py_TPFLAGS_DEFAULT,
_type_slots_EmailMailboxChange
};
// ----- EmailMailboxChangeReader class --------------------
constexpr const char* const _type_name_EmailMailboxChangeReader = "EmailMailboxChangeReader";
static PyObject* _new_EmailMailboxChangeReader(PyTypeObject* type, PyObject* args, PyObject* kwds) noexcept
{
py::set_invalid_activation_error(_type_name_EmailMailboxChangeReader);
return nullptr;
}
static void _dealloc_EmailMailboxChangeReader(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxChangeReader* self)
{
auto hash_value = std::hash<winrt::Windows::Foundation::IInspectable>{}(self->obj);
py::wrapped_instance(hash_value, nullptr);
self->obj = nullptr;
}
static PyObject* EmailMailboxChangeReader_AcceptChanges(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxChangeReader* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 0)
{
try
{
self->obj.AcceptChanges();
Py_RETURN_NONE;
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* EmailMailboxChangeReader_AcceptChangesThrough(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxChangeReader* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::Windows::ApplicationModel::Email::EmailMailboxChange>(args, 0);
self->obj.AcceptChangesThrough(param0);
Py_RETURN_NONE;
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* EmailMailboxChangeReader_ReadBatchAsync(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxChangeReader* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 0)
{
try
{
return py::convert(self->obj.ReadBatchAsync());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* _from_EmailMailboxChangeReader(PyObject* /*unused*/, PyObject* arg) noexcept
{
try
{
auto return_value = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg);
return py::convert(return_value.as<winrt::Windows::ApplicationModel::Email::EmailMailboxChangeReader>());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyMethodDef _methods_EmailMailboxChangeReader[] = {
{ "accept_changes", reinterpret_cast<PyCFunction>(EmailMailboxChangeReader_AcceptChanges), METH_VARARGS, nullptr },
{ "accept_changes_through", reinterpret_cast<PyCFunction>(EmailMailboxChangeReader_AcceptChangesThrough), METH_VARARGS, nullptr },
{ "read_batch_async", reinterpret_cast<PyCFunction>(EmailMailboxChangeReader_ReadBatchAsync), METH_VARARGS, nullptr },
{ "_from", reinterpret_cast<PyCFunction>(_from_EmailMailboxChangeReader), METH_O | METH_STATIC, nullptr },
{ }
};
static PyGetSetDef _getset_EmailMailboxChangeReader[] = {
{ }
};
static PyType_Slot _type_slots_EmailMailboxChangeReader[] =
{
{ Py_tp_new, _new_EmailMailboxChangeReader },
{ Py_tp_dealloc, _dealloc_EmailMailboxChangeReader },
{ Py_tp_methods, _methods_EmailMailboxChangeReader },
{ Py_tp_getset, _getset_EmailMailboxChangeReader },
{ },
};
static PyType_Spec _type_spec_EmailMailboxChangeReader =
{
"_winsdk_Windows_ApplicationModel_Email.EmailMailboxChangeReader",
sizeof(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxChangeReader),
0,
Py_TPFLAGS_DEFAULT,
_type_slots_EmailMailboxChangeReader
};
// ----- EmailMailboxChangeTracker class --------------------
constexpr const char* const _type_name_EmailMailboxChangeTracker = "EmailMailboxChangeTracker";
static PyObject* _new_EmailMailboxChangeTracker(PyTypeObject* type, PyObject* args, PyObject* kwds) noexcept
{
py::set_invalid_activation_error(_type_name_EmailMailboxChangeTracker);
return nullptr;
}
static void _dealloc_EmailMailboxChangeTracker(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxChangeTracker* self)
{
auto hash_value = std::hash<winrt::Windows::Foundation::IInspectable>{}(self->obj);
py::wrapped_instance(hash_value, nullptr);
self->obj = nullptr;
}
static PyObject* EmailMailboxChangeTracker_Enable(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxChangeTracker* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 0)
{
try
{
self->obj.Enable();
Py_RETURN_NONE;
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* EmailMailboxChangeTracker_GetChangeReader(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxChangeTracker* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 0)
{
try
{
return py::convert(self->obj.GetChangeReader());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* EmailMailboxChangeTracker_Reset(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxChangeTracker* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 0)
{
try
{
self->obj.Reset();
Py_RETURN_NONE;
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* EmailMailboxChangeTracker_get_IsTracking(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxChangeTracker* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.IsTracking());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* _from_EmailMailboxChangeTracker(PyObject* /*unused*/, PyObject* arg) noexcept
{
try
{
auto return_value = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg);
return py::convert(return_value.as<winrt::Windows::ApplicationModel::Email::EmailMailboxChangeTracker>());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyMethodDef _methods_EmailMailboxChangeTracker[] = {
{ "enable", reinterpret_cast<PyCFunction>(EmailMailboxChangeTracker_Enable), METH_VARARGS, nullptr },
{ "get_change_reader", reinterpret_cast<PyCFunction>(EmailMailboxChangeTracker_GetChangeReader), METH_VARARGS, nullptr },
{ "reset", reinterpret_cast<PyCFunction>(EmailMailboxChangeTracker_Reset), METH_VARARGS, nullptr },
{ "_from", reinterpret_cast<PyCFunction>(_from_EmailMailboxChangeTracker), METH_O | METH_STATIC, nullptr },
{ }
};
static PyGetSetDef _getset_EmailMailboxChangeTracker[] = {
{ "is_tracking", reinterpret_cast<getter>(EmailMailboxChangeTracker_get_IsTracking), nullptr, nullptr, nullptr },
{ }
};
static PyType_Slot _type_slots_EmailMailboxChangeTracker[] =
{
{ Py_tp_new, _new_EmailMailboxChangeTracker },
{ Py_tp_dealloc, _dealloc_EmailMailboxChangeTracker },
{ Py_tp_methods, _methods_EmailMailboxChangeTracker },
{ Py_tp_getset, _getset_EmailMailboxChangeTracker },
{ },
};
static PyType_Spec _type_spec_EmailMailboxChangeTracker =
{
"_winsdk_Windows_ApplicationModel_Email.EmailMailboxChangeTracker",
sizeof(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxChangeTracker),
0,
Py_TPFLAGS_DEFAULT,
_type_slots_EmailMailboxChangeTracker
};
// ----- EmailMailboxChangedDeferral class --------------------
constexpr const char* const _type_name_EmailMailboxChangedDeferral = "EmailMailboxChangedDeferral";
static PyObject* _new_EmailMailboxChangedDeferral(PyTypeObject* type, PyObject* args, PyObject* kwds) noexcept
{
py::set_invalid_activation_error(_type_name_EmailMailboxChangedDeferral);
return nullptr;
}
static void _dealloc_EmailMailboxChangedDeferral(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxChangedDeferral* self)
{
auto hash_value = std::hash<winrt::Windows::Foundation::IInspectable>{}(self->obj);
py::wrapped_instance(hash_value, nullptr);
self->obj = nullptr;
}
static PyObject* EmailMailboxChangedDeferral_Complete(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxChangedDeferral* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 0)
{
try
{
self->obj.Complete();
Py_RETURN_NONE;
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* _from_EmailMailboxChangedDeferral(PyObject* /*unused*/, PyObject* arg) noexcept
{
try
{
auto return_value = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg);
return py::convert(return_value.as<winrt::Windows::ApplicationModel::Email::EmailMailboxChangedDeferral>());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyMethodDef _methods_EmailMailboxChangedDeferral[] = {
{ "complete", reinterpret_cast<PyCFunction>(EmailMailboxChangedDeferral_Complete), METH_VARARGS, nullptr },
{ "_from", reinterpret_cast<PyCFunction>(_from_EmailMailboxChangedDeferral), METH_O | METH_STATIC, nullptr },
{ }
};
static PyGetSetDef _getset_EmailMailboxChangedDeferral[] = {
{ }
};
static PyType_Slot _type_slots_EmailMailboxChangedDeferral[] =
{
{ Py_tp_new, _new_EmailMailboxChangedDeferral },
{ Py_tp_dealloc, _dealloc_EmailMailboxChangedDeferral },
{ Py_tp_methods, _methods_EmailMailboxChangedDeferral },
{ Py_tp_getset, _getset_EmailMailboxChangedDeferral },
{ },
};
static PyType_Spec _type_spec_EmailMailboxChangedDeferral =
{
"_winsdk_Windows_ApplicationModel_Email.EmailMailboxChangedDeferral",
sizeof(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxChangedDeferral),
0,
Py_TPFLAGS_DEFAULT,
_type_slots_EmailMailboxChangedDeferral
};
// ----- EmailMailboxChangedEventArgs class --------------------
constexpr const char* const _type_name_EmailMailboxChangedEventArgs = "EmailMailboxChangedEventArgs";
static PyObject* _new_EmailMailboxChangedEventArgs(PyTypeObject* type, PyObject* args, PyObject* kwds) noexcept
{
py::set_invalid_activation_error(_type_name_EmailMailboxChangedEventArgs);
return nullptr;
}
static void _dealloc_EmailMailboxChangedEventArgs(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxChangedEventArgs* self)
{
auto hash_value = std::hash<winrt::Windows::Foundation::IInspectable>{}(self->obj);
py::wrapped_instance(hash_value, nullptr);
self->obj = nullptr;
}
static PyObject* EmailMailboxChangedEventArgs_GetDeferral(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxChangedEventArgs* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 0)
{
try
{
return py::convert(self->obj.GetDeferral());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* _from_EmailMailboxChangedEventArgs(PyObject* /*unused*/, PyObject* arg) noexcept
{
try
{
auto return_value = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg);
return py::convert(return_value.as<winrt::Windows::ApplicationModel::Email::EmailMailboxChangedEventArgs>());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyMethodDef _methods_EmailMailboxChangedEventArgs[] = {
{ "get_deferral", reinterpret_cast<PyCFunction>(EmailMailboxChangedEventArgs_GetDeferral), METH_VARARGS, nullptr },
{ "_from", reinterpret_cast<PyCFunction>(_from_EmailMailboxChangedEventArgs), METH_O | METH_STATIC, nullptr },
{ }
};
static PyGetSetDef _getset_EmailMailboxChangedEventArgs[] = {
{ }
};
static PyType_Slot _type_slots_EmailMailboxChangedEventArgs[] =
{
{ Py_tp_new, _new_EmailMailboxChangedEventArgs },
{ Py_tp_dealloc, _dealloc_EmailMailboxChangedEventArgs },
{ Py_tp_methods, _methods_EmailMailboxChangedEventArgs },
{ Py_tp_getset, _getset_EmailMailboxChangedEventArgs },
{ },
};
static PyType_Spec _type_spec_EmailMailboxChangedEventArgs =
{
"_winsdk_Windows_ApplicationModel_Email.EmailMailboxChangedEventArgs",
sizeof(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxChangedEventArgs),
0,
Py_TPFLAGS_DEFAULT,
_type_slots_EmailMailboxChangedEventArgs
};
// ----- EmailMailboxCreateFolderResult class --------------------
constexpr const char* const _type_name_EmailMailboxCreateFolderResult = "EmailMailboxCreateFolderResult";
static PyObject* _new_EmailMailboxCreateFolderResult(PyTypeObject* type, PyObject* args, PyObject* kwds) noexcept
{
py::set_invalid_activation_error(_type_name_EmailMailboxCreateFolderResult);
return nullptr;
}
static void _dealloc_EmailMailboxCreateFolderResult(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxCreateFolderResult* self)
{
auto hash_value = std::hash<winrt::Windows::Foundation::IInspectable>{}(self->obj);
py::wrapped_instance(hash_value, nullptr);
self->obj = nullptr;
}
static PyObject* EmailMailboxCreateFolderResult_get_Folder(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxCreateFolderResult* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Folder());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* EmailMailboxCreateFolderResult_get_Status(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxCreateFolderResult* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Status());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* _from_EmailMailboxCreateFolderResult(PyObject* /*unused*/, PyObject* arg) noexcept
{
try
{
auto return_value = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg);
return py::convert(return_value.as<winrt::Windows::ApplicationModel::Email::EmailMailboxCreateFolderResult>());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyMethodDef _methods_EmailMailboxCreateFolderResult[] = {
{ "_from", reinterpret_cast<PyCFunction>(_from_EmailMailboxCreateFolderResult), METH_O | METH_STATIC, nullptr },
{ }
};
static PyGetSetDef _getset_EmailMailboxCreateFolderResult[] = {
{ "folder", reinterpret_cast<getter>(EmailMailboxCreateFolderResult_get_Folder), nullptr, nullptr, nullptr },
{ "status", reinterpret_cast<getter>(EmailMailboxCreateFolderResult_get_Status), nullptr, nullptr, nullptr },
{ }
};
static PyType_Slot _type_slots_EmailMailboxCreateFolderResult[] =
{
{ Py_tp_new, _new_EmailMailboxCreateFolderResult },
{ Py_tp_dealloc, _dealloc_EmailMailboxCreateFolderResult },
{ Py_tp_methods, _methods_EmailMailboxCreateFolderResult },
{ Py_tp_getset, _getset_EmailMailboxCreateFolderResult },
{ },
};
static PyType_Spec _type_spec_EmailMailboxCreateFolderResult =
{
"_winsdk_Windows_ApplicationModel_Email.EmailMailboxCreateFolderResult",
sizeof(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxCreateFolderResult),
0,
Py_TPFLAGS_DEFAULT,
_type_slots_EmailMailboxCreateFolderResult
};
// ----- EmailMailboxPolicies class --------------------
constexpr const char* const _type_name_EmailMailboxPolicies = "EmailMailboxPolicies";
static PyObject* _new_EmailMailboxPolicies(PyTypeObject* type, PyObject* args, PyObject* kwds) noexcept
{
py::set_invalid_activation_error(_type_name_EmailMailboxPolicies);
return nullptr;
}
static void _dealloc_EmailMailboxPolicies(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxPolicies* self)
{
auto hash_value = std::hash<winrt::Windows::Foundation::IInspectable>{}(self->obj);
py::wrapped_instance(hash_value, nullptr);
self->obj = nullptr;
}
static PyObject* EmailMailboxPolicies_get_RequiredSmimeSigningAlgorithm(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxPolicies* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.RequiredSmimeSigningAlgorithm());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailMailboxPolicies_put_RequiredSmimeSigningAlgorithm(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxPolicies* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::Windows::Foundation::IReference<winrt::Windows::ApplicationModel::Email::EmailMailboxSmimeSigningAlgorithm>>(arg);
self->obj.RequiredSmimeSigningAlgorithm(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailMailboxPolicies_get_RequiredSmimeEncryptionAlgorithm(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxPolicies* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.RequiredSmimeEncryptionAlgorithm());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailMailboxPolicies_put_RequiredSmimeEncryptionAlgorithm(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxPolicies* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::Windows::Foundation::IReference<winrt::Windows::ApplicationModel::Email::EmailMailboxSmimeEncryptionAlgorithm>>(arg);
self->obj.RequiredSmimeEncryptionAlgorithm(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailMailboxPolicies_get_AllowedSmimeEncryptionAlgorithmNegotiation(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxPolicies* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.AllowedSmimeEncryptionAlgorithmNegotiation());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailMailboxPolicies_put_AllowedSmimeEncryptionAlgorithmNegotiation(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxPolicies* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::Windows::ApplicationModel::Email::EmailMailboxAllowedSmimeEncryptionAlgorithmNegotiation>(arg);
self->obj.AllowedSmimeEncryptionAlgorithmNegotiation(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailMailboxPolicies_get_AllowSmimeSoftCertificates(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxPolicies* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.AllowSmimeSoftCertificates());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailMailboxPolicies_put_AllowSmimeSoftCertificates(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxPolicies* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<bool>(arg);
self->obj.AllowSmimeSoftCertificates(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailMailboxPolicies_get_MustSignSmimeMessages(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxPolicies* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.MustSignSmimeMessages());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailMailboxPolicies_put_MustSignSmimeMessages(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxPolicies* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<bool>(arg);
self->obj.MustSignSmimeMessages(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailMailboxPolicies_get_MustEncryptSmimeMessages(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxPolicies* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.MustEncryptSmimeMessages());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailMailboxPolicies_put_MustEncryptSmimeMessages(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxPolicies* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<bool>(arg);
self->obj.MustEncryptSmimeMessages(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* _from_EmailMailboxPolicies(PyObject* /*unused*/, PyObject* arg) noexcept
{
try
{
auto return_value = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg);
return py::convert(return_value.as<winrt::Windows::ApplicationModel::Email::EmailMailboxPolicies>());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyMethodDef _methods_EmailMailboxPolicies[] = {
{ "_from", reinterpret_cast<PyCFunction>(_from_EmailMailboxPolicies), METH_O | METH_STATIC, nullptr },
{ }
};
static PyGetSetDef _getset_EmailMailboxPolicies[] = {
{ "required_smime_signing_algorithm", reinterpret_cast<getter>(EmailMailboxPolicies_get_RequiredSmimeSigningAlgorithm), reinterpret_cast<setter>(EmailMailboxPolicies_put_RequiredSmimeSigningAlgorithm), nullptr, nullptr },
{ "required_smime_encryption_algorithm", reinterpret_cast<getter>(EmailMailboxPolicies_get_RequiredSmimeEncryptionAlgorithm), reinterpret_cast<setter>(EmailMailboxPolicies_put_RequiredSmimeEncryptionAlgorithm), nullptr, nullptr },
{ "allowed_smime_encryption_algorithm_negotiation", reinterpret_cast<getter>(EmailMailboxPolicies_get_AllowedSmimeEncryptionAlgorithmNegotiation), reinterpret_cast<setter>(EmailMailboxPolicies_put_AllowedSmimeEncryptionAlgorithmNegotiation), nullptr, nullptr },
{ "allow_smime_soft_certificates", reinterpret_cast<getter>(EmailMailboxPolicies_get_AllowSmimeSoftCertificates), reinterpret_cast<setter>(EmailMailboxPolicies_put_AllowSmimeSoftCertificates), nullptr, nullptr },
{ "must_sign_smime_messages", reinterpret_cast<getter>(EmailMailboxPolicies_get_MustSignSmimeMessages), reinterpret_cast<setter>(EmailMailboxPolicies_put_MustSignSmimeMessages), nullptr, nullptr },
{ "must_encrypt_smime_messages", reinterpret_cast<getter>(EmailMailboxPolicies_get_MustEncryptSmimeMessages), reinterpret_cast<setter>(EmailMailboxPolicies_put_MustEncryptSmimeMessages), nullptr, nullptr },
{ }
};
static PyType_Slot _type_slots_EmailMailboxPolicies[] =
{
{ Py_tp_new, _new_EmailMailboxPolicies },
{ Py_tp_dealloc, _dealloc_EmailMailboxPolicies },
{ Py_tp_methods, _methods_EmailMailboxPolicies },
{ Py_tp_getset, _getset_EmailMailboxPolicies },
{ },
};
static PyType_Spec _type_spec_EmailMailboxPolicies =
{
"_winsdk_Windows_ApplicationModel_Email.EmailMailboxPolicies",
sizeof(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxPolicies),
0,
Py_TPFLAGS_DEFAULT,
_type_slots_EmailMailboxPolicies
};
// ----- EmailMailboxSyncManager class --------------------
constexpr const char* const _type_name_EmailMailboxSyncManager = "EmailMailboxSyncManager";
static PyObject* _new_EmailMailboxSyncManager(PyTypeObject* type, PyObject* args, PyObject* kwds) noexcept
{
py::set_invalid_activation_error(_type_name_EmailMailboxSyncManager);
return nullptr;
}
static void _dealloc_EmailMailboxSyncManager(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxSyncManager* self)
{
auto hash_value = std::hash<winrt::Windows::Foundation::IInspectable>{}(self->obj);
py::wrapped_instance(hash_value, nullptr);
self->obj = nullptr;
}
static PyObject* EmailMailboxSyncManager_SyncAsync(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxSyncManager* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 0)
{
try
{
return py::convert(self->obj.SyncAsync());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* EmailMailboxSyncManager_get_Status(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxSyncManager* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Status());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailMailboxSyncManager_put_Status(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxSyncManager* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::Windows::ApplicationModel::Email::EmailMailboxSyncStatus>(arg);
self->obj.Status(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailMailboxSyncManager_get_LastSuccessfulSyncTime(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxSyncManager* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.LastSuccessfulSyncTime());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailMailboxSyncManager_put_LastSuccessfulSyncTime(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxSyncManager* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::Windows::Foundation::DateTime>(arg);
self->obj.LastSuccessfulSyncTime(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailMailboxSyncManager_get_LastAttemptedSyncTime(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxSyncManager* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.LastAttemptedSyncTime());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailMailboxSyncManager_put_LastAttemptedSyncTime(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxSyncManager* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::Windows::Foundation::DateTime>(arg);
self->obj.LastAttemptedSyncTime(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailMailboxSyncManager_add_SyncStatusChanged(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxSyncManager* self, PyObject* arg) noexcept
{
try
{
auto param0 = py::convert_to<winrt::Windows::Foundation::TypedEventHandler<winrt::Windows::ApplicationModel::Email::EmailMailboxSyncManager, winrt::Windows::Foundation::IInspectable>>(arg);
return py::convert(self->obj.SyncStatusChanged(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* EmailMailboxSyncManager_remove_SyncStatusChanged(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxSyncManager* self, PyObject* arg) noexcept
{
try
{
auto param0 = py::convert_to<winrt::event_token>(arg);
self->obj.SyncStatusChanged(param0);
Py_RETURN_NONE;
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* _from_EmailMailboxSyncManager(PyObject* /*unused*/, PyObject* arg) noexcept
{
try
{
auto return_value = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg);
return py::convert(return_value.as<winrt::Windows::ApplicationModel::Email::EmailMailboxSyncManager>());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyMethodDef _methods_EmailMailboxSyncManager[] = {
{ "sync_async", reinterpret_cast<PyCFunction>(EmailMailboxSyncManager_SyncAsync), METH_VARARGS, nullptr },
{ "add_sync_status_changed", reinterpret_cast<PyCFunction>(EmailMailboxSyncManager_add_SyncStatusChanged), METH_O, nullptr },
{ "remove_sync_status_changed", reinterpret_cast<PyCFunction>(EmailMailboxSyncManager_remove_SyncStatusChanged), METH_O, nullptr },
{ "_from", reinterpret_cast<PyCFunction>(_from_EmailMailboxSyncManager), METH_O | METH_STATIC, nullptr },
{ }
};
static PyGetSetDef _getset_EmailMailboxSyncManager[] = {
{ "status", reinterpret_cast<getter>(EmailMailboxSyncManager_get_Status), reinterpret_cast<setter>(EmailMailboxSyncManager_put_Status), nullptr, nullptr },
{ "last_successful_sync_time", reinterpret_cast<getter>(EmailMailboxSyncManager_get_LastSuccessfulSyncTime), reinterpret_cast<setter>(EmailMailboxSyncManager_put_LastSuccessfulSyncTime), nullptr, nullptr },
{ "last_attempted_sync_time", reinterpret_cast<getter>(EmailMailboxSyncManager_get_LastAttemptedSyncTime), reinterpret_cast<setter>(EmailMailboxSyncManager_put_LastAttemptedSyncTime), nullptr, nullptr },
{ }
};
static PyType_Slot _type_slots_EmailMailboxSyncManager[] =
{
{ Py_tp_new, _new_EmailMailboxSyncManager },
{ Py_tp_dealloc, _dealloc_EmailMailboxSyncManager },
{ Py_tp_methods, _methods_EmailMailboxSyncManager },
{ Py_tp_getset, _getset_EmailMailboxSyncManager },
{ },
};
static PyType_Spec _type_spec_EmailMailboxSyncManager =
{
"_winsdk_Windows_ApplicationModel_Email.EmailMailboxSyncManager",
sizeof(py::wrapper::Windows::ApplicationModel::Email::EmailMailboxSyncManager),
0,
Py_TPFLAGS_DEFAULT,
_type_slots_EmailMailboxSyncManager
};
// ----- EmailManager class --------------------
constexpr const char* const _type_name_EmailManager = "EmailManager";
static PyObject* _new_EmailManager(PyTypeObject* type, PyObject* args, PyObject* kwds) noexcept
{
py::set_invalid_activation_error(_type_name_EmailManager);
return nullptr;
}
static PyObject* EmailManager_GetForUser(PyObject* /*unused*/, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::Windows::System::User>(args, 0);
return py::convert(winrt::Windows::ApplicationModel::Email::EmailManager::GetForUser(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* EmailManager_RequestStoreAsync(PyObject* /*unused*/, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::Windows::ApplicationModel::Email::EmailStoreAccessType>(args, 0);
return py::convert(winrt::Windows::ApplicationModel::Email::EmailManager::RequestStoreAsync(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* EmailManager_ShowComposeNewEmailAsync(PyObject* /*unused*/, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::Windows::ApplicationModel::Email::EmailMessage>(args, 0);
return py::convert(winrt::Windows::ApplicationModel::Email::EmailManager::ShowComposeNewEmailAsync(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyMethodDef _methods_EmailManager[] = {
{ "get_for_user", reinterpret_cast<PyCFunction>(EmailManager_GetForUser), METH_VARARGS | METH_STATIC, nullptr },
{ "request_store_async", reinterpret_cast<PyCFunction>(EmailManager_RequestStoreAsync), METH_VARARGS | METH_STATIC, nullptr },
{ "show_compose_new_email_async", reinterpret_cast<PyCFunction>(EmailManager_ShowComposeNewEmailAsync), METH_VARARGS | METH_STATIC, nullptr },
{ }
};
static PyGetSetDef _getset_EmailManager[] = {
{ }
};
static PyType_Slot _type_slots_EmailManager[] =
{
{ Py_tp_new, _new_EmailManager },
{ Py_tp_methods, _methods_EmailManager },
{ Py_tp_getset, _getset_EmailManager },
{ },
};
static PyType_Spec _type_spec_EmailManager =
{
"_winsdk_Windows_ApplicationModel_Email.EmailManager",
0,
0,
Py_TPFLAGS_DEFAULT,
_type_slots_EmailManager
};
// ----- EmailManagerForUser class --------------------
constexpr const char* const _type_name_EmailManagerForUser = "EmailManagerForUser";
static PyObject* _new_EmailManagerForUser(PyTypeObject* type, PyObject* args, PyObject* kwds) noexcept
{
py::set_invalid_activation_error(_type_name_EmailManagerForUser);
return nullptr;
}
static void _dealloc_EmailManagerForUser(py::wrapper::Windows::ApplicationModel::Email::EmailManagerForUser* self)
{
auto hash_value = std::hash<winrt::Windows::Foundation::IInspectable>{}(self->obj);
py::wrapped_instance(hash_value, nullptr);
self->obj = nullptr;
}
static PyObject* EmailManagerForUser_RequestStoreAsync(py::wrapper::Windows::ApplicationModel::Email::EmailManagerForUser* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::Windows::ApplicationModel::Email::EmailStoreAccessType>(args, 0);
return py::convert(self->obj.RequestStoreAsync(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* EmailManagerForUser_ShowComposeNewEmailAsync(py::wrapper::Windows::ApplicationModel::Email::EmailManagerForUser* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::Windows::ApplicationModel::Email::EmailMessage>(args, 0);
return py::convert(self->obj.ShowComposeNewEmailAsync(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* EmailManagerForUser_get_User(py::wrapper::Windows::ApplicationModel::Email::EmailManagerForUser* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.User());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* _from_EmailManagerForUser(PyObject* /*unused*/, PyObject* arg) noexcept
{
try
{
auto return_value = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg);
return py::convert(return_value.as<winrt::Windows::ApplicationModel::Email::EmailManagerForUser>());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyMethodDef _methods_EmailManagerForUser[] = {
{ "request_store_async", reinterpret_cast<PyCFunction>(EmailManagerForUser_RequestStoreAsync), METH_VARARGS, nullptr },
{ "show_compose_new_email_async", reinterpret_cast<PyCFunction>(EmailManagerForUser_ShowComposeNewEmailAsync), METH_VARARGS, nullptr },
{ "_from", reinterpret_cast<PyCFunction>(_from_EmailManagerForUser), METH_O | METH_STATIC, nullptr },
{ }
};
static PyGetSetDef _getset_EmailManagerForUser[] = {
{ "user", reinterpret_cast<getter>(EmailManagerForUser_get_User), nullptr, nullptr, nullptr },
{ }
};
static PyType_Slot _type_slots_EmailManagerForUser[] =
{
{ Py_tp_new, _new_EmailManagerForUser },
{ Py_tp_dealloc, _dealloc_EmailManagerForUser },
{ Py_tp_methods, _methods_EmailManagerForUser },
{ Py_tp_getset, _getset_EmailManagerForUser },
{ },
};
static PyType_Spec _type_spec_EmailManagerForUser =
{
"_winsdk_Windows_ApplicationModel_Email.EmailManagerForUser",
sizeof(py::wrapper::Windows::ApplicationModel::Email::EmailManagerForUser),
0,
Py_TPFLAGS_DEFAULT,
_type_slots_EmailManagerForUser
};
// ----- EmailMeetingInfo class --------------------
constexpr const char* const _type_name_EmailMeetingInfo = "EmailMeetingInfo";
static PyObject* _new_EmailMeetingInfo(PyTypeObject* type, PyObject* args, PyObject* kwds) noexcept
{
if (kwds != nullptr)
{
py::set_invalid_kwd_args_error();
return nullptr;
}
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 0)
{
try
{
winrt::Windows::ApplicationModel::Email::EmailMeetingInfo instance{ };
return py::wrap(instance, type);
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static void _dealloc_EmailMeetingInfo(py::wrapper::Windows::ApplicationModel::Email::EmailMeetingInfo* self)
{
auto hash_value = std::hash<winrt::Windows::Foundation::IInspectable>{}(self->obj);
py::wrapped_instance(hash_value, nullptr);
self->obj = nullptr;
}
static PyObject* EmailMeetingInfo_get_Location(py::wrapper::Windows::ApplicationModel::Email::EmailMeetingInfo* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Location());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailMeetingInfo_put_Location(py::wrapper::Windows::ApplicationModel::Email::EmailMeetingInfo* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::hstring>(arg);
self->obj.Location(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailMeetingInfo_get_IsResponseRequested(py::wrapper::Windows::ApplicationModel::Email::EmailMeetingInfo* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.IsResponseRequested());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailMeetingInfo_put_IsResponseRequested(py::wrapper::Windows::ApplicationModel::Email::EmailMeetingInfo* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<bool>(arg);
self->obj.IsResponseRequested(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailMeetingInfo_get_IsAllDay(py::wrapper::Windows::ApplicationModel::Email::EmailMeetingInfo* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.IsAllDay());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailMeetingInfo_put_IsAllDay(py::wrapper::Windows::ApplicationModel::Email::EmailMeetingInfo* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<bool>(arg);
self->obj.IsAllDay(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailMeetingInfo_get_AllowNewTimeProposal(py::wrapper::Windows::ApplicationModel::Email::EmailMeetingInfo* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.AllowNewTimeProposal());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailMeetingInfo_put_AllowNewTimeProposal(py::wrapper::Windows::ApplicationModel::Email::EmailMeetingInfo* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<bool>(arg);
self->obj.AllowNewTimeProposal(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailMeetingInfo_get_Duration(py::wrapper::Windows::ApplicationModel::Email::EmailMeetingInfo* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Duration());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailMeetingInfo_put_Duration(py::wrapper::Windows::ApplicationModel::Email::EmailMeetingInfo* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::Windows::Foundation::TimeSpan>(arg);
self->obj.Duration(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailMeetingInfo_get_AppointmentRoamingId(py::wrapper::Windows::ApplicationModel::Email::EmailMeetingInfo* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.AppointmentRoamingId());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailMeetingInfo_put_AppointmentRoamingId(py::wrapper::Windows::ApplicationModel::Email::EmailMeetingInfo* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::hstring>(arg);
self->obj.AppointmentRoamingId(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailMeetingInfo_get_AppointmentOriginalStartTime(py::wrapper::Windows::ApplicationModel::Email::EmailMeetingInfo* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.AppointmentOriginalStartTime());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailMeetingInfo_put_AppointmentOriginalStartTime(py::wrapper::Windows::ApplicationModel::Email::EmailMeetingInfo* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::Windows::Foundation::IReference<winrt::Windows::Foundation::DateTime>>(arg);
self->obj.AppointmentOriginalStartTime(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailMeetingInfo_get_ProposedDuration(py::wrapper::Windows::ApplicationModel::Email::EmailMeetingInfo* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.ProposedDuration());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailMeetingInfo_put_ProposedDuration(py::wrapper::Windows::ApplicationModel::Email::EmailMeetingInfo* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::Windows::Foundation::IReference<winrt::Windows::Foundation::TimeSpan>>(arg);
self->obj.ProposedDuration(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailMeetingInfo_get_RemoteChangeNumber(py::wrapper::Windows::ApplicationModel::Email::EmailMeetingInfo* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.RemoteChangeNumber());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailMeetingInfo_put_RemoteChangeNumber(py::wrapper::Windows::ApplicationModel::Email::EmailMeetingInfo* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<uint64_t>(arg);
self->obj.RemoteChangeNumber(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailMeetingInfo_get_StartTime(py::wrapper::Windows::ApplicationModel::Email::EmailMeetingInfo* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.StartTime());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailMeetingInfo_put_StartTime(py::wrapper::Windows::ApplicationModel::Email::EmailMeetingInfo* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::Windows::Foundation::DateTime>(arg);
self->obj.StartTime(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailMeetingInfo_get_RecurrenceStartTime(py::wrapper::Windows::ApplicationModel::Email::EmailMeetingInfo* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.RecurrenceStartTime());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailMeetingInfo_put_RecurrenceStartTime(py::wrapper::Windows::ApplicationModel::Email::EmailMeetingInfo* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::Windows::Foundation::IReference<winrt::Windows::Foundation::DateTime>>(arg);
self->obj.RecurrenceStartTime(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailMeetingInfo_get_Recurrence(py::wrapper::Windows::ApplicationModel::Email::EmailMeetingInfo* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Recurrence());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailMeetingInfo_put_Recurrence(py::wrapper::Windows::ApplicationModel::Email::EmailMeetingInfo* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::Windows::ApplicationModel::Appointments::AppointmentRecurrence>(arg);
self->obj.Recurrence(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailMeetingInfo_get_ProposedStartTime(py::wrapper::Windows::ApplicationModel::Email::EmailMeetingInfo* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.ProposedStartTime());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailMeetingInfo_put_ProposedStartTime(py::wrapper::Windows::ApplicationModel::Email::EmailMeetingInfo* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::Windows::Foundation::IReference<winrt::Windows::Foundation::DateTime>>(arg);
self->obj.ProposedStartTime(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailMeetingInfo_get_IsReportedOutOfDateByServer(py::wrapper::Windows::ApplicationModel::Email::EmailMeetingInfo* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.IsReportedOutOfDateByServer());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* _from_EmailMeetingInfo(PyObject* /*unused*/, PyObject* arg) noexcept
{
try
{
auto return_value = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg);
return py::convert(return_value.as<winrt::Windows::ApplicationModel::Email::EmailMeetingInfo>());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyMethodDef _methods_EmailMeetingInfo[] = {
{ "_from", reinterpret_cast<PyCFunction>(_from_EmailMeetingInfo), METH_O | METH_STATIC, nullptr },
{ }
};
static PyGetSetDef _getset_EmailMeetingInfo[] = {
{ "location", reinterpret_cast<getter>(EmailMeetingInfo_get_Location), reinterpret_cast<setter>(EmailMeetingInfo_put_Location), nullptr, nullptr },
{ "is_response_requested", reinterpret_cast<getter>(EmailMeetingInfo_get_IsResponseRequested), reinterpret_cast<setter>(EmailMeetingInfo_put_IsResponseRequested), nullptr, nullptr },
{ "is_all_day", reinterpret_cast<getter>(EmailMeetingInfo_get_IsAllDay), reinterpret_cast<setter>(EmailMeetingInfo_put_IsAllDay), nullptr, nullptr },
{ "allow_new_time_proposal", reinterpret_cast<getter>(EmailMeetingInfo_get_AllowNewTimeProposal), reinterpret_cast<setter>(EmailMeetingInfo_put_AllowNewTimeProposal), nullptr, nullptr },
{ "duration", reinterpret_cast<getter>(EmailMeetingInfo_get_Duration), reinterpret_cast<setter>(EmailMeetingInfo_put_Duration), nullptr, nullptr },
{ "appointment_roaming_id", reinterpret_cast<getter>(EmailMeetingInfo_get_AppointmentRoamingId), reinterpret_cast<setter>(EmailMeetingInfo_put_AppointmentRoamingId), nullptr, nullptr },
{ "appointment_original_start_time", reinterpret_cast<getter>(EmailMeetingInfo_get_AppointmentOriginalStartTime), reinterpret_cast<setter>(EmailMeetingInfo_put_AppointmentOriginalStartTime), nullptr, nullptr },
{ "proposed_duration", reinterpret_cast<getter>(EmailMeetingInfo_get_ProposedDuration), reinterpret_cast<setter>(EmailMeetingInfo_put_ProposedDuration), nullptr, nullptr },
{ "remote_change_number", reinterpret_cast<getter>(EmailMeetingInfo_get_RemoteChangeNumber), reinterpret_cast<setter>(EmailMeetingInfo_put_RemoteChangeNumber), nullptr, nullptr },
{ "start_time", reinterpret_cast<getter>(EmailMeetingInfo_get_StartTime), reinterpret_cast<setter>(EmailMeetingInfo_put_StartTime), nullptr, nullptr },
{ "recurrence_start_time", reinterpret_cast<getter>(EmailMeetingInfo_get_RecurrenceStartTime), reinterpret_cast<setter>(EmailMeetingInfo_put_RecurrenceStartTime), nullptr, nullptr },
{ "recurrence", reinterpret_cast<getter>(EmailMeetingInfo_get_Recurrence), reinterpret_cast<setter>(EmailMeetingInfo_put_Recurrence), nullptr, nullptr },
{ "proposed_start_time", reinterpret_cast<getter>(EmailMeetingInfo_get_ProposedStartTime), reinterpret_cast<setter>(EmailMeetingInfo_put_ProposedStartTime), nullptr, nullptr },
{ "is_reported_out_of_date_by_server", reinterpret_cast<getter>(EmailMeetingInfo_get_IsReportedOutOfDateByServer), nullptr, nullptr, nullptr },
{ }
};
static PyType_Slot _type_slots_EmailMeetingInfo[] =
{
{ Py_tp_new, _new_EmailMeetingInfo },
{ Py_tp_dealloc, _dealloc_EmailMeetingInfo },
{ Py_tp_methods, _methods_EmailMeetingInfo },
{ Py_tp_getset, _getset_EmailMeetingInfo },
{ },
};
static PyType_Spec _type_spec_EmailMeetingInfo =
{
"_winsdk_Windows_ApplicationModel_Email.EmailMeetingInfo",
sizeof(py::wrapper::Windows::ApplicationModel::Email::EmailMeetingInfo),
0,
Py_TPFLAGS_DEFAULT,
_type_slots_EmailMeetingInfo
};
// ----- EmailMessage class --------------------
constexpr const char* const _type_name_EmailMessage = "EmailMessage";
static PyObject* _new_EmailMessage(PyTypeObject* type, PyObject* args, PyObject* kwds) noexcept
{
if (kwds != nullptr)
{
py::set_invalid_kwd_args_error();
return nullptr;
}
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 0)
{
try
{
winrt::Windows::ApplicationModel::Email::EmailMessage instance{ };
return py::wrap(instance, type);
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static void _dealloc_EmailMessage(py::wrapper::Windows::ApplicationModel::Email::EmailMessage* self)
{
auto hash_value = std::hash<winrt::Windows::Foundation::IInspectable>{}(self->obj);
py::wrapped_instance(hash_value, nullptr);
self->obj = nullptr;
}
static PyObject* EmailMessage_GetBodyStream(py::wrapper::Windows::ApplicationModel::Email::EmailMessage* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::Windows::ApplicationModel::Email::EmailMessageBodyKind>(args, 0);
return py::convert(self->obj.GetBodyStream(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* EmailMessage_SetBodyStream(py::wrapper::Windows::ApplicationModel::Email::EmailMessage* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::Windows::ApplicationModel::Email::EmailMessageBodyKind>(args, 0);
auto param1 = py::convert_to<winrt::Windows::Storage::Streams::IRandomAccessStreamReference>(args, 1);
self->obj.SetBodyStream(param0, param1);
Py_RETURN_NONE;
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* EmailMessage_get_Subject(py::wrapper::Windows::ApplicationModel::Email::EmailMessage* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Subject());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailMessage_put_Subject(py::wrapper::Windows::ApplicationModel::Email::EmailMessage* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::hstring>(arg);
self->obj.Subject(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailMessage_get_Body(py::wrapper::Windows::ApplicationModel::Email::EmailMessage* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Body());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailMessage_put_Body(py::wrapper::Windows::ApplicationModel::Email::EmailMessage* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::hstring>(arg);
self->obj.Body(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailMessage_get_Bcc(py::wrapper::Windows::ApplicationModel::Email::EmailMessage* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Bcc());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* EmailMessage_get_CC(py::wrapper::Windows::ApplicationModel::Email::EmailMessage* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.CC());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* EmailMessage_get_Attachments(py::wrapper::Windows::ApplicationModel::Email::EmailMessage* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Attachments());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* EmailMessage_get_To(py::wrapper::Windows::ApplicationModel::Email::EmailMessage* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.To());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* EmailMessage_get_AllowInternetImages(py::wrapper::Windows::ApplicationModel::Email::EmailMessage* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.AllowInternetImages());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailMessage_put_AllowInternetImages(py::wrapper::Windows::ApplicationModel::Email::EmailMessage* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<bool>(arg);
self->obj.AllowInternetImages(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailMessage_get_FlagState(py::wrapper::Windows::ApplicationModel::Email::EmailMessage* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.FlagState());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailMessage_put_FlagState(py::wrapper::Windows::ApplicationModel::Email::EmailMessage* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::Windows::ApplicationModel::Email::EmailFlagState>(arg);
self->obj.FlagState(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailMessage_get_EstimatedDownloadSizeInBytes(py::wrapper::Windows::ApplicationModel::Email::EmailMessage* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.EstimatedDownloadSizeInBytes());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailMessage_put_EstimatedDownloadSizeInBytes(py::wrapper::Windows::ApplicationModel::Email::EmailMessage* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<uint32_t>(arg);
self->obj.EstimatedDownloadSizeInBytes(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailMessage_get_DownloadState(py::wrapper::Windows::ApplicationModel::Email::EmailMessage* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.DownloadState());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailMessage_put_DownloadState(py::wrapper::Windows::ApplicationModel::Email::EmailMessage* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::Windows::ApplicationModel::Email::EmailMessageDownloadState>(arg);
self->obj.DownloadState(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailMessage_get_Importance(py::wrapper::Windows::ApplicationModel::Email::EmailMessage* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Importance());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailMessage_put_Importance(py::wrapper::Windows::ApplicationModel::Email::EmailMessage* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::Windows::ApplicationModel::Email::EmailImportance>(arg);
self->obj.Importance(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailMessage_get_IrmInfo(py::wrapper::Windows::ApplicationModel::Email::EmailMessage* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.IrmInfo());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailMessage_put_IrmInfo(py::wrapper::Windows::ApplicationModel::Email::EmailMessage* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::Windows::ApplicationModel::Email::EmailIrmInfo>(arg);
self->obj.IrmInfo(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailMessage_get_OriginalCodePage(py::wrapper::Windows::ApplicationModel::Email::EmailMessage* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.OriginalCodePage());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailMessage_put_OriginalCodePage(py::wrapper::Windows::ApplicationModel::Email::EmailMessage* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<int32_t>(arg);
self->obj.OriginalCodePage(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailMessage_get_SentTime(py::wrapper::Windows::ApplicationModel::Email::EmailMessage* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.SentTime());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailMessage_put_SentTime(py::wrapper::Windows::ApplicationModel::Email::EmailMessage* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::Windows::Foundation::IReference<winrt::Windows::Foundation::DateTime>>(arg);
self->obj.SentTime(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailMessage_get_Sender(py::wrapper::Windows::ApplicationModel::Email::EmailMessage* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Sender());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailMessage_put_Sender(py::wrapper::Windows::ApplicationModel::Email::EmailMessage* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::Windows::ApplicationModel::Email::EmailRecipient>(arg);
self->obj.Sender(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailMessage_get_RemoteId(py::wrapper::Windows::ApplicationModel::Email::EmailMessage* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.RemoteId());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailMessage_put_RemoteId(py::wrapper::Windows::ApplicationModel::Email::EmailMessage* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::hstring>(arg);
self->obj.RemoteId(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailMessage_get_Preview(py::wrapper::Windows::ApplicationModel::Email::EmailMessage* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Preview());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailMessage_put_Preview(py::wrapper::Windows::ApplicationModel::Email::EmailMessage* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::hstring>(arg);
self->obj.Preview(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailMessage_get_MessageClass(py::wrapper::Windows::ApplicationModel::Email::EmailMessage* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.MessageClass());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailMessage_put_MessageClass(py::wrapper::Windows::ApplicationModel::Email::EmailMessage* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::hstring>(arg);
self->obj.MessageClass(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailMessage_get_MeetingInfo(py::wrapper::Windows::ApplicationModel::Email::EmailMessage* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.MeetingInfo());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailMessage_put_MeetingInfo(py::wrapper::Windows::ApplicationModel::Email::EmailMessage* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::Windows::ApplicationModel::Email::EmailMeetingInfo>(arg);
self->obj.MeetingInfo(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailMessage_get_LastResponseKind(py::wrapper::Windows::ApplicationModel::Email::EmailMessage* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.LastResponseKind());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailMessage_put_LastResponseKind(py::wrapper::Windows::ApplicationModel::Email::EmailMessage* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::Windows::ApplicationModel::Email::EmailMessageResponseKind>(arg);
self->obj.LastResponseKind(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailMessage_get_IsSeen(py::wrapper::Windows::ApplicationModel::Email::EmailMessage* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.IsSeen());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailMessage_put_IsSeen(py::wrapper::Windows::ApplicationModel::Email::EmailMessage* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<bool>(arg);
self->obj.IsSeen(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailMessage_get_IsRead(py::wrapper::Windows::ApplicationModel::Email::EmailMessage* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.IsRead());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailMessage_put_IsRead(py::wrapper::Windows::ApplicationModel::Email::EmailMessage* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<bool>(arg);
self->obj.IsRead(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailMessage_get_IsServerSearchMessage(py::wrapper::Windows::ApplicationModel::Email::EmailMessage* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.IsServerSearchMessage());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* EmailMessage_get_IsSmartSendable(py::wrapper::Windows::ApplicationModel::Email::EmailMessage* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.IsSmartSendable());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* EmailMessage_get_MailboxId(py::wrapper::Windows::ApplicationModel::Email::EmailMessage* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.MailboxId());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* EmailMessage_get_ChangeNumber(py::wrapper::Windows::ApplicationModel::Email::EmailMessage* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.ChangeNumber());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* EmailMessage_get_ConversationId(py::wrapper::Windows::ApplicationModel::Email::EmailMessage* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.ConversationId());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* EmailMessage_get_NormalizedSubject(py::wrapper::Windows::ApplicationModel::Email::EmailMessage* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.NormalizedSubject());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* EmailMessage_get_FolderId(py::wrapper::Windows::ApplicationModel::Email::EmailMessage* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.FolderId());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* EmailMessage_get_HasPartialBodies(py::wrapper::Windows::ApplicationModel::Email::EmailMessage* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.HasPartialBodies());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* EmailMessage_get_Id(py::wrapper::Windows::ApplicationModel::Email::EmailMessage* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Id());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* EmailMessage_get_InResponseToMessageId(py::wrapper::Windows::ApplicationModel::Email::EmailMessage* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.InResponseToMessageId());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* EmailMessage_get_IsDraftMessage(py::wrapper::Windows::ApplicationModel::Email::EmailMessage* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.IsDraftMessage());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* EmailMessage_get_SmimeKind(py::wrapper::Windows::ApplicationModel::Email::EmailMessage* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.SmimeKind());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailMessage_put_SmimeKind(py::wrapper::Windows::ApplicationModel::Email::EmailMessage* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::Windows::ApplicationModel::Email::EmailMessageSmimeKind>(arg);
self->obj.SmimeKind(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailMessage_get_SmimeData(py::wrapper::Windows::ApplicationModel::Email::EmailMessage* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.SmimeData());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailMessage_put_SmimeData(py::wrapper::Windows::ApplicationModel::Email::EmailMessage* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::Windows::Storage::Streams::IRandomAccessStreamReference>(arg);
self->obj.SmimeData(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailMessage_get_SentRepresenting(py::wrapper::Windows::ApplicationModel::Email::EmailMessage* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.SentRepresenting());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailMessage_put_SentRepresenting(py::wrapper::Windows::ApplicationModel::Email::EmailMessage* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::Windows::ApplicationModel::Email::EmailRecipient>(arg);
self->obj.SentRepresenting(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailMessage_get_ReplyTo(py::wrapper::Windows::ApplicationModel::Email::EmailMessage* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.ReplyTo());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* _from_EmailMessage(PyObject* /*unused*/, PyObject* arg) noexcept
{
try
{
auto return_value = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg);
return py::convert(return_value.as<winrt::Windows::ApplicationModel::Email::EmailMessage>());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyMethodDef _methods_EmailMessage[] = {
{ "get_body_stream", reinterpret_cast<PyCFunction>(EmailMessage_GetBodyStream), METH_VARARGS, nullptr },
{ "set_body_stream", reinterpret_cast<PyCFunction>(EmailMessage_SetBodyStream), METH_VARARGS, nullptr },
{ "_from", reinterpret_cast<PyCFunction>(_from_EmailMessage), METH_O | METH_STATIC, nullptr },
{ }
};
static PyGetSetDef _getset_EmailMessage[] = {
{ "subject", reinterpret_cast<getter>(EmailMessage_get_Subject), reinterpret_cast<setter>(EmailMessage_put_Subject), nullptr, nullptr },
{ "body", reinterpret_cast<getter>(EmailMessage_get_Body), reinterpret_cast<setter>(EmailMessage_put_Body), nullptr, nullptr },
{ "bcc", reinterpret_cast<getter>(EmailMessage_get_Bcc), nullptr, nullptr, nullptr },
{ "c_c", reinterpret_cast<getter>(EmailMessage_get_CC), nullptr, nullptr, nullptr },
{ "attachments", reinterpret_cast<getter>(EmailMessage_get_Attachments), nullptr, nullptr, nullptr },
{ "to", reinterpret_cast<getter>(EmailMessage_get_To), nullptr, nullptr, nullptr },
{ "allow_internet_images", reinterpret_cast<getter>(EmailMessage_get_AllowInternetImages), reinterpret_cast<setter>(EmailMessage_put_AllowInternetImages), nullptr, nullptr },
{ "flag_state", reinterpret_cast<getter>(EmailMessage_get_FlagState), reinterpret_cast<setter>(EmailMessage_put_FlagState), nullptr, nullptr },
{ "estimated_download_size_in_bytes", reinterpret_cast<getter>(EmailMessage_get_EstimatedDownloadSizeInBytes), reinterpret_cast<setter>(EmailMessage_put_EstimatedDownloadSizeInBytes), nullptr, nullptr },
{ "download_state", reinterpret_cast<getter>(EmailMessage_get_DownloadState), reinterpret_cast<setter>(EmailMessage_put_DownloadState), nullptr, nullptr },
{ "importance", reinterpret_cast<getter>(EmailMessage_get_Importance), reinterpret_cast<setter>(EmailMessage_put_Importance), nullptr, nullptr },
{ "irm_info", reinterpret_cast<getter>(EmailMessage_get_IrmInfo), reinterpret_cast<setter>(EmailMessage_put_IrmInfo), nullptr, nullptr },
{ "original_code_page", reinterpret_cast<getter>(EmailMessage_get_OriginalCodePage), reinterpret_cast<setter>(EmailMessage_put_OriginalCodePage), nullptr, nullptr },
{ "sent_time", reinterpret_cast<getter>(EmailMessage_get_SentTime), reinterpret_cast<setter>(EmailMessage_put_SentTime), nullptr, nullptr },
{ "sender", reinterpret_cast<getter>(EmailMessage_get_Sender), reinterpret_cast<setter>(EmailMessage_put_Sender), nullptr, nullptr },
{ "remote_id", reinterpret_cast<getter>(EmailMessage_get_RemoteId), reinterpret_cast<setter>(EmailMessage_put_RemoteId), nullptr, nullptr },
{ "preview", reinterpret_cast<getter>(EmailMessage_get_Preview), reinterpret_cast<setter>(EmailMessage_put_Preview), nullptr, nullptr },
{ "message_class", reinterpret_cast<getter>(EmailMessage_get_MessageClass), reinterpret_cast<setter>(EmailMessage_put_MessageClass), nullptr, nullptr },
{ "meeting_info", reinterpret_cast<getter>(EmailMessage_get_MeetingInfo), reinterpret_cast<setter>(EmailMessage_put_MeetingInfo), nullptr, nullptr },
{ "last_response_kind", reinterpret_cast<getter>(EmailMessage_get_LastResponseKind), reinterpret_cast<setter>(EmailMessage_put_LastResponseKind), nullptr, nullptr },
{ "is_seen", reinterpret_cast<getter>(EmailMessage_get_IsSeen), reinterpret_cast<setter>(EmailMessage_put_IsSeen), nullptr, nullptr },
{ "is_read", reinterpret_cast<getter>(EmailMessage_get_IsRead), reinterpret_cast<setter>(EmailMessage_put_IsRead), nullptr, nullptr },
{ "is_server_search_message", reinterpret_cast<getter>(EmailMessage_get_IsServerSearchMessage), nullptr, nullptr, nullptr },
{ "is_smart_sendable", reinterpret_cast<getter>(EmailMessage_get_IsSmartSendable), nullptr, nullptr, nullptr },
{ "mailbox_id", reinterpret_cast<getter>(EmailMessage_get_MailboxId), nullptr, nullptr, nullptr },
{ "change_number", reinterpret_cast<getter>(EmailMessage_get_ChangeNumber), nullptr, nullptr, nullptr },
{ "conversation_id", reinterpret_cast<getter>(EmailMessage_get_ConversationId), nullptr, nullptr, nullptr },
{ "normalized_subject", reinterpret_cast<getter>(EmailMessage_get_NormalizedSubject), nullptr, nullptr, nullptr },
{ "folder_id", reinterpret_cast<getter>(EmailMessage_get_FolderId), nullptr, nullptr, nullptr },
{ "has_partial_bodies", reinterpret_cast<getter>(EmailMessage_get_HasPartialBodies), nullptr, nullptr, nullptr },
{ "id", reinterpret_cast<getter>(EmailMessage_get_Id), nullptr, nullptr, nullptr },
{ "in_response_to_message_id", reinterpret_cast<getter>(EmailMessage_get_InResponseToMessageId), nullptr, nullptr, nullptr },
{ "is_draft_message", reinterpret_cast<getter>(EmailMessage_get_IsDraftMessage), nullptr, nullptr, nullptr },
{ "smime_kind", reinterpret_cast<getter>(EmailMessage_get_SmimeKind), reinterpret_cast<setter>(EmailMessage_put_SmimeKind), nullptr, nullptr },
{ "smime_data", reinterpret_cast<getter>(EmailMessage_get_SmimeData), reinterpret_cast<setter>(EmailMessage_put_SmimeData), nullptr, nullptr },
{ "sent_representing", reinterpret_cast<getter>(EmailMessage_get_SentRepresenting), reinterpret_cast<setter>(EmailMessage_put_SentRepresenting), nullptr, nullptr },
{ "reply_to", reinterpret_cast<getter>(EmailMessage_get_ReplyTo), nullptr, nullptr, nullptr },
{ }
};
static PyType_Slot _type_slots_EmailMessage[] =
{
{ Py_tp_new, _new_EmailMessage },
{ Py_tp_dealloc, _dealloc_EmailMessage },
{ Py_tp_methods, _methods_EmailMessage },
{ Py_tp_getset, _getset_EmailMessage },
{ },
};
static PyType_Spec _type_spec_EmailMessage =
{
"_winsdk_Windows_ApplicationModel_Email.EmailMessage",
sizeof(py::wrapper::Windows::ApplicationModel::Email::EmailMessage),
0,
Py_TPFLAGS_DEFAULT,
_type_slots_EmailMessage
};
// ----- EmailMessageBatch class --------------------
constexpr const char* const _type_name_EmailMessageBatch = "EmailMessageBatch";
static PyObject* _new_EmailMessageBatch(PyTypeObject* type, PyObject* args, PyObject* kwds) noexcept
{
py::set_invalid_activation_error(_type_name_EmailMessageBatch);
return nullptr;
}
static void _dealloc_EmailMessageBatch(py::wrapper::Windows::ApplicationModel::Email::EmailMessageBatch* self)
{
auto hash_value = std::hash<winrt::Windows::Foundation::IInspectable>{}(self->obj);
py::wrapped_instance(hash_value, nullptr);
self->obj = nullptr;
}
static PyObject* EmailMessageBatch_get_Messages(py::wrapper::Windows::ApplicationModel::Email::EmailMessageBatch* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Messages());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* EmailMessageBatch_get_Status(py::wrapper::Windows::ApplicationModel::Email::EmailMessageBatch* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Status());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* _from_EmailMessageBatch(PyObject* /*unused*/, PyObject* arg) noexcept
{
try
{
auto return_value = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg);
return py::convert(return_value.as<winrt::Windows::ApplicationModel::Email::EmailMessageBatch>());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyMethodDef _methods_EmailMessageBatch[] = {
{ "_from", reinterpret_cast<PyCFunction>(_from_EmailMessageBatch), METH_O | METH_STATIC, nullptr },
{ }
};
static PyGetSetDef _getset_EmailMessageBatch[] = {
{ "messages", reinterpret_cast<getter>(EmailMessageBatch_get_Messages), nullptr, nullptr, nullptr },
{ "status", reinterpret_cast<getter>(EmailMessageBatch_get_Status), nullptr, nullptr, nullptr },
{ }
};
static PyType_Slot _type_slots_EmailMessageBatch[] =
{
{ Py_tp_new, _new_EmailMessageBatch },
{ Py_tp_dealloc, _dealloc_EmailMessageBatch },
{ Py_tp_methods, _methods_EmailMessageBatch },
{ Py_tp_getset, _getset_EmailMessageBatch },
{ },
};
static PyType_Spec _type_spec_EmailMessageBatch =
{
"_winsdk_Windows_ApplicationModel_Email.EmailMessageBatch",
sizeof(py::wrapper::Windows::ApplicationModel::Email::EmailMessageBatch),
0,
Py_TPFLAGS_DEFAULT,
_type_slots_EmailMessageBatch
};
// ----- EmailMessageReader class --------------------
constexpr const char* const _type_name_EmailMessageReader = "EmailMessageReader";
static PyObject* _new_EmailMessageReader(PyTypeObject* type, PyObject* args, PyObject* kwds) noexcept
{
py::set_invalid_activation_error(_type_name_EmailMessageReader);
return nullptr;
}
static void _dealloc_EmailMessageReader(py::wrapper::Windows::ApplicationModel::Email::EmailMessageReader* self)
{
auto hash_value = std::hash<winrt::Windows::Foundation::IInspectable>{}(self->obj);
py::wrapped_instance(hash_value, nullptr);
self->obj = nullptr;
}
static PyObject* EmailMessageReader_ReadBatchAsync(py::wrapper::Windows::ApplicationModel::Email::EmailMessageReader* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 0)
{
try
{
return py::convert(self->obj.ReadBatchAsync());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* _from_EmailMessageReader(PyObject* /*unused*/, PyObject* arg) noexcept
{
try
{
auto return_value = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg);
return py::convert(return_value.as<winrt::Windows::ApplicationModel::Email::EmailMessageReader>());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyMethodDef _methods_EmailMessageReader[] = {
{ "read_batch_async", reinterpret_cast<PyCFunction>(EmailMessageReader_ReadBatchAsync), METH_VARARGS, nullptr },
{ "_from", reinterpret_cast<PyCFunction>(_from_EmailMessageReader), METH_O | METH_STATIC, nullptr },
{ }
};
static PyGetSetDef _getset_EmailMessageReader[] = {
{ }
};
static PyType_Slot _type_slots_EmailMessageReader[] =
{
{ Py_tp_new, _new_EmailMessageReader },
{ Py_tp_dealloc, _dealloc_EmailMessageReader },
{ Py_tp_methods, _methods_EmailMessageReader },
{ Py_tp_getset, _getset_EmailMessageReader },
{ },
};
static PyType_Spec _type_spec_EmailMessageReader =
{
"_winsdk_Windows_ApplicationModel_Email.EmailMessageReader",
sizeof(py::wrapper::Windows::ApplicationModel::Email::EmailMessageReader),
0,
Py_TPFLAGS_DEFAULT,
_type_slots_EmailMessageReader
};
// ----- EmailQueryOptions class --------------------
constexpr const char* const _type_name_EmailQueryOptions = "EmailQueryOptions";
static PyObject* _new_EmailQueryOptions(PyTypeObject* type, PyObject* args, PyObject* kwds) noexcept
{
if (kwds != nullptr)
{
py::set_invalid_kwd_args_error();
return nullptr;
}
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
winrt::Windows::ApplicationModel::Email::EmailQueryOptions instance{ param0 };
return py::wrap(instance, type);
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
auto param1 = py::convert_to<winrt::Windows::ApplicationModel::Email::EmailQuerySearchFields>(args, 1);
winrt::Windows::ApplicationModel::Email::EmailQueryOptions instance{ param0, param1 };
return py::wrap(instance, type);
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else if (arg_count == 0)
{
try
{
winrt::Windows::ApplicationModel::Email::EmailQueryOptions instance{ };
return py::wrap(instance, type);
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static void _dealloc_EmailQueryOptions(py::wrapper::Windows::ApplicationModel::Email::EmailQueryOptions* self)
{
auto hash_value = std::hash<winrt::Windows::Foundation::IInspectable>{}(self->obj);
py::wrapped_instance(hash_value, nullptr);
self->obj = nullptr;
}
static PyObject* EmailQueryOptions_get_SortProperty(py::wrapper::Windows::ApplicationModel::Email::EmailQueryOptions* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.SortProperty());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailQueryOptions_put_SortProperty(py::wrapper::Windows::ApplicationModel::Email::EmailQueryOptions* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::Windows::ApplicationModel::Email::EmailQuerySortProperty>(arg);
self->obj.SortProperty(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailQueryOptions_get_SortDirection(py::wrapper::Windows::ApplicationModel::Email::EmailQueryOptions* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.SortDirection());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailQueryOptions_put_SortDirection(py::wrapper::Windows::ApplicationModel::Email::EmailQueryOptions* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::Windows::ApplicationModel::Email::EmailQuerySortDirection>(arg);
self->obj.SortDirection(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailQueryOptions_get_Kind(py::wrapper::Windows::ApplicationModel::Email::EmailQueryOptions* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Kind());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailQueryOptions_put_Kind(py::wrapper::Windows::ApplicationModel::Email::EmailQueryOptions* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::Windows::ApplicationModel::Email::EmailQueryKind>(arg);
self->obj.Kind(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailQueryOptions_get_FolderIds(py::wrapper::Windows::ApplicationModel::Email::EmailQueryOptions* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.FolderIds());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* EmailQueryOptions_get_TextSearch(py::wrapper::Windows::ApplicationModel::Email::EmailQueryOptions* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.TextSearch());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* _from_EmailQueryOptions(PyObject* /*unused*/, PyObject* arg) noexcept
{
try
{
auto return_value = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg);
return py::convert(return_value.as<winrt::Windows::ApplicationModel::Email::EmailQueryOptions>());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyMethodDef _methods_EmailQueryOptions[] = {
{ "_from", reinterpret_cast<PyCFunction>(_from_EmailQueryOptions), METH_O | METH_STATIC, nullptr },
{ }
};
static PyGetSetDef _getset_EmailQueryOptions[] = {
{ "sort_property", reinterpret_cast<getter>(EmailQueryOptions_get_SortProperty), reinterpret_cast<setter>(EmailQueryOptions_put_SortProperty), nullptr, nullptr },
{ "sort_direction", reinterpret_cast<getter>(EmailQueryOptions_get_SortDirection), reinterpret_cast<setter>(EmailQueryOptions_put_SortDirection), nullptr, nullptr },
{ "kind", reinterpret_cast<getter>(EmailQueryOptions_get_Kind), reinterpret_cast<setter>(EmailQueryOptions_put_Kind), nullptr, nullptr },
{ "folder_ids", reinterpret_cast<getter>(EmailQueryOptions_get_FolderIds), nullptr, nullptr, nullptr },
{ "text_search", reinterpret_cast<getter>(EmailQueryOptions_get_TextSearch), nullptr, nullptr, nullptr },
{ }
};
static PyType_Slot _type_slots_EmailQueryOptions[] =
{
{ Py_tp_new, _new_EmailQueryOptions },
{ Py_tp_dealloc, _dealloc_EmailQueryOptions },
{ Py_tp_methods, _methods_EmailQueryOptions },
{ Py_tp_getset, _getset_EmailQueryOptions },
{ },
};
static PyType_Spec _type_spec_EmailQueryOptions =
{
"_winsdk_Windows_ApplicationModel_Email.EmailQueryOptions",
sizeof(py::wrapper::Windows::ApplicationModel::Email::EmailQueryOptions),
0,
Py_TPFLAGS_DEFAULT,
_type_slots_EmailQueryOptions
};
// ----- EmailQueryTextSearch class --------------------
constexpr const char* const _type_name_EmailQueryTextSearch = "EmailQueryTextSearch";
static PyObject* _new_EmailQueryTextSearch(PyTypeObject* type, PyObject* args, PyObject* kwds) noexcept
{
py::set_invalid_activation_error(_type_name_EmailQueryTextSearch);
return nullptr;
}
static void _dealloc_EmailQueryTextSearch(py::wrapper::Windows::ApplicationModel::Email::EmailQueryTextSearch* self)
{
auto hash_value = std::hash<winrt::Windows::Foundation::IInspectable>{}(self->obj);
py::wrapped_instance(hash_value, nullptr);
self->obj = nullptr;
}
static PyObject* EmailQueryTextSearch_get_Text(py::wrapper::Windows::ApplicationModel::Email::EmailQueryTextSearch* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Text());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailQueryTextSearch_put_Text(py::wrapper::Windows::ApplicationModel::Email::EmailQueryTextSearch* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::hstring>(arg);
self->obj.Text(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailQueryTextSearch_get_SearchScope(py::wrapper::Windows::ApplicationModel::Email::EmailQueryTextSearch* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.SearchScope());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailQueryTextSearch_put_SearchScope(py::wrapper::Windows::ApplicationModel::Email::EmailQueryTextSearch* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::Windows::ApplicationModel::Email::EmailQuerySearchScope>(arg);
self->obj.SearchScope(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailQueryTextSearch_get_Fields(py::wrapper::Windows::ApplicationModel::Email::EmailQueryTextSearch* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Fields());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailQueryTextSearch_put_Fields(py::wrapper::Windows::ApplicationModel::Email::EmailQueryTextSearch* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::Windows::ApplicationModel::Email::EmailQuerySearchFields>(arg);
self->obj.Fields(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* _from_EmailQueryTextSearch(PyObject* /*unused*/, PyObject* arg) noexcept
{
try
{
auto return_value = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg);
return py::convert(return_value.as<winrt::Windows::ApplicationModel::Email::EmailQueryTextSearch>());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyMethodDef _methods_EmailQueryTextSearch[] = {
{ "_from", reinterpret_cast<PyCFunction>(_from_EmailQueryTextSearch), METH_O | METH_STATIC, nullptr },
{ }
};
static PyGetSetDef _getset_EmailQueryTextSearch[] = {
{ "text", reinterpret_cast<getter>(EmailQueryTextSearch_get_Text), reinterpret_cast<setter>(EmailQueryTextSearch_put_Text), nullptr, nullptr },
{ "search_scope", reinterpret_cast<getter>(EmailQueryTextSearch_get_SearchScope), reinterpret_cast<setter>(EmailQueryTextSearch_put_SearchScope), nullptr, nullptr },
{ "fields", reinterpret_cast<getter>(EmailQueryTextSearch_get_Fields), reinterpret_cast<setter>(EmailQueryTextSearch_put_Fields), nullptr, nullptr },
{ }
};
static PyType_Slot _type_slots_EmailQueryTextSearch[] =
{
{ Py_tp_new, _new_EmailQueryTextSearch },
{ Py_tp_dealloc, _dealloc_EmailQueryTextSearch },
{ Py_tp_methods, _methods_EmailQueryTextSearch },
{ Py_tp_getset, _getset_EmailQueryTextSearch },
{ },
};
static PyType_Spec _type_spec_EmailQueryTextSearch =
{
"_winsdk_Windows_ApplicationModel_Email.EmailQueryTextSearch",
sizeof(py::wrapper::Windows::ApplicationModel::Email::EmailQueryTextSearch),
0,
Py_TPFLAGS_DEFAULT,
_type_slots_EmailQueryTextSearch
};
// ----- EmailRecipient class --------------------
constexpr const char* const _type_name_EmailRecipient = "EmailRecipient";
static PyObject* _new_EmailRecipient(PyTypeObject* type, PyObject* args, PyObject* kwds) noexcept
{
if (kwds != nullptr)
{
py::set_invalid_kwd_args_error();
return nullptr;
}
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
winrt::Windows::ApplicationModel::Email::EmailRecipient instance{ param0 };
return py::wrap(instance, type);
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
auto param1 = py::convert_to<winrt::hstring>(args, 1);
winrt::Windows::ApplicationModel::Email::EmailRecipient instance{ param0, param1 };
return py::wrap(instance, type);
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else if (arg_count == 0)
{
try
{
winrt::Windows::ApplicationModel::Email::EmailRecipient instance{ };
return py::wrap(instance, type);
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static void _dealloc_EmailRecipient(py::wrapper::Windows::ApplicationModel::Email::EmailRecipient* self)
{
auto hash_value = std::hash<winrt::Windows::Foundation::IInspectable>{}(self->obj);
py::wrapped_instance(hash_value, nullptr);
self->obj = nullptr;
}
static PyObject* EmailRecipient_get_Name(py::wrapper::Windows::ApplicationModel::Email::EmailRecipient* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Name());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailRecipient_put_Name(py::wrapper::Windows::ApplicationModel::Email::EmailRecipient* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::hstring>(arg);
self->obj.Name(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailRecipient_get_Address(py::wrapper::Windows::ApplicationModel::Email::EmailRecipient* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Address());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailRecipient_put_Address(py::wrapper::Windows::ApplicationModel::Email::EmailRecipient* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::hstring>(arg);
self->obj.Address(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* _from_EmailRecipient(PyObject* /*unused*/, PyObject* arg) noexcept
{
try
{
auto return_value = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg);
return py::convert(return_value.as<winrt::Windows::ApplicationModel::Email::EmailRecipient>());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyMethodDef _methods_EmailRecipient[] = {
{ "_from", reinterpret_cast<PyCFunction>(_from_EmailRecipient), METH_O | METH_STATIC, nullptr },
{ }
};
static PyGetSetDef _getset_EmailRecipient[] = {
{ "name", reinterpret_cast<getter>(EmailRecipient_get_Name), reinterpret_cast<setter>(EmailRecipient_put_Name), nullptr, nullptr },
{ "address", reinterpret_cast<getter>(EmailRecipient_get_Address), reinterpret_cast<setter>(EmailRecipient_put_Address), nullptr, nullptr },
{ }
};
static PyType_Slot _type_slots_EmailRecipient[] =
{
{ Py_tp_new, _new_EmailRecipient },
{ Py_tp_dealloc, _dealloc_EmailRecipient },
{ Py_tp_methods, _methods_EmailRecipient },
{ Py_tp_getset, _getset_EmailRecipient },
{ },
};
static PyType_Spec _type_spec_EmailRecipient =
{
"_winsdk_Windows_ApplicationModel_Email.EmailRecipient",
sizeof(py::wrapper::Windows::ApplicationModel::Email::EmailRecipient),
0,
Py_TPFLAGS_DEFAULT,
_type_slots_EmailRecipient
};
// ----- EmailRecipientResolutionResult class --------------------
constexpr const char* const _type_name_EmailRecipientResolutionResult = "EmailRecipientResolutionResult";
static PyObject* _new_EmailRecipientResolutionResult(PyTypeObject* type, PyObject* args, PyObject* kwds) noexcept
{
if (kwds != nullptr)
{
py::set_invalid_kwd_args_error();
return nullptr;
}
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 0)
{
try
{
winrt::Windows::ApplicationModel::Email::EmailRecipientResolutionResult instance{ };
return py::wrap(instance, type);
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static void _dealloc_EmailRecipientResolutionResult(py::wrapper::Windows::ApplicationModel::Email::EmailRecipientResolutionResult* self)
{
auto hash_value = std::hash<winrt::Windows::Foundation::IInspectable>{}(self->obj);
py::wrapped_instance(hash_value, nullptr);
self->obj = nullptr;
}
static PyObject* EmailRecipientResolutionResult_SetPublicKeys(py::wrapper::Windows::ApplicationModel::Email::EmailRecipientResolutionResult* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::Windows::Foundation::Collections::IIterable<winrt::Windows::Security::Cryptography::Certificates::Certificate>>(args, 0);
self->obj.SetPublicKeys(param0);
Py_RETURN_NONE;
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* EmailRecipientResolutionResult_get_Status(py::wrapper::Windows::ApplicationModel::Email::EmailRecipientResolutionResult* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.Status());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static int EmailRecipientResolutionResult_put_Status(py::wrapper::Windows::ApplicationModel::Email::EmailRecipientResolutionResult* self, PyObject* arg, void* /*unused*/) noexcept
{
if (arg == nullptr)
{
PyErr_SetString(PyExc_TypeError, "property delete not supported");
return -1;
}
try
{
auto param0 = py::convert_to<winrt::Windows::ApplicationModel::Email::EmailRecipientResolutionStatus>(arg);
self->obj.Status(param0);
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyObject* EmailRecipientResolutionResult_get_PublicKeys(py::wrapper::Windows::ApplicationModel::Email::EmailRecipientResolutionResult* self, void* /*unused*/) noexcept
{
try
{
return py::convert(self->obj.PublicKeys());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyObject* _from_EmailRecipientResolutionResult(PyObject* /*unused*/, PyObject* arg) noexcept
{
try
{
auto return_value = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg);
return py::convert(return_value.as<winrt::Windows::ApplicationModel::Email::EmailRecipientResolutionResult>());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyMethodDef _methods_EmailRecipientResolutionResult[] = {
{ "set_public_keys", reinterpret_cast<PyCFunction>(EmailRecipientResolutionResult_SetPublicKeys), METH_VARARGS, nullptr },
{ "_from", reinterpret_cast<PyCFunction>(_from_EmailRecipientResolutionResult), METH_O | METH_STATIC, nullptr },
{ }
};
static PyGetSetDef _getset_EmailRecipientResolutionResult[] = {
{ "status", reinterpret_cast<getter>(EmailRecipientResolutionResult_get_Status), reinterpret_cast<setter>(EmailRecipientResolutionResult_put_Status), nullptr, nullptr },
{ "public_keys", reinterpret_cast<getter>(EmailRecipientResolutionResult_get_PublicKeys), nullptr, nullptr, nullptr },
{ }
};
static PyType_Slot _type_slots_EmailRecipientResolutionResult[] =
{
{ Py_tp_new, _new_EmailRecipientResolutionResult },
{ Py_tp_dealloc, _dealloc_EmailRecipientResolutionResult },
{ Py_tp_methods, _methods_EmailRecipientResolutionResult },
{ Py_tp_getset, _getset_EmailRecipientResolutionResult },
{ },
};
static PyType_Spec _type_spec_EmailRecipientResolutionResult =
{
"_winsdk_Windows_ApplicationModel_Email.EmailRecipientResolutionResult",
sizeof(py::wrapper::Windows::ApplicationModel::Email::EmailRecipientResolutionResult),
0,
Py_TPFLAGS_DEFAULT,
_type_slots_EmailRecipientResolutionResult
};
// ----- EmailStore class --------------------
constexpr const char* const _type_name_EmailStore = "EmailStore";
static PyObject* _new_EmailStore(PyTypeObject* type, PyObject* args, PyObject* kwds) noexcept
{
py::set_invalid_activation_error(_type_name_EmailStore);
return nullptr;
}
static void _dealloc_EmailStore(py::wrapper::Windows::ApplicationModel::Email::EmailStore* self)
{
auto hash_value = std::hash<winrt::Windows::Foundation::IInspectable>{}(self->obj);
py::wrapped_instance(hash_value, nullptr);
self->obj = nullptr;
}
static PyObject* EmailStore_CreateMailboxAsync(py::wrapper::Windows::ApplicationModel::Email::EmailStore* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 2)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
auto param1 = py::convert_to<winrt::hstring>(args, 1);
return py::convert(self->obj.CreateMailboxAsync(param0, param1));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else if (arg_count == 3)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
auto param1 = py::convert_to<winrt::hstring>(args, 1);
auto param2 = py::convert_to<winrt::hstring>(args, 2);
return py::convert(self->obj.CreateMailboxAsync(param0, param1, param2));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* EmailStore_FindMailboxesAsync(py::wrapper::Windows::ApplicationModel::Email::EmailStore* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 0)
{
try
{
return py::convert(self->obj.FindMailboxesAsync());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* EmailStore_GetConversationAsync(py::wrapper::Windows::ApplicationModel::Email::EmailStore* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
return py::convert(self->obj.GetConversationAsync(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* EmailStore_GetConversationReader(py::wrapper::Windows::ApplicationModel::Email::EmailStore* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 0)
{
try
{
return py::convert(self->obj.GetConversationReader());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::Windows::ApplicationModel::Email::EmailQueryOptions>(args, 0);
return py::convert(self->obj.GetConversationReader(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* EmailStore_GetFolderAsync(py::wrapper::Windows::ApplicationModel::Email::EmailStore* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
return py::convert(self->obj.GetFolderAsync(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* EmailStore_GetMailboxAsync(py::wrapper::Windows::ApplicationModel::Email::EmailStore* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
return py::convert(self->obj.GetMailboxAsync(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* EmailStore_GetMessageAsync(py::wrapper::Windows::ApplicationModel::Email::EmailStore* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::hstring>(args, 0);
return py::convert(self->obj.GetMessageAsync(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* EmailStore_GetMessageReader(py::wrapper::Windows::ApplicationModel::Email::EmailStore* self, PyObject* args) noexcept
{
Py_ssize_t arg_count = PyTuple_Size(args);
if (arg_count == 0)
{
try
{
return py::convert(self->obj.GetMessageReader());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else if (arg_count == 1)
{
try
{
auto param0 = py::convert_to<winrt::Windows::ApplicationModel::Email::EmailQueryOptions>(args, 0);
return py::convert(self->obj.GetMessageReader(param0));
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
else
{
py::set_invalid_arg_count_error(arg_count);
return nullptr;
}
}
static PyObject* _from_EmailStore(PyObject* /*unused*/, PyObject* arg) noexcept
{
try
{
auto return_value = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg);
return py::convert(return_value.as<winrt::Windows::ApplicationModel::Email::EmailStore>());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyMethodDef _methods_EmailStore[] = {
{ "create_mailbox_async", reinterpret_cast<PyCFunction>(EmailStore_CreateMailboxAsync), METH_VARARGS, nullptr },
{ "find_mailboxes_async", reinterpret_cast<PyCFunction>(EmailStore_FindMailboxesAsync), METH_VARARGS, nullptr },
{ "get_conversation_async", reinterpret_cast<PyCFunction>(EmailStore_GetConversationAsync), METH_VARARGS, nullptr },
{ "get_conversation_reader", reinterpret_cast<PyCFunction>(EmailStore_GetConversationReader), METH_VARARGS, nullptr },
{ "get_folder_async", reinterpret_cast<PyCFunction>(EmailStore_GetFolderAsync), METH_VARARGS, nullptr },
{ "get_mailbox_async", reinterpret_cast<PyCFunction>(EmailStore_GetMailboxAsync), METH_VARARGS, nullptr },
{ "get_message_async", reinterpret_cast<PyCFunction>(EmailStore_GetMessageAsync), METH_VARARGS, nullptr },
{ "get_message_reader", reinterpret_cast<PyCFunction>(EmailStore_GetMessageReader), METH_VARARGS, nullptr },
{ "_from", reinterpret_cast<PyCFunction>(_from_EmailStore), METH_O | METH_STATIC, nullptr },
{ }
};
static PyGetSetDef _getset_EmailStore[] = {
{ }
};
static PyType_Slot _type_slots_EmailStore[] =
{
{ Py_tp_new, _new_EmailStore },
{ Py_tp_dealloc, _dealloc_EmailStore },
{ Py_tp_methods, _methods_EmailStore },
{ Py_tp_getset, _getset_EmailStore },
{ },
};
static PyType_Spec _type_spec_EmailStore =
{
"_winsdk_Windows_ApplicationModel_Email.EmailStore",
sizeof(py::wrapper::Windows::ApplicationModel::Email::EmailStore),
0,
Py_TPFLAGS_DEFAULT,
_type_slots_EmailStore
};
// ----- EmailStoreNotificationTriggerDetails class --------------------
constexpr const char* const _type_name_EmailStoreNotificationTriggerDetails = "EmailStoreNotificationTriggerDetails";
static PyObject* _new_EmailStoreNotificationTriggerDetails(PyTypeObject* type, PyObject* args, PyObject* kwds) noexcept
{
py::set_invalid_activation_error(_type_name_EmailStoreNotificationTriggerDetails);
return nullptr;
}
static void _dealloc_EmailStoreNotificationTriggerDetails(py::wrapper::Windows::ApplicationModel::Email::EmailStoreNotificationTriggerDetails* self)
{
auto hash_value = std::hash<winrt::Windows::Foundation::IInspectable>{}(self->obj);
py::wrapped_instance(hash_value, nullptr);
self->obj = nullptr;
}
static PyObject* _from_EmailStoreNotificationTriggerDetails(PyObject* /*unused*/, PyObject* arg) noexcept
{
try
{
auto return_value = py::convert_to<winrt::Windows::Foundation::IInspectable>(arg);
return py::convert(return_value.as<winrt::Windows::ApplicationModel::Email::EmailStoreNotificationTriggerDetails>());
}
catch (...)
{
py::to_PyErr();
return nullptr;
}
}
static PyMethodDef _methods_EmailStoreNotificationTriggerDetails[] = {
{ "_from", reinterpret_cast<PyCFunction>(_from_EmailStoreNotificationTriggerDetails), METH_O | METH_STATIC, nullptr },
{ }
};
static PyGetSetDef _getset_EmailStoreNotificationTriggerDetails[] = {
{ }
};
static PyType_Slot _type_slots_EmailStoreNotificationTriggerDetails[] =
{
{ Py_tp_new, _new_EmailStoreNotificationTriggerDetails },
{ Py_tp_dealloc, _dealloc_EmailStoreNotificationTriggerDetails },
{ Py_tp_methods, _methods_EmailStoreNotificationTriggerDetails },
{ Py_tp_getset, _getset_EmailStoreNotificationTriggerDetails },
{ },
};
static PyType_Spec _type_spec_EmailStoreNotificationTriggerDetails =
{
"_winsdk_Windows_ApplicationModel_Email.EmailStoreNotificationTriggerDetails",
sizeof(py::wrapper::Windows::ApplicationModel::Email::EmailStoreNotificationTriggerDetails),
0,
Py_TPFLAGS_DEFAULT,
_type_slots_EmailStoreNotificationTriggerDetails
};
// ----- Windows.ApplicationModel.Email Initialization --------------------
static int module_exec(PyObject* module) noexcept
{
try
{
py::pyobj_handle bases { PyTuple_Pack(1, py::winrt_type<py::Object>::python_type) };
py::winrt_type<winrt::Windows::ApplicationModel::Email::EmailAttachment>::python_type = py::register_python_type(module, _type_name_EmailAttachment, &_type_spec_EmailAttachment, bases.get());
py::winrt_type<winrt::Windows::ApplicationModel::Email::EmailConversation>::python_type = py::register_python_type(module, _type_name_EmailConversation, &_type_spec_EmailConversation, bases.get());
py::winrt_type<winrt::Windows::ApplicationModel::Email::EmailConversationBatch>::python_type = py::register_python_type(module, _type_name_EmailConversationBatch, &_type_spec_EmailConversationBatch, bases.get());
py::winrt_type<winrt::Windows::ApplicationModel::Email::EmailConversationReader>::python_type = py::register_python_type(module, _type_name_EmailConversationReader, &_type_spec_EmailConversationReader, bases.get());
py::winrt_type<winrt::Windows::ApplicationModel::Email::EmailFolder>::python_type = py::register_python_type(module, _type_name_EmailFolder, &_type_spec_EmailFolder, bases.get());
py::winrt_type<winrt::Windows::ApplicationModel::Email::EmailIrmInfo>::python_type = py::register_python_type(module, _type_name_EmailIrmInfo, &_type_spec_EmailIrmInfo, bases.get());
py::winrt_type<winrt::Windows::ApplicationModel::Email::EmailIrmTemplate>::python_type = py::register_python_type(module, _type_name_EmailIrmTemplate, &_type_spec_EmailIrmTemplate, bases.get());
py::winrt_type<winrt::Windows::ApplicationModel::Email::EmailItemCounts>::python_type = py::register_python_type(module, _type_name_EmailItemCounts, &_type_spec_EmailItemCounts, bases.get());
py::winrt_type<winrt::Windows::ApplicationModel::Email::EmailMailbox>::python_type = py::register_python_type(module, _type_name_EmailMailbox, &_type_spec_EmailMailbox, bases.get());
py::winrt_type<winrt::Windows::ApplicationModel::Email::EmailMailboxAction>::python_type = py::register_python_type(module, _type_name_EmailMailboxAction, &_type_spec_EmailMailboxAction, bases.get());
py::winrt_type<winrt::Windows::ApplicationModel::Email::EmailMailboxAutoReply>::python_type = py::register_python_type(module, _type_name_EmailMailboxAutoReply, &_type_spec_EmailMailboxAutoReply, bases.get());
py::winrt_type<winrt::Windows::ApplicationModel::Email::EmailMailboxAutoReplySettings>::python_type = py::register_python_type(module, _type_name_EmailMailboxAutoReplySettings, &_type_spec_EmailMailboxAutoReplySettings, bases.get());
py::winrt_type<winrt::Windows::ApplicationModel::Email::EmailMailboxCapabilities>::python_type = py::register_python_type(module, _type_name_EmailMailboxCapabilities, &_type_spec_EmailMailboxCapabilities, bases.get());
py::winrt_type<winrt::Windows::ApplicationModel::Email::EmailMailboxChange>::python_type = py::register_python_type(module, _type_name_EmailMailboxChange, &_type_spec_EmailMailboxChange, bases.get());
py::winrt_type<winrt::Windows::ApplicationModel::Email::EmailMailboxChangeReader>::python_type = py::register_python_type(module, _type_name_EmailMailboxChangeReader, &_type_spec_EmailMailboxChangeReader, bases.get());
py::winrt_type<winrt::Windows::ApplicationModel::Email::EmailMailboxChangeTracker>::python_type = py::register_python_type(module, _type_name_EmailMailboxChangeTracker, &_type_spec_EmailMailboxChangeTracker, bases.get());
py::winrt_type<winrt::Windows::ApplicationModel::Email::EmailMailboxChangedDeferral>::python_type = py::register_python_type(module, _type_name_EmailMailboxChangedDeferral, &_type_spec_EmailMailboxChangedDeferral, bases.get());
py::winrt_type<winrt::Windows::ApplicationModel::Email::EmailMailboxChangedEventArgs>::python_type = py::register_python_type(module, _type_name_EmailMailboxChangedEventArgs, &_type_spec_EmailMailboxChangedEventArgs, bases.get());
py::winrt_type<winrt::Windows::ApplicationModel::Email::EmailMailboxCreateFolderResult>::python_type = py::register_python_type(module, _type_name_EmailMailboxCreateFolderResult, &_type_spec_EmailMailboxCreateFolderResult, bases.get());
py::winrt_type<winrt::Windows::ApplicationModel::Email::EmailMailboxPolicies>::python_type = py::register_python_type(module, _type_name_EmailMailboxPolicies, &_type_spec_EmailMailboxPolicies, bases.get());
py::winrt_type<winrt::Windows::ApplicationModel::Email::EmailMailboxSyncManager>::python_type = py::register_python_type(module, _type_name_EmailMailboxSyncManager, &_type_spec_EmailMailboxSyncManager, bases.get());
py::winrt_type<winrt::Windows::ApplicationModel::Email::EmailManager>::python_type = py::register_python_type(module, _type_name_EmailManager, &_type_spec_EmailManager, nullptr);
py::winrt_type<winrt::Windows::ApplicationModel::Email::EmailManagerForUser>::python_type = py::register_python_type(module, _type_name_EmailManagerForUser, &_type_spec_EmailManagerForUser, bases.get());
py::winrt_type<winrt::Windows::ApplicationModel::Email::EmailMeetingInfo>::python_type = py::register_python_type(module, _type_name_EmailMeetingInfo, &_type_spec_EmailMeetingInfo, bases.get());
py::winrt_type<winrt::Windows::ApplicationModel::Email::EmailMessage>::python_type = py::register_python_type(module, _type_name_EmailMessage, &_type_spec_EmailMessage, bases.get());
py::winrt_type<winrt::Windows::ApplicationModel::Email::EmailMessageBatch>::python_type = py::register_python_type(module, _type_name_EmailMessageBatch, &_type_spec_EmailMessageBatch, bases.get());
py::winrt_type<winrt::Windows::ApplicationModel::Email::EmailMessageReader>::python_type = py::register_python_type(module, _type_name_EmailMessageReader, &_type_spec_EmailMessageReader, bases.get());
py::winrt_type<winrt::Windows::ApplicationModel::Email::EmailQueryOptions>::python_type = py::register_python_type(module, _type_name_EmailQueryOptions, &_type_spec_EmailQueryOptions, bases.get());
py::winrt_type<winrt::Windows::ApplicationModel::Email::EmailQueryTextSearch>::python_type = py::register_python_type(module, _type_name_EmailQueryTextSearch, &_type_spec_EmailQueryTextSearch, bases.get());
py::winrt_type<winrt::Windows::ApplicationModel::Email::EmailRecipient>::python_type = py::register_python_type(module, _type_name_EmailRecipient, &_type_spec_EmailRecipient, bases.get());
py::winrt_type<winrt::Windows::ApplicationModel::Email::EmailRecipientResolutionResult>::python_type = py::register_python_type(module, _type_name_EmailRecipientResolutionResult, &_type_spec_EmailRecipientResolutionResult, bases.get());
py::winrt_type<winrt::Windows::ApplicationModel::Email::EmailStore>::python_type = py::register_python_type(module, _type_name_EmailStore, &_type_spec_EmailStore, bases.get());
py::winrt_type<winrt::Windows::ApplicationModel::Email::EmailStoreNotificationTriggerDetails>::python_type = py::register_python_type(module, _type_name_EmailStoreNotificationTriggerDetails, &_type_spec_EmailStoreNotificationTriggerDetails, bases.get());
return 0;
}
catch (...)
{
py::to_PyErr();
return -1;
}
}
static PyModuleDef_Slot module_slots[] = {{Py_mod_exec, module_exec}, {}};
PyDoc_STRVAR(module_doc, "Windows.ApplicationModel.Email");
static PyModuleDef module_def
= {PyModuleDef_HEAD_INIT,
"_winsdk_Windows_ApplicationModel_Email",
module_doc,
0,
nullptr,
module_slots,
nullptr,
nullptr,
nullptr};
} // py::cpp::Windows::ApplicationModel::Email
PyMODINIT_FUNC
PyInit__winsdk_Windows_ApplicationModel_Email (void) noexcept
{
return PyModuleDef_Init(&py::cpp::Windows::ApplicationModel::Email::module_def);
}
| 33.376568 | 269 | 0.590571 | [
"object"
] |
bfe0c475fdce6708025e778ccae3254f01a08921 | 11,808 | hh | C++ | benchmarks/solvers/minizinc/include/minizinc/astiterator.hh | 95A31/MDD-LNS | 9b78143e13ce8b3916bf3cc9662d9cbfe63fd7c7 | [
"MIT"
] | null | null | null | benchmarks/solvers/minizinc/include/minizinc/astiterator.hh | 95A31/MDD-LNS | 9b78143e13ce8b3916bf3cc9662d9cbfe63fd7c7 | [
"MIT"
] | null | null | null | benchmarks/solvers/minizinc/include/minizinc/astiterator.hh | 95A31/MDD-LNS | 9b78143e13ce8b3916bf3cc9662d9cbfe63fd7c7 | [
"MIT"
] | null | null | null | /* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
* Main authors:
* Guido Tack <guido.tack@monash.edu>
*/
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#pragma once
#include <minizinc/ast.hh>
#include <minizinc/hash.hh>
namespace MiniZinc {
/**
* \brief Bottom-up iterator for expressions
*/
template <class T>
class BottomUpIterator {
protected:
/// The visitor to call back during iteration
T& _t;
/// Stack item
struct C {
/// Expression on the stack
Expression* e;
/// Whether this expression has been visited before
bool done;
/// If part of a generator expression, which one it is
int genNumber;
/// Constructor
C(Expression* e0) : e(e0), done(false), genNumber(-1) {}
/// Constructor for generator expression
C(Expression* e0, int genNumber0) : e(e0), done(true), genNumber(genNumber0) {}
};
/// Push all elements of \a v onto \a stack
template <class E>
void pushVec(std::vector<C>& stack, ASTExprVec<E> v) {
for (unsigned int i = 0; i < v.size(); i++) {
stack.push_back(C(v[i]));
}
}
public:
/// Constructor
BottomUpIterator(T& t) : _t(t) {}
/// Run iterator on expression \a e
void run(Expression* root);
};
template <class T>
void bottom_up(T& t, Expression* e) {
BottomUpIterator<T>(t).run(e);
}
/**
* \brief Leaf iterator for expressions
*/
template <class T>
class TopDownIterator {
protected:
/// The visitor to call back during iteration
T& _t;
/// Push all elements of \a v onto \a stack
template <class E>
static void pushVec(std::vector<Expression*>& stack, ASTExprVec<E> v) {
for (unsigned int i = 0; i < v.size(); i++) {
stack.push_back(v[i]);
}
}
public:
/// Constructor
TopDownIterator(T& t) : _t(t) {}
/// Run iterator on expression \a e
void run(Expression* root);
};
template <class T>
void top_down(T& t, Expression* root) {
TopDownIterator<T>(t).run(root);
}
/* IMPLEMENTATION */
template <class T>
void BottomUpIterator<T>::run(Expression* root) {
std::vector<C> stack;
if (_t.enter(root)) {
stack.push_back(C(root));
}
while (!stack.empty()) {
C& c = stack.back();
if (c.e == nullptr) {
stack.pop_back();
continue;
}
if (c.done) {
switch (c.e->eid()) {
case Expression::E_INTLIT:
_t.vIntLit(*c.e->template cast<IntLit>());
break;
case Expression::E_FLOATLIT:
_t.vFloatLit(*c.e->template cast<FloatLit>());
break;
case Expression::E_SETLIT:
_t.vSetLit(*c.e->template cast<SetLit>());
break;
case Expression::E_BOOLLIT:
_t.vBoolLit(*c.e->template cast<BoolLit>());
break;
case Expression::E_STRINGLIT:
_t.vStringLit(*c.e->template cast<StringLit>());
break;
case Expression::E_ID:
_t.vId(*c.e->template cast<Id>());
break;
case Expression::E_ANON:
_t.vAnonVar(*c.e->template cast<AnonVar>());
break;
case Expression::E_ARRAYLIT:
_t.vArrayLit(*c.e->template cast<ArrayLit>());
break;
case Expression::E_ARRAYACCESS:
_t.vArrayAccess(*c.e->template cast<ArrayAccess>());
break;
case Expression::E_COMP:
if (c.genNumber >= 0) {
_t.vComprehensionGenerator(*c.e->template cast<Comprehension>(), c.genNumber);
} else {
_t.vComprehension(*c.e->template cast<Comprehension>());
}
break;
case Expression::E_ITE:
_t.vITE(*c.e->template cast<ITE>());
break;
case Expression::E_BINOP:
_t.vBinOp(*c.e->template cast<BinOp>());
break;
case Expression::E_UNOP:
_t.vUnOp(*c.e->template cast<UnOp>());
break;
case Expression::E_CALL:
_t.vCall(*c.e->template cast<Call>());
break;
case Expression::E_VARDECL:
_t.vVarDecl(*c.e->template cast<VarDecl>());
break;
case Expression::E_LET:
_t.vLet(*c.e->template cast<Let>());
break;
case Expression::E_TI:
_t.vTypeInst(*c.e->template cast<TypeInst>());
break;
case Expression::E_TIID:
_t.vTIId(*c.e->template cast<TIId>());
break;
}
_t.exit(c.e);
stack.pop_back();
} else {
c.done = true;
Expression* ce = c.e;
for (ExpressionSetIter it = ce->ann().begin(); it != ce->ann().end(); ++it) {
if (_t.enter(*it)) {
stack.push_back(C(*it));
}
}
if (_t.enter(ce)) {
switch (ce->eid()) {
case Expression::E_INTLIT:
case Expression::E_FLOATLIT:
case Expression::E_BOOLLIT:
case Expression::E_STRINGLIT:
case Expression::E_ANON:
case Expression::E_ID:
case Expression::E_TIID:
break;
case Expression::E_SETLIT:
pushVec(stack, ce->template cast<SetLit>()->v());
break;
case Expression::E_ARRAYLIT: {
for (unsigned int i = 0; i < ce->cast<ArrayLit>()->size(); i++) {
stack.push_back((*ce->cast<ArrayLit>())[i]);
}
} break;
case Expression::E_ARRAYACCESS:
pushVec(stack, ce->template cast<ArrayAccess>()->idx());
stack.push_back(C(ce->template cast<ArrayAccess>()->v()));
break;
case Expression::E_COMP: {
auto* comp = ce->template cast<Comprehension>();
stack.push_back(C(comp->e()));
for (unsigned int i = comp->numberOfGenerators(); (i--) != 0U;) {
for (unsigned int j = comp->numberOfDecls(i); (j--) != 0U;) {
stack.push_back(C(comp->decl(i, j)));
}
if (comp->in(i) != nullptr) {
stack.push_back(C(comp->where(i)));
stack.push_back(C(comp, i));
stack.push_back(C(comp->in(i)));
} else {
stack.push_back(C(comp, i));
stack.push_back(C(comp->where(i)));
}
}
} break;
case Expression::E_ITE: {
ITE* ite = ce->template cast<ITE>();
stack.push_back(C(ite->elseExpr()));
for (int i = 0; i < ite->size(); i++) {
stack.push_back(C(ite->ifExpr(i)));
stack.push_back(C(ite->thenExpr(i)));
}
} break;
case Expression::E_BINOP:
stack.push_back(C(ce->template cast<BinOp>()->rhs()));
stack.push_back(C(ce->template cast<BinOp>()->lhs()));
break;
case Expression::E_UNOP:
stack.push_back(C(ce->template cast<UnOp>()->e()));
break;
case Expression::E_CALL:
for (unsigned int i = 0; i < ce->template cast<Call>()->argCount(); i++) {
stack.push_back(ce->template cast<Call>()->arg(i));
}
break;
case Expression::E_VARDECL:
stack.push_back(C(ce->template cast<VarDecl>()->e()));
stack.push_back(C(ce->template cast<VarDecl>()->ti()));
break;
case Expression::E_LET:
stack.push_back(C(ce->template cast<Let>()->in()));
pushVec(stack, ce->template cast<Let>()->let());
break;
case Expression::E_TI:
stack.push_back(C(ce->template cast<TypeInst>()->domain()));
pushVec(stack, ce->template cast<TypeInst>()->ranges());
break;
}
} else {
c.e = nullptr;
}
}
}
}
template <class T>
void TopDownIterator<T>::run(Expression* root) {
std::vector<Expression*> stack;
if (_t.enter(root)) {
stack.push_back(root);
}
while (!stack.empty()) {
Expression* e = stack.back();
stack.pop_back();
if (e == nullptr) {
continue;
}
if (!_t.enter(e)) {
continue;
}
for (ExpressionSetIter it = e->ann().begin(); it != e->ann().end(); ++it) {
stack.push_back(*it);
}
switch (e->eid()) {
case Expression::E_INTLIT:
_t.vIntLit(*e->template cast<IntLit>());
break;
case Expression::E_FLOATLIT:
_t.vFloatLit(*e->template cast<FloatLit>());
break;
case Expression::E_SETLIT:
_t.vSetLit(*e->template cast<SetLit>());
pushVec(stack, e->template cast<SetLit>()->v());
break;
case Expression::E_BOOLLIT:
_t.vBoolLit(*e->template cast<BoolLit>());
break;
case Expression::E_STRINGLIT:
_t.vStringLit(*e->template cast<StringLit>());
break;
case Expression::E_ID:
_t.vId(*e->template cast<Id>());
break;
case Expression::E_ANON:
_t.vAnonVar(*e->template cast<AnonVar>());
break;
case Expression::E_ARRAYLIT:
_t.vArrayLit(*e->template cast<ArrayLit>());
for (unsigned int i = 0; i < e->cast<ArrayLit>()->size(); i++) {
stack.push_back((*e->cast<ArrayLit>())[i]);
}
break;
case Expression::E_ARRAYACCESS:
_t.vArrayAccess(*e->template cast<ArrayAccess>());
pushVec(stack, e->template cast<ArrayAccess>()->idx());
stack.push_back(e->template cast<ArrayAccess>()->v());
break;
case Expression::E_COMP:
_t.vComprehension(*e->template cast<Comprehension>());
{
auto* comp = e->template cast<Comprehension>();
for (unsigned int i = comp->numberOfGenerators(); (i--) != 0U;) {
stack.push_back(comp->where(i));
stack.push_back(comp->in(i));
for (unsigned int j = comp->numberOfDecls(i); (j--) != 0U;) {
stack.push_back(comp->decl(i, j));
}
}
stack.push_back(comp->e());
}
break;
case Expression::E_ITE:
_t.vITE(*e->template cast<ITE>());
{
ITE* ite = e->template cast<ITE>();
stack.push_back(ite->elseExpr());
for (int i = 0; i < ite->size(); i++) {
stack.push_back(ite->ifExpr(i));
stack.push_back(ite->thenExpr(i));
}
}
break;
case Expression::E_BINOP:
_t.vBinOp(*e->template cast<BinOp>());
stack.push_back(e->template cast<BinOp>()->rhs());
stack.push_back(e->template cast<BinOp>()->lhs());
break;
case Expression::E_UNOP:
_t.vUnOp(*e->template cast<UnOp>());
stack.push_back(e->template cast<UnOp>()->e());
break;
case Expression::E_CALL:
_t.vCall(*e->template cast<Call>());
for (unsigned int i = 0; i < e->template cast<Call>()->argCount(); i++) {
stack.push_back(e->template cast<Call>()->arg(i));
}
break;
case Expression::E_VARDECL:
_t.vVarDecl(*e->template cast<VarDecl>());
stack.push_back(e->template cast<VarDecl>()->e());
stack.push_back(e->template cast<VarDecl>()->ti());
break;
case Expression::E_LET:
_t.vLet(*e->template cast<Let>());
stack.push_back(e->template cast<Let>()->in());
pushVec(stack, e->template cast<Let>()->let());
break;
case Expression::E_TI:
_t.vTypeInst(*e->template cast<TypeInst>());
stack.push_back(e->template cast<TypeInst>()->domain());
pushVec(stack, e->template cast<TypeInst>()->ranges());
break;
case Expression::E_TIID:
_t.vTIId(*e->template cast<TIId>());
break;
}
}
}
} // namespace MiniZinc
| 31.913514 | 90 | 0.539634 | [
"vector"
] |
bfe60d97992693765ca5eae3d001774ce7517d1b | 1,724 | cpp | C++ | KickStart/2022/C/c.cpp | a4org/Angorithm4 | d2227d36608491bed270375bcea67fbde134209a | [
"MIT"
] | null | null | null | KickStart/2022/C/c.cpp | a4org/Angorithm4 | d2227d36608491bed270375bcea67fbde134209a | [
"MIT"
] | null | null | null | KickStart/2022/C/c.cpp | a4org/Angorithm4 | d2227d36608491bed270375bcea67fbde134209a | [
"MIT"
] | null | null | null | #include <iostream>
#include <unordered_map>
#include <vector>
using namespace::std;
int all = 0;
void move(unordered_map<int, pair<int, int>>& pd, unordered_map<int, int> pa, int ant, int L) {
pair<int, int> *antp = &pd[ant];
// Handle the first situation
if (antp->second == -1) return; // falls off
int curr = antp->first;
if (antp->second == 1) {
// right
if (pa.find(curr+1) != pa.end() && pd[pa[curr+1]].second == 0) {
antp->second = 0;
pd[pa[curr]].second = 1;
} else {
antp->first++;
if (antp->first > L) {
antp->second = -1;
cout << ant << " ";
all++;
}
}
} else {
// left
if (pa.find(curr-1) != pa.end() && pd[pa[curr-1]].second == 1) {
antp->second = 1;
pd[pa[curr]].second = 0;
} else {
antp->first--;
if (antp->first < 1) {
antp->second = -1;
cout << ant << " ";
all++;
}
}
}
}
void test_case(int no) {
int N, L;
cin >> N >> L;
all = 0;
unordered_map<int, pair<int, int>> posDir;
for (int i = 1; i <= N; i++) {
int pos, dir;
cin >> pos >> dir;
posDir[i] = {pos, dir};
// distinct pos
}
cout << "Case #" << no << ": ";
while (true) {
// time simulation:
unordered_map<int, int> posAnt = {}; // which ant at position i?
for (int i = 1; i <= N; i++) {
int pos = posDir[i].first;
if (posAnt.find(pos) != posAnt.end()) {
cout << "Error! Not distinct!" << endl;
break;
}
posAnt[pos] = i;
}
for (int i = 1; i <= N; i++) {
move(posDir, posAnt, i, L);
}
if (all == N) break;
}
cout << '\n';
}
int main() {
int N;
cin >> N;
int i = 1;
while (i <= N) {
test_case(i);
i++;
}
}
| 18.340426 | 95 | 0.482019 | [
"vector"
] |
bfe68e9f7ed4a1ee45f065780b0c0b3c2a97f5b3 | 1,143 | cpp | C++ | L2-027/main.cpp | Heliovic/GPLT | 7e8745e589a6b6594d4db24a2030f3b0e6efe38b | [
"MIT"
] | 1 | 2019-03-14T05:35:16.000Z | 2019-03-14T05:35:16.000Z | L2-027/main.cpp | Heliovic/GPLT | 7e8745e589a6b6594d4db24a2030f3b0e6efe38b | [
"MIT"
] | null | null | null | L2-027/main.cpp | Heliovic/GPLT | 7e8745e589a6b6594d4db24a2030f3b0e6efe38b | [
"MIT"
] | null | null | null | #include <cstdio>
#include <vector>
#include <algorithm>
#include <cstring>
#define MAX_N 10240
using namespace std;
struct stu
{
char account[64];
int score;
};
int N, G, K;
vector<stu> stus;
int rnk[MAX_N];
bool cmp(stu& s1, stu& s2)
{
if (s1.score != s2.score)
return s1.score > s2.score;
else
return strcmp(s1.account, s2.account) < 0;
}
int main()
{
scanf("%d %d %d", &N, &G, &K);
int pat = 0;
for (int i = 0; i < N; i++)
{
stu s;
scanf("%s %d", s.account, &s.score);
if (s.score >= G && s.score <= 100)
pat += 50;
else if (s.score < G && s.score >= 60)
pat += 20;
stus.push_back(s);
}
printf("%d\n", pat);
sort(stus.begin(), stus.end(), cmp);
rnk[0] = 1;
for (int i = 1; i < N; i++)
{
if (stus[i].score == stus[i - 1].score)
rnk[i] = rnk[i - 1];
else
rnk[i] = i + 1;
}
int ptr = 0;
while (ptr < N && rnk[ptr] <= K)
{
printf("%d %s %d\n", rnk[ptr], stus[ptr].account, stus[ptr].score);
ptr++;
}
return 0;
}
| 16.565217 | 75 | 0.461942 | [
"vector"
] |
bfed12420b046e72448d5805dc39aec62eec209f | 6,223 | cc | C++ | src/table_store/table/table_store.cc | avwsolutions/pixie | 21f4726499d0c4ed0a5ed1be29977dc639ac98c6 | [
"Apache-2.0"
] | null | null | null | src/table_store/table/table_store.cc | avwsolutions/pixie | 21f4726499d0c4ed0a5ed1be29977dc639ac98c6 | [
"Apache-2.0"
] | null | null | null | src/table_store/table/table_store.cc | avwsolutions/pixie | 21f4726499d0c4ed0a5ed1be29977dc639ac98c6 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2018- The Pixie 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.
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <algorithm>
#include <utility>
#include <vector>
#include "src/table_store/table/table_store.h"
namespace px {
namespace table_store {
std::unique_ptr<std::unordered_map<std::string, schema::Relation>> TableStore::GetRelationMap() {
auto map = std::make_unique<RelationMap>();
map->reserve(name_to_relation_map_.size());
for (auto& [table_name, relation] : name_to_relation_map_) {
map->emplace(table_name, relation);
}
return map;
}
StatusOr<Table*> TableStore::CreateNewTablet(uint64_t table_id, const types::TabletID& tablet_id) {
auto id_to_table_info_map_iter = id_to_table_info_map_.find(table_id);
if (id_to_table_info_map_iter == id_to_table_info_map_.end()) {
return error::InvalidArgument("Table_id $0 doesn't exist.", table_id);
}
const TableInfo& table_info = id_to_table_info_map_iter->second;
const schema::Relation& relation = table_info.relation;
std::shared_ptr<Table> new_tablet = Table::Create(relation);
TableIDTablet id_key = {table_id, tablet_id};
id_to_table_map_[id_key] = new_tablet;
const std::string& table_name = table_info.table_name;
DCHECK(relation == name_to_relation_map_.find(table_name)->second);
NameTablet name_key = {table_name, tablet_id};
name_to_table_map_[name_key] = new_tablet;
return new_tablet.get();
}
Status TableStore::AppendData(uint64_t table_id, types::TabletID tablet_id,
std::unique_ptr<px::types::ColumnWrapperRecordBatch> record_batch) {
Table* table = GetTable(table_id, tablet_id);
// We create new tablets only if the table at `table_id` exists, otherwise errors out.
if (table == nullptr) {
PL_ASSIGN_OR_RETURN(table, CreateNewTablet(table_id, tablet_id));
}
return table->TransferRecordBatch(std::move(record_batch));
}
table_store::Table* TableStore::GetTable(const std::string& table_name,
const types::TabletID& tablet_id) const {
auto name_to_table_iter = name_to_table_map_.find(NameTablet{table_name, tablet_id});
if (name_to_table_iter == name_to_table_map_.end()) {
return nullptr;
}
return name_to_table_iter->second.get();
}
table_store::Table* TableStore::GetTable(uint64_t table_id,
const types::TabletID& tablet_id) const {
auto id_to_table_iter = id_to_table_map_.find(TableIDTablet{table_id, tablet_id});
if (id_to_table_iter == id_to_table_map_.end()) {
return nullptr;
}
return id_to_table_iter->second.get();
}
void TableStore::RegisterTableName(const std::string& table_name, const types::TabletID& tablet_id,
const schema::Relation& table_relation,
std::shared_ptr<table_store::Table> table) {
auto name_to_relation_map_iter = name_to_relation_map_.find(table_name);
if (name_to_relation_map_iter == name_to_relation_map_.end()) {
name_to_relation_map_[table_name] = table_relation;
} else {
DCHECK_EQ(name_to_relation_map_iter->second, table_relation);
}
NameTablet key = {table_name, tablet_id};
name_to_table_map_[key] = table;
}
void TableStore::RegisterTableID(uint64_t table_id, TableInfo table_info,
const types::TabletID& tablet_id,
std::shared_ptr<table_store::Table> table) {
// Lookup whether the table already exists in the relation map, add if it does not.
auto id_to_table_info_map_iter = id_to_table_info_map_.find(table_id);
if (id_to_table_info_map_iter == id_to_table_info_map_.end()) {
id_to_table_info_map_[table_id] = table_info;
} else {
DCHECK_EQ(id_to_table_info_map_iter->second.relation, table_info.relation);
}
TableIDTablet key{table_id, tablet_id};
id_to_table_map_[key] = table;
}
void TableStore::AddTable(std::shared_ptr<table_store::Table> table, const std::string& table_name,
std::optional<uint64_t> table_id, const types::TabletID& tablet_id) {
const auto& table_relation = table->GetRelation();
// Register the table by name.
RegisterTableName(table_name, tablet_id, table_relation, table);
// Register the table by ID, if one is present.
if (table_id.has_value()) {
RegisterTableID(table_id.value(), TableInfo{table_name, table_relation}, tablet_id, table);
}
}
Status TableStore::AddTableAlias(uint64_t table_id, const std::string& table_name) {
auto table_iter = name_to_table_map_.find({table_name, ""});
if (table_iter == name_to_table_map_.end()) {
return error::Internal(
"Could not create table alias. Could not find table for $0 If the target table is "
"tabletized, aliasing is not yet supported.",
table_name);
}
std::shared_ptr<Table> table_ptr = table_iter->second;
auto relation_iter = name_to_relation_map_.find(table_name);
if (relation_iter == name_to_relation_map_.end()) {
return error::Internal("Could not create table alias. Could not find relation for $0.",
table_name);
}
const schema::Relation& relation = relation_iter->second;
RegisterTableID(table_id, TableInfo{table_name, relation}, "", std::move(table_ptr));
return Status::OK();
}
Status TableStore::SchemaAsProto(schemapb::Schema* schema) const {
return schema::Schema::ToProto(schema, name_to_relation_map_);
}
std::vector<uint64_t> TableStore::GetTableIDs() const {
std::vector<uint64_t> ids;
for (const auto& it : id_to_table_map_) {
ids.emplace_back(it.first.table_id_);
}
return ids;
}
} // namespace table_store
} // namespace px
| 38.41358 | 99 | 0.713643 | [
"vector"
] |
bff47d431f87effd5d17355dca770456db761725 | 6,984 | cpp | C++ | Source/Entity/Components/StaticMeshComponent.cpp | MrFrenik/Enjon | 405733f1b8d05c65bc6b4f4c779d3c6845a8c12b | [
"BSD-3-Clause"
] | 121 | 2019-05-02T01:22:17.000Z | 2022-03-19T00:16:14.000Z | Source/Entity/Components/StaticMeshComponent.cpp | MrFrenik/Enjon | 405733f1b8d05c65bc6b4f4c779d3c6845a8c12b | [
"BSD-3-Clause"
] | 42 | 2019-08-17T20:33:43.000Z | 2019-09-25T14:28:50.000Z | Source/Entity/Components/StaticMeshComponent.cpp | MrFrenik/Enjon | 405733f1b8d05c65bc6b4f4c779d3c6845a8c12b | [
"BSD-3-Clause"
] | 20 | 2019-05-02T01:22:20.000Z | 2022-01-30T04:04:57.000Z | #include "Entity/Components/StaticMeshComponent.h"
#include "Entity/EntityManager.h"
#include "Graphics/GraphicsScene.h"
#include "Serialize/AssetArchiver.h"
#include "Asset/AssetManager.h"
#include "Graphics/GraphicsSubsystem.h"
#include "SubsystemCatalog.h"
#include "ImGui/ImGuiManager.h"
#include "Entity/EntityManager.h"
#include "Base/World.h"
#include "Engine.h"
namespace Enjon
{
//====================================================================
void StaticMeshComponent::ExplicitConstructor()
{
// Set explicit tick state
mTickState = ComponentTickState::TickAlways;
}
//====================================================================
void StaticMeshComponent::ExplicitDestructor()
{
// Remove renderable from scene
if (mRenderable.GetGraphicsScene() != nullptr)
{
mRenderable.GetGraphicsScene()->RemoveStaticMeshRenderable(&mRenderable);
}
}
//====================================================================
void StaticMeshComponent::PostConstruction( )
{
// Add default mesh and material for renderable
AssetManager* am = EngineSubsystem( AssetManager );
mRenderable.SetMesh( am->GetDefaultAsset< Mesh >( ) );
// Set default materials for all material elements
for ( u32 i = 0; i < mRenderable.GetMesh( )->GetSubMeshCount( ); ++i )
{
mRenderable.SetMaterial( am->GetDefaultAsset< Material >( ), i );
}
// Get graphics scene from world graphics context
World* world = mEntity->GetWorld( )->ConstCast< World >( );
GraphicsScene* gs = world->GetContext< GraphicsSubsystemContext >( )->GetGraphicsScene( );
// Add renderable to scene
gs->AddStaticMeshRenderable( &mRenderable );
// Set id of renderable to entity id
mRenderable.SetRenderableID( mEntity->GetID( ) );
}
//====================================================================
void StaticMeshComponent::AddToWorld( World* world )
{
RemoveFromWorld( );
// Get graphics scene from world graphics context
GraphicsScene* gs = world->GetContext< GraphicsSubsystemContext >( )->GetGraphicsScene( );
// Add to graphics scene
if ( gs )
{
gs->AddStaticMeshRenderable( &mRenderable );
}
}
//====================================================================
void StaticMeshComponent::RemoveFromWorld( )
{
if ( mRenderable.GetGraphicsScene( ) != nullptr )
{
mRenderable.GetGraphicsScene( )->RemoveStaticMeshRenderable( &mRenderable );
}
}
void StaticMeshComponent::Update( )
{
mRenderable.SetTransform(mEntity->GetWorldTransform());
}
//====================================================================
Vec3 StaticMeshComponent::GetPosition() const
{
return mRenderable.GetPosition();
}
//====================================================================
Vec3 StaticMeshComponent::GetScale() const
{
return mRenderable.GetScale();
}
//====================================================================
Quaternion StaticMeshComponent::GetRotation() const
{
return mRenderable.GetRotation();
}
//====================================================================
AssetHandle< Material > StaticMeshComponent::GetMaterial( const u32& idx ) const
{
return mRenderable.GetMaterial( idx );
}
//====================================================================
AssetHandle<Mesh> StaticMeshComponent::GetMesh() const
{
return mRenderable.GetMesh();
}
//====================================================================
GraphicsScene* StaticMeshComponent::GetGraphicsScene() const
{
return mRenderable.GetGraphicsScene();
}
//====================================================================
Transform StaticMeshComponent::GetTransform() const
{
return mRenderable.GetTransform();
}
//====================================================================
StaticMeshRenderable* StaticMeshComponent::GetRenderable()
{
return &mRenderable;
}
/* Sets world transform */
void StaticMeshComponent::SetTransform( const Transform& transform )
{
mRenderable.SetTransform( transform );
}
//====================================================================
void StaticMeshComponent::SetPosition(const Vec3& position)
{
mRenderable.SetPosition(position);
}
//====================================================================
void StaticMeshComponent::SetScale(const Vec3& scale)
{
mRenderable.SetScale(scale);
}
//====================================================================
void StaticMeshComponent::SetScale(const f32& scale)
{
mRenderable.SetScale(scale);
}
//====================================================================
void StaticMeshComponent::SetRotation(const Quaternion& rotation)
{
mRenderable.SetRotation(rotation);
}
//====================================================================
void StaticMeshComponent::SetMaterial( const AssetHandle< Material >& material, const u32& idx )
{
mRenderable.SetMaterial( material, idx );
}
//====================================================================
void StaticMeshComponent::SetMesh(const AssetHandle<Mesh>& mesh)
{
mRenderable.SetMesh( mesh );
}
//====================================================================
void StaticMeshComponent::SetGraphicsScene(GraphicsScene* scene)
{
mRenderable.SetGraphicsScene(scene);
}
//====================================================================
Result StaticMeshComponent::SerializeData( ByteBuffer* buffer ) const
{
// Write uuid of mesh
buffer->Write< UUID >( mRenderable.GetMesh( )->GetUUID( ) );
// Write out renderable material size
buffer->Write< u32 >( mRenderable.GetMaterialsCount( ) );
// Write uuid of materials in renderable
for ( auto& mat : mRenderable.GetMaterials( ) )
{
buffer->Write< UUID >( mat.Get()->GetUUID( ) );
}
return Result::SUCCESS;
}
//====================================================================
Result StaticMeshComponent::DeserializeData( ByteBuffer* buffer )
{
// Get asset manager
AssetManager* am = EngineSubsystem( AssetManager );
// Set mesh
mRenderable.SetMesh( am->GetAsset< Mesh >( buffer->Read< UUID >( ) ) );
// Get count of materials
u32 matCount = buffer->Read< u32 >( );
// Deserialize materials
for ( u32 i = 0; i < matCount; ++i )
{
// Grab the material
AssetHandle< Material > mat = am->GetAsset< Material >( buffer->Read< UUID >( ) );
// Set material in renderable at index
mRenderable.SetMaterial( mat, i );
}
return Result::SUCCESS;
}
//====================================================================
Result StaticMeshComponent::OnEditorUI( )
{
ImGuiManager* igm = EngineSubsystem( ImGuiManager );
// Debug dump renderable
igm->InspectObject( &mRenderable );
// Reset renderable mesh
mRenderable.SetMesh( mRenderable.GetMesh( ) );
return Result::SUCCESS;
}
//====================================================================
}
| 26.555133 | 98 | 0.535796 | [
"mesh",
"transform"
] |
870e7ba21a41ed6a903164e47b29e3a922b1c885 | 5,987 | cc | C++ | src/ui/base/models/list_selection_model_unittest.cc | jxjnjjn/chromium | 435c1d02fd1b99001dc9e1e831632c894523580d | [
"Apache-2.0"
] | 9 | 2018-09-21T05:36:12.000Z | 2021-11-15T15:14:36.000Z | ui/base/models/list_selection_model_unittest.cc | devasia1000/chromium | 919a8a666862fb866a6bb7aa7f3ae8c0442b4828 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | ui/base/models/list_selection_model_unittest.cc | devasia1000/chromium | 919a8a666862fb866a6bb7aa7f3ae8c0442b4828 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 3 | 2018-11-28T14:54:13.000Z | 2020-07-02T07:36:07.000Z | // Copyright (c) 2012 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/base/models/list_selection_model.h"
#include <algorithm>
#include <string>
#include "base/string_number_conversions.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace ui {
typedef testing::Test ListSelectionModelTest;
// Returns the state of the selection model as a string. The format is:
// 'active=X anchor=X selection=X X X...'.
static std::string StateAsString(const ListSelectionModel& model) {
std::string result = "active=" + base::IntToString(model.active()) +
" anchor=" + base::IntToString(model.anchor()) +
" selection=";
const ListSelectionModel::SelectedIndices& selection(
model.selected_indices());
for (size_t i = 0; i < selection.size(); ++i) {
if (i != 0)
result += " ";
result += base::IntToString(selection[i]);
}
return result;
}
TEST_F(ListSelectionModelTest, InitialState) {
ListSelectionModel model;
EXPECT_EQ("active=-1 anchor=-1 selection=", StateAsString(model));
EXPECT_TRUE(model.empty());
}
TEST_F(ListSelectionModelTest, SetSelectedIndex) {
ListSelectionModel model;
model.SetSelectedIndex(2);
EXPECT_EQ("active=2 anchor=2 selection=2", StateAsString(model));
EXPECT_FALSE(model.empty());
}
TEST_F(ListSelectionModelTest, SetSelectedIndexToEmpty) {
ListSelectionModel model;
model.SetSelectedIndex(-1);
EXPECT_EQ("active=-1 anchor=-1 selection=", StateAsString(model));
EXPECT_TRUE(model.empty());
}
TEST_F(ListSelectionModelTest, IncrementFrom) {
ListSelectionModel model;
model.SetSelectedIndex(1);
model.IncrementFrom(1);
EXPECT_EQ("active=2 anchor=2 selection=2", StateAsString(model));
// Increment from 4. This shouldn't effect the selection as its past the
// end of the selection.
model.IncrementFrom(4);
EXPECT_EQ("active=2 anchor=2 selection=2", StateAsString(model));
}
TEST_F(ListSelectionModelTest, DecrementFrom) {
ListSelectionModel model;
model.SetSelectedIndex(2);
model.DecrementFrom(0);
EXPECT_EQ("active=1 anchor=1 selection=1", StateAsString(model));
// Shift down from 1. As the selection as the index being removed, this should
// clear the selection.
model.DecrementFrom(1);
EXPECT_EQ("active=-1 anchor=-1 selection=", StateAsString(model));
// Reset the selection to 2, and shift down from 4. This shouldn't do
// anything.
model.SetSelectedIndex(2);
model.DecrementFrom(4);
EXPECT_EQ("active=2 anchor=2 selection=2", StateAsString(model));
}
TEST_F(ListSelectionModelTest, IsSelected) {
ListSelectionModel model;
model.SetSelectedIndex(2);
EXPECT_FALSE(model.IsSelected(0));
EXPECT_TRUE(model.IsSelected(2));
}
TEST_F(ListSelectionModelTest, AddIndexToSelected) {
ListSelectionModel model;
model.AddIndexToSelection(2);
EXPECT_EQ("active=-1 anchor=-1 selection=2", StateAsString(model));
model.AddIndexToSelection(4);
EXPECT_EQ("active=-1 anchor=-1 selection=2 4", StateAsString(model));
}
TEST_F(ListSelectionModelTest, RemoveIndexFromSelection) {
ListSelectionModel model;
model.SetSelectedIndex(2);
model.AddIndexToSelection(4);
EXPECT_EQ("active=2 anchor=2 selection=2 4", StateAsString(model));
model.RemoveIndexFromSelection(4);
EXPECT_EQ("active=2 anchor=2 selection=2", StateAsString(model));
model.RemoveIndexFromSelection(2);
EXPECT_EQ("active=2 anchor=2 selection=", StateAsString(model));
}
TEST_F(ListSelectionModelTest, SetSelectionFromAnchorTo) {
ListSelectionModel model;
model.SetSelectedIndex(2);
model.SetSelectionFromAnchorTo(7);
EXPECT_EQ("active=7 anchor=2 selection=2 3 4 5 6 7", StateAsString(model));
model.Clear();
model.SetSelectedIndex(7);
model.SetSelectionFromAnchorTo(2);
EXPECT_EQ("active=2 anchor=7 selection=2 3 4 5 6 7", StateAsString(model));
model.Clear();
model.SetSelectionFromAnchorTo(7);
EXPECT_EQ("active=7 anchor=7 selection=7", StateAsString(model));
}
TEST_F(ListSelectionModelTest, Clear) {
ListSelectionModel model;
model.SetSelectedIndex(2);
model.Clear();
EXPECT_EQ("active=-1 anchor=-1 selection=", StateAsString(model));
}
TEST_F(ListSelectionModelTest, MoveToLeft) {
ListSelectionModel model;
model.SetSelectedIndex(0);
model.AddIndexToSelection(4);
model.AddIndexToSelection(10);
model.set_anchor(4);
model.set_active(4);
model.Move(4, 0);
EXPECT_EQ("active=0 anchor=0 selection=0 1 10", StateAsString(model));
}
TEST_F(ListSelectionModelTest, MoveToRight) {
ListSelectionModel model;
model.SetSelectedIndex(0);
model.AddIndexToSelection(4);
model.AddIndexToSelection(10);
model.set_anchor(0);
model.set_active(0);
model.Move(0, 3);
EXPECT_EQ("active=3 anchor=3 selection=3 4 10", StateAsString(model));
}
TEST_F(ListSelectionModelTest, Copy) {
ListSelectionModel model;
model.SetSelectedIndex(0);
model.AddIndexToSelection(4);
model.AddIndexToSelection(10);
EXPECT_EQ("active=0 anchor=0 selection=0 4 10", StateAsString(model));
ListSelectionModel model2;
model2.Copy(model);
EXPECT_EQ("active=0 anchor=0 selection=0 4 10", StateAsString(model2));
}
TEST_F(ListSelectionModelTest, AddSelectionFromAnchorTo) {
ListSelectionModel model;
model.SetSelectedIndex(2);
model.AddSelectionFromAnchorTo(4);
EXPECT_EQ("active=4 anchor=2 selection=2 3 4", StateAsString(model));
model.AddSelectionFromAnchorTo(0);
EXPECT_EQ("active=0 anchor=2 selection=0 1 2 3 4", StateAsString(model));
}
TEST_F(ListSelectionModelTest, Equals) {
ListSelectionModel model1;
model1.SetSelectedIndex(0);
model1.AddSelectionFromAnchorTo(4);
ListSelectionModel model2;
model2.SetSelectedIndex(0);
model2.AddSelectionFromAnchorTo(4);
EXPECT_TRUE(model1.Equals(model2));
EXPECT_TRUE(model2.Equals(model1));
model2.SetSelectedIndex(0);
EXPECT_FALSE(model1.Equals(model2));
EXPECT_FALSE(model2.Equals(model1));
}
} // namespace ui
| 30.237374 | 80 | 0.747787 | [
"model"
] |
870fb58e3f09f795a26bd4a46abeee59a306b373 | 1,544 | hpp | C++ | src/log.hpp | C2python/TRAFT | 01974979f76f66330a3031f036fce6f4f5b4aa28 | [
"BSL-1.0"
] | null | null | null | src/log.hpp | C2python/TRAFT | 01974979f76f66330a3031f036fce6f4f5b4aa28 | [
"BSL-1.0"
] | null | null | null | src/log.hpp | C2python/TRAFT | 01974979f76f66330a3031f036fce6f4f5b4aa28 | [
"BSL-1.0"
] | null | null | null | #ifndef TRAFT_LOG_H
#define TRAFT_LOG_H
#include<vector>
#include<queue>
#include<mutex>
#include<thread>
#include<condition_variable>
#include<atomic>
#include<cassert>
#include<string>
#include<iostream>
#include "on_exit.hpp"
#include "util.hpp"
#include "entry.hpp"
namespace TRAFT{
class Log{
private:
int m_fd; //Log file descriptor
Log** m_exit;
std::vector<std::shared_ptr<Entry>> m_new;
std::queue<std::shared_ptr<Entry>> m_recent;
int max_new;
int max_recent;
std::string m_log_file;
uid_t m_uid;
gid_t m_gid;
std::atomic<bool> m_stop{true};
std::thread logHandle;
std::mutex lock_queue;
std::mutex lock_flush;
std::condition_variable cond_queue;
std::condition_variable cond_flush;
pthread_t m_queue_mutex_holder;
pthread_t m_flush_mutex_holder;
void _flush(std::vector<std::shared_ptr<Entry>>&,bool crash=false);
public:
Log(const std::string&);
~Log();
void set_flush_on_exit();
void flush();
void start();
void stop();
bool is_started();
int open_log_file(const std::string&);
void thread_handle(const std::string name);
void join();
void detach();
std::shared_ptr<Entry> create_entry(short level,pthread_t,const std::string&);
std::shared_ptr<Entry> create_entry(short level,pthread_t p_id = pthread_self());
void submit_entry(std::shared_ptr<Entry>);
int set_log_file(const std::string& log_file);
std::string get_log_file(){
return m_log_file;
}
};
}
#endif | 20.586667 | 85 | 0.685881 | [
"vector"
] |
8712c7522f36ea7d80d3dc9f4342cc20c8b152c1 | 9,308 | cpp | C++ | archive/olddraw/Draw/DrawOpX11.cpp | dreamsxin/ultimatepp | 41d295d999f9ff1339b34b43c99ce279b9b3991c | [
"BSD-2-Clause"
] | 2 | 2016-04-07T07:54:26.000Z | 2020-04-14T12:37:34.000Z | archive/olddraw/Draw/DrawOpX11.cpp | dreamsxin/ultimatepp | 41d295d999f9ff1339b34b43c99ce279b9b3991c | [
"BSD-2-Clause"
] | null | null | null | archive/olddraw/Draw/DrawOpX11.cpp | dreamsxin/ultimatepp | 41d295d999f9ff1339b34b43c99ce279b9b3991c | [
"BSD-2-Clause"
] | null | null | null | #include "Draw.h"
NAMESPACE_UPP
#ifdef PLATFORM_X11
#define LLOG(x) // LOG(x)
#define LTIMING(x) // TIMING(x)
void Draw::BeginOp()
{
Cloff f = cloff.Top();
Vector<Rect> newclip;
newclip <<= clip.Top();
f.clipi = clip.GetCount();
clip.Add() = newclip;
cloff.Add(f);
}
void Draw::OffsetOp(Point p)
{
Cloff f = cloff.Top();
f.offseti = offset.GetCount();
actual_offset += p;
offset.Add(actual_offset);
cloff.Add(f);
}
bool Draw::ClipOp(const Rect& r)
{
LLOG("Draw::ClipOp(" << r << ")");
Cloff f = cloff.Top();
bool ch = false;
Vector<Rect> newclip = Intersect(clip.Top(), r + actual_offset, ch);
if(ch) {
f.clipi = clip.GetCount();
clip.Add() = newclip;
}
cloff.Add(f);
if(ch)
SetClip();
return clip.Top().GetCount();
}
bool Draw::ClipoffOp(const Rect& r)
{
LLOG("Draw::ClipOffOp(" << r << ")");
Cloff f = cloff.Top();
bool ch = false;
Vector<Rect> newclip = Intersect(clip.Top(), r + actual_offset, ch);
if(ch) {
f.clipi = clip.GetCount();
clip.Add() = newclip;
}
f.offseti = offset.GetCount();
actual_offset += r.TopLeft();
offset.Add(actual_offset);
cloff.Add(f);
if(ch)
SetClip();
return clip.Top().GetCount();
}
void Draw::EndOp()
{
ASSERT(cloff.GetCount());
cloff.Drop();
actual_offset = offset[cloff.Top().offseti];
clip.SetCount(cloff.Top().clipi + 1);
SetClip();
}
bool Draw::ExcludeClipOp(const Rect& r)
{
LLOG("Draw::ExcludeClipOp(" << r << ")");
CloneClip();
Vector<Rect>& cl = clip.Top();
bool ch = false;
Vector<Rect> ncl = Subtract(cl, r + actual_offset, ch);
if(ch) {
cl = ncl;
SetClip();
}
return clip.Top().GetCount();
}
bool Draw::IntersectClipOp(const Rect& r)
{
CloneClip();
Vector<Rect>& cl = clip.Top();
bool ch = false;
Vector<Rect> ncl = Intersect(cl, r + actual_offset, ch);
if(ch) {
cl = ncl;
SetClip();
}
return clip.Top().GetCount();
}
Rect Draw::GetClipOp() const
{
LLOG("Draw::GetClipOp; #clip = " << clip.GetCount() << ", #cloff = " << cloff.GetCount()
<< ", clipi = " << cloff.Top().clipi);
const Vector<Rect>& cl = clip[cloff.Top().clipi];
Rect box(0, 0, 0, 0);
if(!cl.GetCount()) return box;
box = cl[0];
LLOG("cl[0] = " << box);
for(int i = 1; i < cl.GetCount(); i++) {
LLOG("cl[" << i << "] = " << cl[i]);
box |= cl[i];
}
LLOG("out box = " << box << ", actual offset = " << actual_offset);
return box - actual_offset;
}
bool Draw::IsPaintingOp(const Rect& r) const
{
LTIMING("IsPaintingOp");
Rect rr = r + actual_offset;
const Vector<Rect>& cl = clip[cloff.Top().clipi];
for(int i = 0; i < cl.GetCount(); i++)
if(cl[i].Intersects(rr))
return true;
return false;
}
void Draw::DrawRectOp(int x, int y, int cx, int cy, Color color)
{
LTIMING("DrawRect");
DrawLock __;
LLOG("DrawRect " << RectC(x, y, cx, cy) << ": " << color);
if(IsNull(color)) return;
if(cx <= 0 || cy <= 0) return;
if(color == InvertColor) {
XSetFunction(Xdisplay, gc, GXinvert);
XFillRectangle(Xdisplay, dw, gc, x + actual_offset.x, y + actual_offset.y, cx, cy);
XSetFunction(Xdisplay, gc, GXcopy);
}
else {
SetForeground(color);
XFillRectangle(Xdisplay, dw, gc, x + actual_offset.x, y + actual_offset.y, cx, cy);
}
}
void Draw::DrawLineOp(int x1, int y1, int x2, int y2, int width, Color color)
{
DrawLock __;
if(IsNull(width) || IsNull(color)) return;
SetLineStyle(width);
SetForeground(color);
XDrawLine(Xdisplay, dw, gc,
x1 + actual_offset.x, y1 + actual_offset.y,
x2 + actual_offset.x, y2 + actual_offset.y);
}
void Draw::DrawPolyPolylineOp(const Point *vertices, int vertex_count,
const int *counts, int count_count,
int width, Color color, Color doxor)
{
DrawLock __;
ASSERT(count_count > 0 && vertex_count > 0);
if(vertex_count < 2 || IsNull(color))
return;
XGCValues gcv_old, gcv_new;
XGetGCValues(Xdisplay, GetGC(), GCForeground | GCLineWidth | GCFunction, &gcv_old);
gcv_new.function = IsNull(doxor) ? X11_ROP2_COPY : X11_ROP2_XOR;
gcv_new.foreground = GetXPixel(color) ^ (IsNull(doxor) ? 0 : GetXPixel(doxor));
gcv_new.line_width = width;
XChangeGC(Xdisplay, GetGC(), GCForeground | GCLineWidth | GCFunction, &gcv_new);
enum { REQUEST_LENGTH = 256 }; // X server XDrawLines request length (heuristic)
Point offset = GetOffset();
if(vertex_count == 2)
XDrawLine(Xdisplay, GetDrawable(), GetGC(),
vertices[0].x + offset.x, vertices[0].y + offset.y,
vertices[1].x + offset.x, vertices[1].y + offset.y);
else if(count_count == 1 || vertex_count > count_count * (REQUEST_LENGTH + 2)) {
for(; --count_count >= 0; counts++)
{
Buffer<XPoint> part(*counts);
for(XPoint *vo = part, *ve = vo + *counts; vo < ve; vo++, vertices++)
{
vo -> x = (short)(vertices -> x + offset.x);
vo -> y = (short)(vertices -> y + offset.y);
}
XDrawLines(Xdisplay, GetDrawable(), GetGC(), part, *counts, CoordModeOrigin);
}
}
else {
int segment_count = vertex_count - count_count;
Buffer<XSegment> segments(segment_count);
XSegment *so = segments;
while(--count_count >= 0)
{
const Point *end = vertices + *counts++;
so -> x1 = (short)(vertices -> x + offset.x);
so -> y1 = (short)(vertices -> y + offset.y);
vertices++;
so -> x2 = (short)(vertices -> x + offset.x);
so -> y2 = (short)(vertices -> y + offset.y);
so++;
while(++vertices < end) {
so -> x1 = so[-1].x2;
so -> y1 = so[-1].y2;
so -> x2 = (short)(vertices -> x + offset.x);
so -> y2 = (short)(vertices -> y + offset.y);
so++;
}
}
ASSERT(so == segments + segment_count);
XDrawSegments(Xdisplay, GetDrawable(), GetGC(), segments, segment_count);
}
XChangeGC(Xdisplay, GetGC(), GCForeground | GCLineWidth | GCFunction, &gcv_old);
}
static void DrawPolyPolyPolygonRaw(Draw& draw, const Point *vertices, int vertex_count,
const int *subpolygon_counts, int subpolygon_count_count, const int *, int)
{
DrawLock __;
Point offset = draw.GetOffset();
const Point *in = vertices;
for(int i = 0; i < subpolygon_count_count; i++) {
int n = subpolygon_counts[i];
Buffer<XPoint> out_points(n);
XPoint *t = out_points;
XPoint *e = t + n;
while(t < e) {
t->x = (short)(in->x + offset.x);
t->y = (short)(in->y + offset.y);
t++;
in++;
}
XFillPolygon(Xdisplay, draw.GetDrawable(), draw.GetGC(), out_points, n, Nonconvex, CoordModeOrigin);
}
}
void Draw::DrawPolyPolyPolygonOp(const Point *vertices, int vertex_count,
const int *subpolygon_counts, int subpolygon_count_count,
const int *disjunct_polygon_counts, int disjunct_polygon_count_count,
Color color, int width, Color outline, uint64 pattern, Color doxor)
{
DrawLock __;
if(vertex_count == 0)
return;
bool is_xor = !IsNull(doxor);
XGCValues gcv_old, gcv_new;
XGetGCValues(Xdisplay, GetGC(), GCForeground | GCFunction | GCLineWidth, &gcv_old);
unsigned xor_pixel = (is_xor ? GetXPixel(doxor) : 0);
if(!IsNull(color))
{
gcv_new.foreground = GetXPixel(color) ^ xor_pixel;
gcv_new.function = is_xor ? X11_ROP2_XOR : X11_ROP2_COPY;
XChangeGC(Xdisplay, GetGC(), GCForeground | GCFunction, &gcv_new);
DrawPolyPolyPolygonRaw(*this, vertices, vertex_count,
subpolygon_counts, subpolygon_count_count,
disjunct_polygon_counts, disjunct_polygon_count_count);
}
if(!IsNull(outline))
{
gcv_new.foreground = GetXPixel(outline) ^ xor_pixel;
gcv_new.line_width = width;
XChangeGC(Xdisplay, GetGC(), GCForeground | GCLineWidth, &gcv_new);
Point offset = GetOffset();
for(const int *sp = subpolygon_counts, *se = sp + subpolygon_count_count; sp < se; sp++)
{
Buffer<XPoint> segment(*sp + 1);
XPoint *out = segment;
for(const Point *end = vertices + *sp; vertices < end; vertices++, out++)
{
out -> x = (short)(vertices -> x + offset.x);
out -> y = (short)(vertices -> y + offset.y);
}
*out = segment[0];
XDrawLines(Xdisplay, GetDrawable(), GetGC(), segment, *sp + 1, CoordModeOrigin);
}
}
XChangeGC(Xdisplay, GetGC(), GCForeground | GCFunction | GCLineWidth, &gcv_old);
}
void Draw::DrawEllipseOp(const Rect& r, Color color, int pen, Color pencolor)
{
DrawLock __;
SetLineStyle(pen);
if(!IsNull(color)) {
SetForeground(color);
XFillArc(Xdisplay, dw, gc, r.left + actual_offset.x, r.top + actual_offset.y,
r.Width() - 1, r.Height() - 1, 0, 360 * 64);
}
if(!IsNull(pencolor) && !IsNull(pen)) {
SetForeground(pencolor);
XDrawArc(Xdisplay, dw, gc, r.left + actual_offset.x, r.top + actual_offset.y,
r.Width() - 1, r.Height() - 1, 0, 360 * 64);
}
}
void Draw::DrawArcOp(const Rect& rc, Point start, Point end, int width, Color color)
{
DrawLock __;
XGCValues gcv, gcv_old;
XGetGCValues(Xdisplay, GetGC(), GCForeground, &gcv_old);
Point offset = GetOffset();
gcv.foreground = GetXPixel(color);
XChangeGC(Xdisplay, GetGC(), GCForeground, &gcv);
Point centre = rc.CenterPoint();
int angle1 = fround(360 * 64 / (2 * M_PI) *
atan2(centre.y - start.y, start.x - centre.x));
int angle2 = fround(360 * 64 / (2 * M_PI) *
atan2(centre.y - end.y, end.x - centre.x));
if(angle2 <= angle1)
angle2 += 360 * 64;
angle2 -= angle1;
XDrawArc(Xdisplay, GetDrawable(), GetGC(), rc.left + offset.x, rc.top + offset.y,
rc.Width(), rc.Height(), angle1, angle2);
XChangeGC(Xdisplay, GetGC(), GCForeground, &gcv_old);
}
#endif
END_UPP_NAMESPACE
| 28.996885 | 102 | 0.643962 | [
"vector"
] |
8716023e5980309115025450702235f71bceaee1 | 3,395 | hpp | C++ | applications/unit_tests/helpers.hpp | Rythe-Interactive/Legion-LLRI | e0cc449cc8c2ba0701a73b8c07b80ccfd8f20477 | [
"MIT"
] | 16 | 2021-09-10T18:11:37.000Z | 2022-01-26T06:28:51.000Z | applications/unit_tests/helpers.hpp | Rythe-Interactive/Legion-LLRI | e0cc449cc8c2ba0701a73b8c07b80ccfd8f20477 | [
"MIT"
] | 13 | 2021-09-12T16:28:47.000Z | 2022-02-07T19:34:01.000Z | applications/unit_tests/helpers.hpp | Rythe-Interactive/Legion-LLRI | e0cc449cc8c2ba0701a73b8c07b80ccfd8f20477 | [
"MIT"
] | 1 | 2021-08-15T23:35:32.000Z | 2021-08-15T23:35:32.000Z | /**
* @file helpers.hpp
* @copyright 2021-2021 Leon Brands. All rights served.
* @license: https://github.com/Legion-Engine/Legion-LLRI/blob/main/LICENSE
*/
#pragma once
#include <doctest/doctest.h>
#include <llri/llri.hpp>
namespace helpers
{
inline llri::Instance* defaultInstance()
{
llri::Instance* instance;
auto ext = llri::instance_extension::DriverValidation;
const llri::instance_desc desc{ 1, &ext, "unit test instance"};
REQUIRE_EQ(llri::createInstance(desc, &instance), llri::result::Success);
return instance;
}
inline llri::Adapter* selectAdapter(llri::Instance* instance)
{
std::vector<llri::Adapter*> adapters;
REQUIRE_EQ(instance->enumerateAdapters(&adapters), llri::result::Success);
return adapters[0];
}
inline llri::Device* defaultDevice(llri::Instance* instance, llri::Adapter* adapter)
{
llri::Device* device = nullptr;
uint8_t graphicsQueueCount = adapter->queryQueueCount(llri::queue_type::Graphics);
uint8_t computeQueueCount = adapter->queryQueueCount(llri::queue_type::Compute);
uint8_t transferQueueCount = adapter->queryQueueCount(llri::queue_type::Transfer);
std::vector<llri::queue_desc> queues;
if (graphicsQueueCount > 0)
queues.push_back(llri::queue_desc{ llri::queue_type::Graphics, llri::queue_priority::Normal });
if (computeQueueCount > 0)
queues.push_back(llri::queue_desc{ llri::queue_type::Compute, llri::queue_priority::Normal });
if (transferQueueCount > 0)
queues.push_back(llri::queue_desc{ llri::queue_type::Transfer, llri::queue_priority::Normal });
const llri::device_desc ddesc{ adapter, llri::adapter_features{}, 0, nullptr, static_cast<uint32_t>(queues.size()), queues.data() };
REQUIRE_EQ(instance->createDevice(ddesc, &device), llri::result::Success);
return device;
}
inline llri::queue_type availableQueueType(llri::Adapter* adapter)
{
for (size_t type = 0; type <= static_cast<uint8_t>(llri::queue_type::MaxEnum); type++)
{
uint8_t count = adapter->queryQueueCount(static_cast<llri::queue_type>(type));
if (count > 0)
return static_cast<llri::queue_type>(type);
}
FAIL("No available queue for this adapter");
return llri::queue_type::MaxEnum;
}
inline llri::CommandGroup* defaultCommandGroup(llri::Device* device, llri::queue_type type)
{
llri::CommandGroup* cmdGroup;
REQUIRE_EQ(device->createCommandGroup(type, &cmdGroup), llri::result::Success);
return cmdGroup;
}
inline llri::CommandList* defaultCommandList(llri::CommandGroup* group, uint32_t nodeMask, llri::command_list_usage usage)
{
llri::command_list_alloc_desc desc{};
desc.nodeMask = nodeMask;
desc.usage = usage;
llri::CommandList* cmd;
REQUIRE_EQ(group->allocate(desc, &cmd), llri::result::Success);
return cmd;
}
inline llri::Fence* defaultFence(llri::Device* device, bool signaled)
{
llri::fence_flags flags = signaled ? llri::fence_flag_bits::Signaled : llri::fence_flag_bits::None;
llri::Fence* result;
REQUIRE_EQ(device->createFence(flags, &result), llri::result::Success);
return result;
}
}
| 37.307692 | 140 | 0.660972 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.