blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 2 247 | content_id stringlengths 40 40 | detected_licenses listlengths 0 57 | license_type stringclasses 2 values | repo_name stringlengths 4 111 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 58 | visit_date timestamp[ns]date 2015-07-25 18:16:41 2023-09-06 10:45:08 | revision_date timestamp[ns]date 1970-01-14 14:03:36 2023-09-06 06:22:19 | committer_date timestamp[ns]date 1970-01-14 14:03:36 2023-09-06 06:22:19 | github_id int64 3.89k 689M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 25 values | gha_event_created_at timestamp[ns]date 2012-06-07 00:51:45 2023-09-14 21:58:52 ⌀ | gha_created_at timestamp[ns]date 2008-03-27 23:40:48 2023-08-24 19:49:39 ⌀ | gha_language stringclasses 159 values | src_encoding stringclasses 34 values | language stringclasses 1 value | is_vendor bool 1 class | is_generated bool 2 classes | length_bytes int64 7 10.5M | extension stringclasses 111 values | filename stringlengths 1 195 | text stringlengths 7 10.5M |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4f6590c04fb2a954609ad1241208e7fb7201a079 | 7cad9eddd20ba6db557598466b54885524b2ce0b | /Drivetrain/TestFile/TestFile.ino | 7b0b821d574507a6f2b1e0a18b2e4b7e3b569187 | [] | no_license | UCLAX1/BruinBot-Controls | 3c432953489e57c3be1dda4dcc3b7a405b216389 | cbd3e5ccf0ddea47f01f28c940ef377572978354 | refs/heads/master | 2022-07-09T02:46:06.227931 | 2022-06-09T02:01:53 | 2022-06-09T02:01:53 | 243,472,494 | 0 | 1 | null | 2022-04-22T17:59:00 | 2020-02-27T08:47:45 | C++ | UTF-8 | C++ | false | false | 207 | ino | TestFile.ino | #include <Servo.h>
int SERVO_PIN = 9;
Servo myservo ;
void setup() {
Serial.begin(9600);
myservo.attach(SERVO_PIN);
}
void loop() {
delay(200);
myservo.write(10);
}
|
e8cdd7a1883bf04a2dce6b66f40b48e1d8578d1a | 844fd8528d5c839c0660dd0de367cb050a6b6694 | /main.cpp | 5e42bc6674f87360aee635713233dbaee6b5b152 | [
"BSD-3-Clause"
] | permissive | MiguelMendozaG/vpl | 2b619da17d3839ab69ddbaee66367416f36a11f1 | cd46f23af8806371661342d82af8ed251a3842a0 | refs/heads/master | 2021-09-19T18:54:21.327100 | 2018-07-30T20:22:04 | 2018-07-30T20:22:04 | 113,601,726 | 0 | 0 | null | 2017-12-08T17:48:08 | 2017-12-08T17:48:08 | null | UTF-8 | C++ | false | false | 6,196 | cpp | main.cpp | #include <iostream>
#include <pcl/io/pcd_io.h>
#include <pcl/point_types.h>
#include <pcl/filters/voxel_grid.h>
#include <vector>
#include <pcl/correspondence.h>
#include <pcl/search/kdtree.h>
#include <pcl/visualization/cloud_viewer.h>
#include <pcl/io/io.h>
using namespace std;
typedef pcl::PointXYZ pointType;
typedef pcl::PointCloud<pointType> pointCloudType;
typedef pcl::PointCloud<pointType>::Ptr pointCloudTypePtr;
//pcl::PCLPointCloud2::Ptr z (new pcl::PCLPointCloud2 ());
vector <pointCloudTypePtr> all_z;
/**
*
* Reads the point clouds
*
*/
void read_all_z(std::string input_folder){
vector< vector<double> > pcl_raw;
pcl::PCDReader reader_pcl;
pointCloudTypePtr pcl_file_pcd (new pcl::PointCloud<pointType>);
for(int i = 0; i<100; i+=5){
std::stringstream indice_img;
indice_img << i;
std::cout << "\n Imagen " << i << endl;
pointCloudTypePtr cloud (new pcl::PointCloud<pointType>);
pcl::io::loadPCDFile(input_folder + "imagen-" + indice_img.str() + ".pcd", *cloud);
all_z.push_back(cloud);
}
}
void changeColor(pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud, int R, int G, int B)
{
for (size_t i = 0; i < cloud->size (); ++i)
{
if (! pcl_isfinite ((*cloud)[i].x))
{ continue; }
(*cloud)[i].r = R; (*cloud)[i].g = G; (*cloud)[i].b = B;
}
}
/*
* It computes the coorrespondent points
* A correspondent point is apoint in the ground trouth that is closer than a threhold to the a target pc
*/
size_t correspondentPoints(pointCloudTypePtr grountTruth, pointCloudTypePtr target, pointCloudTypePtr corrCloud, double radius)
{
std::vector<int> indices;
std::vector<float> sqr_distances;
pcl::search::KdTree<pointType> tree;
tree.setInputCloud (target);
corrCloud->clear();
size_t corr_points = 0;
for (size_t i = 0; i < grountTruth->size (); ++i)
{
if (! pcl_isfinite ((*grountTruth)[i].x))
{
continue;
}
if(tree.radiusSearch((*grountTruth)[i], radius, indices, sqr_distances, 1))
{
corr_points++;
corrCloud->push_back((*target)[indices[0]]);
}
}
return corr_points;
}
/*
*
* Algorith that computes the "NBV" from a set of views and already taken point clouds
*
*/
int main (int argc, char** argv)
{
// Check the following parameters
// downsampling res
float voxel_res = 0.0005;
// correspond thres
double corres_thres = 0.001;
//Read the groundtruth
pointCloudTypePtr ground_truth(new pcl::PointCloud<pointType>);
pcl::io::loadPCDFile("./model/model2.pcd", *ground_truth);
// read all the sensor positions and orientations
// 1 Read all the posible sensor readings (Z). They are point clouds.
std::string input_folder ("./z/");
read_all_z(input_folder);
double coverage = 0;
double coverage_stop_threshold = 0.99;
int iteration = 1;
int iteration_stop = 10;
int w_star_index = 0;
pointType w_pos;
pointType w_pos_end;
double overlap;
pointCloudTypePtr z_ptr;
pointCloudTypePtr P_acu (new pointCloudType());
pointCloudTypePtr P_overlap(new pointCloudType());
// Create the filtering object
pcl::VoxelGrid<pointType> voxel_filter;
voxel_filter.setLeafSize(voxel_res, voxel_res, voxel_res);
while (coverage < coverage_stop_threshold && iteration < iteration_stop) {
cout << "Iteration:" << iteration << endl;
z_ptr = all_z[w_star_index];
// nbv position
w_pos.x = 0.0;
w_pos.y = 0.0;
w_pos.z = 0.4;
// nbv orientation
w_pos_end.x = 0.0;
w_pos_end.y = 0.0;
w_pos_end.z = 0.3;
// segment the object from z;
// register z ; not necessary because they are in the world's reference frame
// join both pc
*P_acu = *P_acu + *z_ptr;
//filtering
//voxel_filter.setInputCloud(P_acu);
//voxel_filter.filter(*P_acu);
//NOTE: it seems like the voxel filter is introducing an error so I removed from here
// compute current coverage
// TODO: change for the groundtruth
size_t positives;
size_t total = ground_truth->size();
positives = correspondentPoints(ground_truth, P_acu, P_overlap, corres_thres);
coverage = (double)positives/total;
//cout << "Correspondent points: " << (long)positives << endl;
cout << "Current coverage: " << (double)positives/total << endl;
// Select the NBV
//TODO:
w_star_index ++;
//Compute the overlap of the NBV
positives = correspondentPoints(P_acu, all_z[w_star_index], P_overlap, corres_thres);
total = P_acu->size();
overlap = (double)positives/total;
cout << "NBV overlap: " << overlap << endl;
iteration ++;
pcl::PointCloud<pcl::PointXYZRGB>::Ptr colorAcu(new pcl::PointCloud<pcl::PointXYZRGB>);
pcl::PointCloud<pcl::PointXYZRGB>::Ptr colorOver(new pcl::PointCloud<pcl::PointXYZRGB>);
pcl::PointCloud<pcl::PointXYZRGB>::Ptr colorZ(new pcl::PointCloud<pcl::PointXYZRGB>);
pcl::PointCloud<pcl::PointXYZRGB>::Ptr colorZstar(new pcl::PointCloud<pcl::PointXYZRGB>);
pcl::copyPointCloud(*z_ptr, *colorZ);
pcl::copyPointCloud(*P_acu, *colorAcu);
pcl::copyPointCloud(*P_overlap, *colorOver);
pcl::copyPointCloud(*(all_z[w_star_index]), *colorZstar);
changeColor(colorZ, 0, 255, 0);
// Visualización
pcl::visualization::PCLVisualizer viewer("Cloud Viewer");
viewer.addCoordinateSystem(0.1);
// Display z
//viewer.addPointCloud(colorZ, "Z");
//TODO: Add arrow with previous w*
// Display accumulated point cloud
changeColor(colorAcu, 255, 255, 255);
viewer.addPointCloud(colorAcu, "Accumulated");
//TODO: Add arrow with w*
// Display z*
changeColor(colorZstar, 0,0,255);
viewer.addPointCloud(colorZstar, "Z star");
// Display overlap
changeColor(colorOver, 255, 0, 0);
viewer.addPointCloud(colorOver, "Overlap");
viewer.addLine<pointType>(w_pos, w_pos_end, 255, 255 , 255,"w_star_prev");
viewer.spin();
}// end while
return 0;
// pcl::PCLPointCloud2::Ptr cloud (new pcl::PCLPointCloud2());
//pcl::PCLPointCloud2::Ptr cloud_filtered (new pcl::PCLPointCloud2());
} |
111e06d8da06d0a07531e4fcfba074c76f27786c | 3aade8553e7a07134cf53e4e49b65360f58ba06a | /collection/cp/Algorithm_Collection-master/generate_next_permutation.cpp | 4daecd7fa6031435394c015d7da611aa24212339 | [
"Apache-2.0"
] | permissive | bruler/Notebook | beb529f027816abda776a88f36bfc5051fcc5880 | a9880be9bd86955afd6b8f7352822bc18673eda3 | refs/heads/master | 2021-06-13T17:25:22.460991 | 2017-04-07T18:42:25 | 2017-04-07T18:42:25 | 73,064,126 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,181 | cpp | generate_next_permutation.cpp | /*Analysis:
Well, this is more like a math problem, and I don't know how to solve it.
From the wikipedia, one classic algorithm to generate next permutation is:
Step 1: Find the largest index k, such that A[k]<A[k+1]. If not exist, this is the last permutation. (in this problem just sort the vector and return.)
Step 2: Find the largest index l, such that A[l]>A[k].
Step 3: Swap A[k] and A[l].
Step 4: Reverse A[k+1] to the end.
i*/
class Solution {
public:
void nextPermutation(vector<int> &num) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int sz = num.size();
int k=-1;
int l;
//step1
for (int i=0;i<sz-1;i++){
if (num[i]<num[i+1]){
k=i;
}
}
if (k==-1){
sort(num.begin(),num.end());
return;
}
//step2
for (int i=0;i<sz;i++){
if (num[i]>num[k]){
l=i;
}
}
//step3
int tmp = num[l];
num[l]=num[k];
num[k]=tmp;
//step4
reverse(num.begin()+k+1,num.end());
}
};
|
ca5f56f9a592f5943ff01186d71a12ebf61c8860 | 580e530b5b21f96ebeb97c93d37257b863792bf1 | /cpp/src/data_structures/intersections/intersections.cpp | 0931e8fdd7eb1e752928fdccb5817d08124c41cf | [
"MIT"
] | permissive | LawrenceRafferty/ray-tracer-challenge | 05273fb0ef74a21a8066094b198463c9946c7a8e | f54dfd4eb717e44c9e313be4bd28f8fad00094d0 | refs/heads/master | 2021-07-01T10:26:39.834636 | 2020-10-28T07:05:01 | 2020-10-28T07:05:01 | 188,644,524 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,651 | cpp | intersections.cpp | #include "./intersections.h"
using data_structures::world;
using shapes::shape;
namespace data_structures
{
intersections intersections::find(std::shared_ptr<const shape> object, const ray &r)
{
auto tValues = object->intersect(r);
auto tValuesWithTheirObject = std::vector<intersection>();
for (auto tValue : tValues)
tValuesWithTheirObject.emplace_back(intersection(tValue, object));
return intersections { std::move(tValuesWithTheirObject) };
}
intersections intersections::find(const world & w, const ray & r)
{
auto tValuesWithTheirObject = std::vector<intersection>();
for (auto object : w.getObjects())
{
auto tValues = object->intersect(r);
for (auto tValue : tValues)
tValuesWithTheirObject.emplace_back(intersection(tValue, object));
}
std::sort(tValuesWithTheirObject.begin(), tValuesWithTheirObject.end());
return intersections { std::move(tValuesWithTheirObject) };
}
intersections::intersections(std::vector<intersection> intersections)
: _intersections { std::move(intersections) }
{}
intersections::intersections(std::initializer_list<intersection> intersections)
: _intersections { std::vector<intersection>(intersections) }
{}
int intersections::size() const { return _intersections.size(); }
intersection intersections::at(int index) const { return _intersections.at(index); }
std::unique_ptr<const intersection> intersections::getHit() const
{
std::unique_ptr<const intersection> hit = nullptr;
for (const intersection & i : _intersections)
{
if (i.isHitCandidate() && (hit == nullptr || i < *hit))
hit = std::make_unique<intersection>(i);
}
return hit;
}
} // namespace data_structures
|
31d4114ce81d30903463a5657fd4225892d35454 | d37b74c5e4a66863eb47ebab89e6f9ab112be0ef | /SwordPlay/Incude/Tokamak/math/ne_math.h | e15f8702552d1e9dbc95f7abad81949f9d0ea20d | [] | no_license | Ionsto/SwordPlay | e44b4d961b5c7c3ecb17e0ed62d005d47c811680 | 808f0079504fa47e3176386a17b86349f28eed2c | refs/heads/master | 2016-09-10T22:10:37.397294 | 2014-12-13T23:32:12 | 2014-12-13T23:32:12 | 25,430,614 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,288 | h | ne_math.h | /*************************************************************************
* *
* Tokamak Physics Engine, Copyright (C) 2002-2007 David Lam. *
* All rights reserved. Email: david@tokamakphysics.com *
* Web: www.tokamakphysics.com *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files *
* LICENSE.TXT for more details. *
* *
*************************************************************************/
#ifndef NE_MATH_H
#define NE_MATH_H
#ifdef USE_OPCODE
#include "Opcode.h"
#endif //USE_OPCODE
#include <math.h>
#include <float.h>
#include "ne_type.h"
#include "ne_debug.h"
#include "ne_smath.h"
//#include <xmmintrin.h>
/****************************************************************************
*
* neV3
*
****************************************************************************/
static s32 neNextDim1[] = {1, 2, 0};
static s32 neNextDim2[] = {2, 0, 1};
typedef struct neQ neQ;
typedef struct neM3 neM3;
//struct __declspec(align(16)) neV3
struct neV3
{
public:
f32 v[4];
/*
union
{
f32 v[4];
struct nTag
{
f32 X,Y,Z,W;
}n;
//__m128 m;
};
*/
NEINLINE neV3 & SetZero (void );
NEINLINE neV3 & SetOne(void);
NEINLINE neV3 & SetHalf(void);
NEINLINE neV3 & Set(f32 value);
NEINLINE neV3 & Set (f32 x, f32 y, f32 z );
NEINLINE neV3 & Set (const neV3& V);
NEINLINE neV3 & Set (const neQ& Q);
NEINLINE void Set (f32 val[3]);
NEINLINE void Get (f32 val[3]);
NEINLINE f32& operator [] (s32 I);
NEINLINE f32 operator [] (s32 I) const;
NEINLINE f32 X() const;
NEINLINE f32 Y() const;
NEINLINE f32 Z() const;
NEINLINE f32 W() const;
NEINLINE void Normalize (void);
NEINLINE f32 Length (void) const;
NEINLINE f32 Dot (const neV3& V) const;
NEINLINE neV3 Cross (const neV3& V) const;
NEINLINE void RotateX (neRadian Rx);
NEINLINE void RotateY (neRadian Ry);
NEINLINE void RotateZ (neRadian Rz);
NEINLINE neRadian GetPitch (void) const;
NEINLINE neRadian GetYaw (void) const;
NEINLINE void SetBoxTensor (f32 width, f32 height, f32 depth, f32 mass);
NEINLINE void SetAbs (const neV3 & v);
NEINLINE f32 GetDistanceFromLine(const neV3 & point1, const neV3 & point2);
NEINLINE f32 GetDistanceFromLine2(neV3 & project, const neV3 & pointA, const neV3 & pointB);
NEINLINE f32 GetDistanceFromLineAndProject(neV3 & result, const neV3 & startPoint, const neV3 & dir);
NEINLINE neBool GetIntersectPlane(neV3 & normal, neV3 & pointOnPlane, neV3 & point1, neV3 & point2);
NEINLINE void SetMin (const neV3& V1, const neV3& V2);
NEINLINE void SetMax (const neV3& V1, const neV3& V2);
NEINLINE void RemoveComponent (const neV3& V);
NEINLINE bool IsConsiderZero () const;
NEINLINE bool IsFinite () const;
NEINLINE neV3 Project (const neV3 & v) const;
// NEINLINE neV3 & operator = (const neV3& V);
NEINLINE neV3& operator /= (f32 S);
NEINLINE neV3& operator *= (f32 S);
NEINLINE neV3& operator += (const neV3& V);
NEINLINE neV3& operator -= (const neV3& V);
NEINLINE neV3 friend operator + (const neV3& V1, const neV3& V2);
NEINLINE neV3 friend operator - (const neV3& V1, const neV3& V2);
NEINLINE neV3 friend operator / (const neV3& V, f32 S);
NEINLINE neV3 friend operator * (const neV3& V, f32 S);
NEINLINE neV3 friend operator * (const neV3& V1, const neV3& V2);
NEINLINE neV3 friend operator * (const neV3& V, const neM3& M);
NEINLINE neM3 friend operator ^ (const neV3 & V, const neM3 & M); //cross product operator
NEINLINE friend neV3 operator - (const neV3& V );
NEINLINE friend neV3 operator * (f32 S, const neV3& V );
#ifdef USE_OPCODE
NEINLINE neV3 & operator = (const IceMaths::Point & pt);
NEINLINE IceMaths::Point& AssignIcePoint(IceMaths::Point & pt) const;
#endif //USE_OPCODE
};
/****************************************************************************
*
* neV4
*
****************************************************************************/
struct neV4
{
f32 X, Y, Z, W;
// functions
NEINLINE neV4 ( void );
NEINLINE neV4 ( f32 x, f32 y, f32 z, f32 w );
NEINLINE neV4 ( const neV3& V, f32 w );
NEINLINE neV4 ( const neV4& V );
NEINLINE void SetZero ( void );
NEINLINE void Set ( f32 x, f32 y, f32 z, f32 w );
NEINLINE f32& operator [] ( s32 I );
NEINLINE neV4& operator /= ( f32 S );
NEINLINE neV4& operator *= ( f32 S );
NEINLINE neV4& operator += ( const neV4& V );
NEINLINE neV4& operator -= ( const neV4& V );
NEINLINE neV4& Normalize ( void );
NEINLINE f32 Length ( void ) const;
NEINLINE f32 Dot ( const neV4& V ) const;
NEINLINE friend neV4 operator - ( const neV4& V );
NEINLINE friend neV4 operator * ( f32 S, const neV4& V );
NEINLINE friend neV4 operator / ( const neV4& V, f32 S );
NEINLINE friend neV4 operator * ( const neV4& V, f32 S );
NEINLINE friend neV4 operator + ( const neV4& V1, const neV4& V2 );
NEINLINE friend neV4 operator - ( const neV4& V1, const neV4& V2 );
};
/****************************************************************************
*
* neM3
*
****************************************************************************/
struct neM3
{
neV3 M[3];
NEINLINE neV3& operator [] ( s32 I );
NEINLINE neV3 operator [] ( s32 I ) const;
NEINLINE void SetZero ( void );
NEINLINE void SetIdentity ( void );
NEINLINE neBool SetInvert(const neM3 & rhs);
NEINLINE neM3 & SetTranspose ( neM3 & M );
NEINLINE void GetColumns( neV3& V1, neV3& V2, neV3& V3 ) const;
NEINLINE void SetColumns( const neV3& V1, const neV3& V2, const neV3& V3 );
NEINLINE neV3 GetDiagonal();
NEINLINE neV3 TransposeMulV3(const neV3 & V);
NEINLINE void RotateXYZ(const neV3 & rotate);
NEINLINE neM3 & SkewSymmetric(const neV3 & V);
NEINLINE neBool IsIdentity() const;
NEINLINE neBool IsOrthogonalNormal() const;
NEINLINE neBool IsFinite() const;
NEINLINE neM3 &operator += ( const neM3& add);
NEINLINE neM3 operator ^ (const neV3 & vec) const; //cross product
NEINLINE neM3 operator * (f32 scalar) const;
NEINLINE friend neM3 operator + ( const neM3& add1, const neM3& add2);
NEINLINE friend neM3 operator - ( const neM3& sub1, const neM3& sub2);
NEINLINE friend neM3 operator * ( const neM3& M1, const neM3& M2 );
NEINLINE friend neV3 operator * ( const neM3& M1, const neV3& V );
NEINLINE friend neM3 operator * ( f32 scalar, const neM3& M );
NEINLINE friend neM3& operator *= ( neM3& M1, const f32 f );
NEINLINE friend neM3& operator /= ( neM3& M1, const f32 f );
};
/****************************************************************************
*
* neM4
*
****************************************************************************/
struct neM4
{
f32 M[4][4];
// functions
NEINLINE void Set(float row00, float row01, float row02, float row03
, float row10, float row11, float row12, float row13
, float row20, float row21, float row22, float row23
, float row30, float row31, float row32, float row33);
NEINLINE void Set(int row, int col, f32 val){M[col][row] = val;}
NEINLINE void SetZero ( void );
NEINLINE void SetIdentity ( void );
NEINLINE neV3 GetScale ( void ) const;
NEINLINE neV3 GetTranslation ( void ) const;
NEINLINE void SetTranslation ( const neV3& V );
NEINLINE void SetScale ( const neV3& V );
NEINLINE f32& operator [] ( s32 I );
NEINLINE neM4& operator *= ( const neM4& M );
NEINLINE neM4& operator = ( const neM3& M );
NEINLINE neV3 TransformAs3x3 ( const neV3& V ) const;
NEINLINE void GetRows ( neV3& V1, neV3& V2, neV3& V3 ) const;
NEINLINE void SetRows ( const neV3& V1, const neV3& V2, const neV3& V3 );
NEINLINE void GetColumns ( neV3& V1, neV3& V2, neV3& V3 ) const;
NEINLINE void SetColumns ( const neV3& V1, const neV3& V2, const neV3& V3 );
NEINLINE void GetColumn ( neV3& V1, u32 col) const;
NEINLINE void SetTranspose(const neM4 & M);
NEINLINE void SetFastInvert ( const neM4& Src );
NEINLINE friend neM4 operator * ( const neM4& M1, const neM4& M2 );
NEINLINE friend neV3 operator * ( const neM4& M1, const neV3& V );
};
/****************************************************************************
*
* neQ
*
****************************************************************************/
struct neQ
{
f32 X, Y, Z, W;
// functions
NEINLINE neQ ( void );
NEINLINE neQ ( f32 X, f32 Y, f32 Z, f32 W );
NEINLINE neQ ( const neM4& M );
NEINLINE void Zero ( void );
NEINLINE void Identity ( void );
NEINLINE void SetupFromMatrix ( const neM4& Matrix );
NEINLINE void SetupFromMatrix3 ( const neM3& Matrix );
NEINLINE void GetAxisAngle ( neV3& Axis, neRadian& Angle ) const;
NEINLINE neM4 BuildMatrix ( void ) const;
NEINLINE neM3 BuildMatrix3 ( void ) const;
NEINLINE neQ& Normalize ( void );
NEINLINE f32 Dot ( const neQ& Q ) const;
NEINLINE neQ& Invert ( void );
NEINLINE neBool IsFinite ();
NEINLINE neQ& operator *= ( const neQ& Q );
NEINLINE neQ& operator *= ( f32 S );
NEINLINE neQ& operator += ( const neQ& Q );
NEINLINE neQ& operator -= ( const neQ& Q );
NEINLINE neQ& Set (f32 X, f32 Y, f32 Z, f32 W);
NEINLINE neQ& Set (const neV3 & V, f32 W);
NEINLINE neQ& Set (f32 angle, const neV3 & axis);
NEINLINE friend neQ operator - ( const neQ& V );
NEINLINE friend neQ operator * ( const neQ& Qa, const neQ& Qb );
NEINLINE friend neV3 operator * ( const neQ& Q, const neV3& V );
NEINLINE friend neQ operator * ( const neQ& Q, f32 S );
NEINLINE friend neQ operator * ( f32 S, const neQ& Q );
NEINLINE friend neQ operator + ( const neQ& Qa, const neQ& Qb );
NEINLINE friend neQ operator - ( const neQ& Qa, const neQ& Qb );
};
/****************************************************************************
*
* neT3
*
****************************************************************************/
struct neT3
{
public:
neM3 rot;
neV3 pos;
NEINLINE neT3 FastInverse();
NEINLINE neT3 operator * (const neT3 & t);
NEINLINE neV3 operator * (const neV3 & v);
NEINLINE neBool IsFinite();
public:
NEINLINE void MakeD3DCompatibleMatrix()
{
rot[0].v[3] = 0.0f;
rot[1].v[3] = 0.0f;
rot[2].v[3] = 0.0f;
pos.v[3] = 1.0f;
}
NEINLINE void SetIdentity()
{
rot.SetIdentity();
pos.SetZero();
/*
* additional code to make this binary compatible with rendering matrix
*/
MakeD3DCompatibleMatrix();
}
#ifdef USE_OPCODE
NEINLINE neT3 & operator = (const IceMaths::Matrix4x4 & mat);
NEINLINE IceMaths::Matrix4x4 & AssignIceMatrix(IceMaths::Matrix4x4 & mat) const;
#endif //USE_OPCODE
};
///////////////////////////////////////////////////////////////////////////
// INCLUDE INLINE HEADERS
///////////////////////////////////////////////////////////////////////////
#include "ne_math_misc_inline.h"
#include "ne_math_v3_inline.h"
#include "ne_math_v4_inline.h"
#include "ne_math_m4_inline.h"
#include "ne_math_m3_inline.h"
#include "ne_math_q_inline.h"
#include "ne_math_t3_inline.h"
///////////////////////////////////////////////////////////////////////////
// END
///////////////////////////////////////////////////////////////////////////
#endif //NE_MATH_H
|
7285105e864414531787d5ef50125093443b850e | 3ad9b096e235bebec814e9d6bd0bea9473a24f2d | /src/avt/Pipeline/Data/avtLightingModel.h | 06d17619e36c93e5f42650ddd728c18037e1ae3b | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | larrycameron80/visit | bca20089d4642fc9e40f605404bc5408ef4c465f | e20e2ddbec3b0ceb611a0588898f652432165a24 | refs/heads/develop | 2020-06-05T09:28:16.704247 | 2019-06-14T22:02:59 | 2019-06-14T22:02:59 | 192,389,674 | 0 | 0 | BSD-3-Clause | 2019-09-17T07:05:10 | 2019-06-17T17:23:31 | C | UTF-8 | C++ | false | false | 5,226 | h | avtLightingModel.h | /*****************************************************************************
*
* Copyright (c) 2000 - 2019, Lawrence Livermore National Security, LLC
* Produced at the Lawrence Livermore National Laboratory
* LLNL-CODE-442911
* All rights reserved.
*
* This file is part of VisIt. For details, see https://visit.llnl.gov/. The
* full copyright notice is contained in the file COPYRIGHT located at the root
* of the VisIt distribution or at http://www.llnl.gov/visit/copyright.html.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the disclaimer below.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the disclaimer (as noted below) in the
* documentation and/or other materials provided with the distribution.
* - Neither the name of the LLNS/LLNL nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL LAWRENCE LIVERMORE NATIONAL SECURITY,
* LLC, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*
*****************************************************************************/
// ************************************************************************* //
// avtLightingModel.h //
// ************************************************************************* //
#ifndef AVT_LIGHTING_MODEL
#define AVT_LIGHTING_MODEL
#include <pipeline_exports.h>
#include <LightList.h>
class avtRay;
// ****************************************************************************
// Class: avtLightingModel
//
// Purpose:
// An abstract type that defines a lighting model. It is only an
// interface.
//
// Programmer: Hank Childs
// Creation: November 29, 2000
//
// Modifications:
// Brad Whitlock, Wed Apr 24 10:18:48 PDT 2002
// Added constructor and destructor so the vtable gets into the Windows DLL.
//
// ****************************************************************************
class PIPELINE_API avtLightingModel
{
public:
avtLightingModel();
virtual ~avtLightingModel();
virtual void AddLighting(int, const avtRay *, unsigned char *)
const = 0;
virtual void AddLightingHeadlight(int, const avtRay *, unsigned char *, double alpha, double matProperties[4])
const = 0;
void SetGradientVariableIndex(int gvi)
{ gradientVariableIndex = gvi; };
void SetViewDirection(double *vd)
{ view_direction[0] = vd[0];
view_direction[1] = vd[1];
view_direction[2] = vd[2];
ComputeViewRight();
};
void SetViewUp(double *vu)
{ view_up[0] = vu[0];
view_up[1] = vu[1];
view_up[2] = vu[2];
ComputeViewRight();
};
void SetLightInfo(const LightList &ll)
{ lights = ll; };
void SetSpecularInfo(bool ds, double sc, double sp)
{ doSpecular = ds; specularCoeff = sc;
specularPower = sp; };
void ComputeViewRight()
{
view_right[0] = view_direction[1]*view_up[2] - view_direction[2]*view_up[1];
view_right[1] = view_direction[2]*view_up[0] - view_direction[0]*view_up[2];
view_right[2] = view_direction[0]*view_up[1] - view_direction[1]*view_up[0];
}
protected:
int gradientVariableIndex;
double view_direction[3];
double view_up[3];
double view_right[3];
LightList lights;
bool doSpecular;
double specularCoeff;
double specularPower;
};
#endif
|
adcf0eb48916419a61d71267bc02b3c79b3c9dbc | ac7683edcdfddf481a704bd02e334d1d695aea3a | /bbtoDijetAnalyzer/plugins/bbtoDijetAnalyzer.cc | 2fc1b60fe10d27cc7bb8181e512092877fd4c9f6 | [
"MIT"
] | permissive | avkhadiev/bbtoDijet | cf4884f2b71e6abb593332d0a0437e00e347ff1d | d04c4c150ed21a0b51344410a01deeff36aa04f6 | refs/heads/master | 2021-01-17T08:11:55.336927 | 2016-08-09T15:03:25 | 2016-08-09T15:03:25 | 63,870,509 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 29,981 | cc | bbtoDijetAnalyzer.cc | // -*- C++ -*-
//
// Package: bbtoDijet/bbtoDijetAnalyzer
// Class: bbtoDijetAnalyzer
//
/**\class bbtoDijetAnalyzer bbtoDijetAnalyzer.cc bbtoDijet/bbtoDijetAnalyzer/plugins/bbtoDijetAnalyzer.cc
Description: collect b-tagging data (online and offline), calo and pf jet kinematics, and trigger results
Implementation:
- set up tree variables during construction
- clear (memset) variables before each event
- collect data in analyze() per event
- delete tree variables during destruction
FIXME: branches for trigger results are created in analyze();
corresponding arrays are not cleared nor deleted.
This can lead to excessive memory use on some CRAB jobs, need testing to verify.
FIXME: getting data for calo and pf jets, and getting data for online and offline CSV tags is very similar;
writing two functions to get the event information will simplify code
*/
//
// Original Author: Artur Avkhadiev
// Created: Fri, 22 Jul 2016 08:05:25 GMT
//
//
// system include file
#include <memory> // included by default
#include <TTree.h> // added in
// user include files
#include "FWCore/Framework/interface/Frameworkfwd.h" // included by default
#include "FWCore/Framework/interface/one/EDAnalyzer.h"
#include "FWCore/Framework/interface/Event.h"
#include "FWCore/Framework/interface/MakerMacros.h"
#include "FWCore/ParameterSet/interface/ParameterSet.h"
#include "FWCore/Framework/interface/EventSetup.h" // added in
#include "FWCore/Framework/interface/ESHandle.h" // https://cmssdt.cern.ch/SDT/doxygen/CMSSW_8_0_13/doc/html/dd/d5c/HLTBitAnalyzer_8h_source.html
#include "FWCore/Framework/interface/ConsumesCollector.h" // https://cmssdt.cern.ch/SDT/doxygen/CMSSW_8_0_13/doc/html/d2/d04/HLTJets_8h_source.html
#include "FWCore/ParameterSet/interface/ConfigurationDescriptions.h" // https://cmssdt.cern.ch/SDT/doxygen/CMSSW_8_0_9/doc/html/df/d03/HLTEventAnalyzerRAW_8cc_source.html
#include "FWCore/MessageLogger/interface/MessageLogger.h" // https://cmssdt.cern.ch/SDT/doxygen/CMSSW_8_0_13/doc/html/d5/d74/HLTBitAnalyzer_8cc_source.html
#include "FWCore/ServiceRegistry/interface/Service.h"
#include "CommonTools/UtilAlgos/interface/TFileService.h"
#include "HLTrigger/HLTanalyzers/interface/EventHeader.h" // https://cmssdt.cern.ch/SDT/doxygen/CMSSW_8_0_13/doc/html/dd/d5c/HLTBitAnalyzer_8h_source.html
#include "HLTrigger/HLTanalyzers/src/EventHeader.cc"
#include "HLTrigger/HLTanalyzers/interface/HLTInfo.h"
#include "HLTrigger/HLTcore/interface/HLTConfigProvider.h" // https://cmssdt.cern.ch/SDT/doxygen/CMSSW_8_0_13/doc/html/d2/dc0/HLTEventAnalyzerAOD_8cc_source.html
#include "FWCore/Common/interface/TriggerNames.h"
#include "FWCore/Common/interface/TriggerResultsByName.h"
#include "DataFormats/Common/interface/Handle.h"
// event content access
#include "DataFormats/Common/interface/TriggerResults.h" // trigger-related information
#include "DataFormats/HLTReco/interface/TriggerEvent.h"
#include "DataFormats/JetReco/interface/CaloJetCollection.h" // jet-related information
#include "DataFormats/JetReco/interface/PFJetCollection.h" // https://cmssdt.cern.ch/SDT/doxygen/CMSSW_8_0_13/doc/html/d2/d04/HLTJets_8h_source.html
#include "DataFormats/JetReco/interface/Jet.h" // b-jet-tagging information
#include "DataFormats/BTauReco/interface/JetTag.h" // https://cmssdt.cern.ch/SDT/doxygen/CMSSW_8_0_13/doc/html/d2/d2e/HLTBJet_8h_source.html
//
// class declaration
//
// If the analyzer does not use TFileService, please remove
// the template argument to the base class so the class inherits
// from edm::one::EDAnalyzer<> and also remove the line from
// constructor "usesResource("TFileService");"
// This will improve performance in multithreaded jobs.
class bbtoDijetAnalyzer : public edm::one::EDAnalyzer<edm::one::SharedResources> {
public:
explicit bbtoDijetAnalyzer(const edm::ParameterSet&);
~bbtoDijetAnalyzer();
static void fillDescriptions(edm::ConfigurationDescriptions& descriptions);
private:
virtual void beginJob() override;
virtual void clear();
virtual void analyze(const edm::Event&, const edm::EventSetup&) override;
virtual void endJob() override;
virtual void beginRun(edm::Run const&, edm::EventSetup const&) ;
virtual void endRun (edm::Run const&, edm::EventSetup const&) ;
// ----------member data ---------------------------
HLTConfigProvider hltConfig_ ;
EventHeader eventHeader_ ;
std::string processName_ ;
// input tags
const edm::InputTag triggerResultsTag_ ;
const edm::InputTag triggerEventTag_ ;
const edm::InputTag caloJetsTag_ ;
const edm::InputTag pfJetsTag_ ;
const edm::InputTag bTagCSVOnlineTag_ ;
const edm::InputTag bTagCSVOfflineTag_ ;
// tokens
const edm::EDGetTokenT<edm::TriggerResults> triggerResultsToken_ ;
const edm::EDGetTokenT<trigger::TriggerEvent> triggerEventToken_ ;
const edm::EDGetTokenT<reco::CaloJetCollection> caloJetsToken_ ;
const edm::EDGetTokenT<reco::PFJetCollection> pfJetsToken_ ;
const edm::EDGetTokenT<reco::JetTagCollection> bTagCSVOnlineToken_ ;
const edm::EDGetTokenT<reco::JetTagCollection> bTagCSVOfflineToken_ ;
// tree variables
// array sizes
static const size_t kMaxTriggerPass_ = 10000 ;
static const size_t kMaxCaloJet_ = 10000 ;
static const size_t kMaxPFJet_ = 10000 ;
static const size_t kMaxBTagCSVOnline_ = 1000 ;
static const size_t kMaxBTagCSVOffline_ = 1000 ;
// set of variables for
// event-header information: included in eventHeader_
// trigger-related information
bool firstEvent_ ; // will create new branch for trigger path if firstEvent_ = true
unsigned int *triggerPass_ ;
// jet-related information
// CaloJet
int caloJetCounter_ ;
double *caloJetPt_ ;
float *caloJetEta_ ;
float *caloJetPhi_ ;
double *caloJetEt_ ;
float *caloJetMass_ ;
double *caloJetEnergy_ ;
double *caloJetPx_ ;
double *caloJetPy_ ;
double *caloJetPz_ ;
// PFJet
int pfJetCounter_ ;
double *pfJetPt_ ;
float *pfJetEta_ ;
float *pfJetPhi_ ;
double *pfJetEt_ ;
double *pfJetMass_ ;
double *pfJetEnergy_ ;
double *pfJetPx_ ;
double *pfJetPy_ ;
double *pfJetPz_ ;
// b-jet-tagging information
// bTagCSVOnline
int bTagCSVOnlineJetCounter_ ;
double *bTagCSVOnlineJetPt_ ;
float *bTagCSVOnlineJetEta_ ;
float *bTagCSVOnlineJetPhi_ ;
double *bTagCSVOnlineJetEt_ ;
double *bTagCSVOnlineJetMass_ ;
float *bTagCSVOnline_ ;
// bTagCSVOffline
int bTagCSVOfflineJetCounter_ ;
double *bTagCSVOfflineJetPt_ ;
float *bTagCSVOfflineJetEta_ ;
float *bTagCSVOfflineJetPhi_ ;
double *bTagCSVOfflineJetEt_ ;
double *bTagCSVOfflineJetMass_ ;
float *bTagCSVOffline_ ;
TTree* outTree_;
};
//
// constructors and destructor
//
bbtoDijetAnalyzer::bbtoDijetAnalyzer(const edm::ParameterSet& iConfig) :
processName_ (iConfig.getParameter<std::string>("processName")),
// initialize input tags
// (strings should match variable names in the *.py config file)
triggerResultsTag_ (iConfig.getParameter<edm::InputTag>("triggerResults")),
triggerEventTag_ (iConfig.getParameter<edm::InputTag>("triggerEvent")),
caloJetsTag_ (iConfig.getParameter<edm::InputTag>("caloJets")),
pfJetsTag_ (iConfig.getParameter<edm::InputTag>("pfJets")),
bTagCSVOnlineTag_ (iConfig.getParameter<edm::InputTag>("bTagCSVOnline")),
bTagCSVOfflineTag_ (iConfig.getParameter<edm::InputTag>("bTagCSVOffline")),
// initialize tokens
triggerResultsToken_ (consumes<edm::TriggerResults>(triggerResultsTag_)),
triggerEventToken_ (consumes<trigger::TriggerEvent>(triggerEventTag_)),
caloJetsToken_ (consumes<reco::CaloJetCollection>(caloJetsTag_)),
pfJetsToken_ (consumes<reco::PFJetCollection>(pfJetsTag_)),
bTagCSVOnlineToken_ (consumes<reco::JetTagCollection>(bTagCSVOnlineTag_)),
bTagCSVOfflineToken_ (consumes<reco::JetTagCollection>(bTagCSVOfflineTag_)),
// initialize tree variables
firstEvent_ (true)
{
//now do what ever initialization is needed
usesResource("TFileService");
/* Setup the analysis to put the branch-variables into the tree. */
// set of variables for
// event-header information: included in eventHeader_
// trigger-related information
triggerPass_ = new unsigned int[kMaxTriggerPass_] ;
// jet-related information
// CaloJet
caloJetCounter_ = 0 ;
caloJetPt_ = new double[kMaxCaloJet_] ;
caloJetEta_ = new float[kMaxCaloJet_] ;
caloJetPhi_ = new float[kMaxCaloJet_] ;
caloJetEt_ = new double[kMaxCaloJet_] ;
caloJetMass_ = new float[kMaxCaloJet_] ;
caloJetEnergy_ = new double[kMaxCaloJet_] ;
caloJetPx_ = new double[kMaxCaloJet_] ;
caloJetPy_ = new double[kMaxCaloJet_] ;
caloJetPz_ = new double[kMaxCaloJet_] ;
// PFJet
pfJetCounter_ = 0 ;
pfJetPt_ = new double[kMaxPFJet_] ;
pfJetEta_ = new float[kMaxPFJet_] ;
pfJetPhi_ = new float[kMaxPFJet_] ;
pfJetEt_ = new double[kMaxPFJet_] ;
pfJetMass_ = new double[kMaxPFJet_] ;
pfJetEnergy_ = new double[kMaxPFJet_] ;
pfJetPx_ = new double[kMaxPFJet_] ;
pfJetPy_ = new double[kMaxPFJet_] ;
pfJetPz_ = new double[kMaxPFJet_] ;
// b-jet-tagging information
// bTagCSVOnline
bTagCSVOnlineJetCounter_ = 0 ;
bTagCSVOnlineJetPt_ = new double[kMaxBTagCSVOnline_] ;
bTagCSVOnlineJetEta_ = new float[kMaxBTagCSVOnline_] ;
bTagCSVOnlineJetPhi_ = new float[kMaxBTagCSVOnline_] ;
bTagCSVOnlineJetEt_ = new double[kMaxBTagCSVOnline_] ;
bTagCSVOnlineJetMass_ = new double[kMaxBTagCSVOnline_] ;
bTagCSVOnline_ = new float[kMaxBTagCSVOnline_] ;
// bTagCSVOffline
bTagCSVOfflineJetCounter_ = 0 ;
bTagCSVOfflineJetPt_ = new double[kMaxBTagCSVOffline_] ;
bTagCSVOfflineJetEta_ = new float[kMaxBTagCSVOffline_] ;
bTagCSVOfflineJetPhi_ = new float[kMaxBTagCSVOffline_] ;
bTagCSVOfflineJetEt_ = new double[kMaxBTagCSVOffline_] ;
bTagCSVOfflineJetMass_ = new double[kMaxBTagCSVOffline_] ;
bTagCSVOffline_ = new float[kMaxBTagCSVOffline_] ;
// open the tree file and initialize the tree
edm::Service<TFileService> fs ;
outTree_ = fs->make<TTree>("efficiencyTree", "") ;
// setup event header and HLT results analysis
eventHeader_.setup(consumesCollector(), outTree_);
// create branches
// slash letter is ROOT's way for figuring out types:
// I is int
// F is float
// D is double
// sets of variables for
// event-header information: included in eventHeader_
// trigger-related information: created in ``analyze''
// jet-related information
// CaloJet
outTree_->Branch("caloJetCounter", &caloJetCounter_, "caloJetCounter/I") ;
outTree_->Branch("caloJetPt", caloJetPt_, "caloJetPT[caloJetCounter]/D") ;
outTree_->Branch("caloJetEta", caloJetEta_, "caloJetEta[caloJetCounter]/F") ;
outTree_->Branch("caloJetPhi", caloJetPhi_, "caloJetPhi[caloJetCounter]/F") ;
outTree_->Branch("caloJetEt", caloJetEt_, "caloJetEt[caloJetCounter]/D") ;
outTree_->Branch("caloJetMass", caloJetMass_, "caloJetMass[caloJetCounter]/F") ;
outTree_->Branch("caloJetEnergy", caloJetEnergy_, "caloJetEnergy[caloJetCounter]/D") ;
outTree_->Branch("caloJetPx", caloJetPx_, "caloJetPx[caloJetCounter]/D") ;
outTree_->Branch("caloJetPy", caloJetPy_, "caloJetPy[caloJetCounter]/D") ;
outTree_->Branch("caloJetPz", caloJetPz_, "caloJetPz[caloJetCounter]/D") ;
// PFJet
outTree_->Branch("pfJetCounter", &pfJetCounter_, "pfJetCounter/I") ;
outTree_->Branch("pfJetPt", pfJetPt_, "pfJetPT[pfJetCounter]/D") ;
outTree_->Branch("pfJetEta", pfJetEta_, "pfJetEta[pfJetCounter]/F") ;
outTree_->Branch("pfJetPhi", pfJetPhi_, "pfJetPhi[pfJetCounter]/F") ;
outTree_->Branch("pfJetEt", pfJetEt_, "pfJetEt[pfJetCounter]/D") ;
outTree_->Branch("pfJetMass", pfJetMass_, "pfJetMass[pfJetCounter]/D") ;
outTree_->Branch("pfJetEnergy", pfJetEnergy_, "pfJetEnergy[pfJetCounter]/D") ;
outTree_->Branch("pfJetPx", pfJetPx_, "pfJetPx[pfJetCounter]/D") ;
outTree_->Branch("pfJetPy", pfJetPy_, "pfJetPy[pfJetCounter]/D") ;
outTree_->Branch("pfJetPz", pfJetPz_, "pfJetPz[pfJetCounter]/D") ;
// b-jet-tagging information
// bTagCSVOnline
outTree_->Branch("bTagCSVOnlineJetCounter", &bTagCSVOnlineJetCounter_, "bTagCSVOnlineJetCounter/I") ;
outTree_->Branch("bTagCSVOnlineJetPt", bTagCSVOnlineJetPt_, "bTagCSVOnlineJetPt[bTagCSVOnlineJetCounter]/D") ;
outTree_->Branch("bTagCSVOnlineJetEta", bTagCSVOnlineJetEta_, "bTagCSVOnlineJetEta[bTagCSVOnlineJetCounter]/F") ;
outTree_->Branch("bTagCSVOnlineJetPhi", bTagCSVOnlineJetPhi_, "bTagCSVOnlineJetPhi[bTagCSVOnlineJetCounter]/F") ;
outTree_->Branch("bTagCSVOnlineJetEt", bTagCSVOnlineJetEt_, "bTagCSVOnlineJetEt[bTagCSVOnlineJetCounter]/D") ;
outTree_->Branch("bTagCSVOnlineJetMass", bTagCSVOnlineJetMass_, "bTagCSVOnlineJetMass[bTagCSVOnlineJetCounter]/D") ;
outTree_->Branch("bTagCSVOnline", bTagCSVOnline_, "bTagCSVOnline[bTagCSVOnlineJetCounter]/F") ;
// bTagCSVOffline
outTree_->Branch("bTagCSVOfflineJetCounter", &bTagCSVOfflineJetCounter_, "bTagCSVOfflineJetCounter/I") ;
outTree_->Branch("bTagCSVOfflineJetPt", bTagCSVOfflineJetPt_, "bTagCSVOfflineJetPt[bTagCSVOfflineJetCounter]/D") ;
outTree_->Branch("bTagCSVOfflineJetEta", bTagCSVOfflineJetEta_, "bTagCSVOfflineJetEta[bTagCSVOfflineJetCounter]/F") ;
outTree_->Branch("bTagCSVOfflineJetPhi", bTagCSVOfflineJetPhi_, "bTagCSVOfflineJetPhi[bTagCSVOfflineJetCounter]/F") ;
outTree_->Branch("bTagCSVOfflineJetEt", bTagCSVOfflineJetEt_, "bTagCSVOfflineJetEt[bTagCSVOfflineJetCounter]/D") ;
outTree_->Branch("bTagCSVOfflineJetMass", bTagCSVOfflineJetMass_, "bTagCSVOfflineJetMass[bTagCSVOfflineJetCounter]/D") ;
outTree_->Branch("bTagCSVOffline", bTagCSVOffline_, "bTagCSVOffline[bTagCSVOfflineJetCounter]/F") ;
}
bbtoDijetAnalyzer::~bbtoDijetAnalyzer()
{
// do anything here that needs to be done at desctruction time
// (e.g. close files, deallocate resources etc.)
// jet-related information
// CaloJet
delete[] caloJetPt_ ;
delete[] caloJetEta_ ;
delete[] caloJetPhi_ ;
delete[] caloJetEt_ ;
delete[] caloJetMass_ ;
delete[] caloJetEnergy_ ;
delete[] caloJetPx_ ;
delete[] caloJetPy_ ;
delete[] caloJetPz_ ;
// PFJet
delete[] pfJetPt_ ;
delete[] pfJetEta_ ;
delete[] pfJetPhi_ ;
delete[] pfJetEt_ ;
delete[] pfJetMass_ ;
delete[] pfJetEnergy_ ;
delete[] pfJetPx_ ;
delete[] pfJetPy_ ;
delete[] pfJetPz_ ;
// b-jet-tagging information
// bTagCSVOnline
delete[] bTagCSVOnlineJetPt_ ;
delete[] bTagCSVOnlineJetEta_ ;
delete[] bTagCSVOnlineJetPhi_ ;
delete[] bTagCSVOnlineJetEt_ ;
delete[] bTagCSVOnlineJetMass_ ;
delete[] bTagCSVOnline_ ;
// bTagCSVOffline
delete[] bTagCSVOfflineJetPt_ ;
delete[] bTagCSVOfflineJetEta_ ;
delete[] bTagCSVOfflineJetPhi_ ;
delete[] bTagCSVOfflineJetEt_ ;
delete[] bTagCSVOfflineJetMass_ ;
delete[] bTagCSVOffline_ ;
}
//
// member functions
//
// ----------- method called in the body of analyze to clear memory ----------------
// ----------- does not clear memory for trigger results! ----------------
void
bbtoDijetAnalyzer::clear()
{
// set memory for branch variables
// jet-related information
// CaloJet
caloJetCounter_ = 0 ;
std::memset(caloJetPt_, '\0', kMaxCaloJet_ * sizeof(double)) ;
std::memset(caloJetEta_, '\0', kMaxCaloJet_ * sizeof(float)) ;
std::memset(caloJetPhi_, '\0', kMaxCaloJet_ * sizeof(float)) ;
std::memset(caloJetEt_, '\0', kMaxCaloJet_ * sizeof(double)) ;
std::memset(caloJetMass_, '\0', kMaxCaloJet_ * sizeof(float)) ;
std::memset(caloJetEnergy_, '\0', kMaxCaloJet_ * sizeof(double)) ;
std::memset(caloJetPx_, '\0', kMaxCaloJet_ * sizeof(double)) ;
std::memset(caloJetPy_, '\0', kMaxCaloJet_ * sizeof(double)) ;
std::memset(caloJetPz_, '\0', kMaxCaloJet_ * sizeof(double)) ;
// CaloJet
pfJetCounter_ = 0 ;
std::memset(pfJetPt_, '\0', kMaxPFJet_ * sizeof(double)) ;
std::memset(pfJetEta_, '\0', kMaxPFJet_ * sizeof(float)) ;
std::memset(pfJetPhi_, '\0', kMaxPFJet_ * sizeof(float)) ;
std::memset(pfJetEt_, '\0', kMaxPFJet_ * sizeof(double)) ;
std::memset(pfJetMass_, '\0', kMaxPFJet_ * sizeof(double)) ;
std::memset(pfJetEnergy_, '\0', kMaxPFJet_ * sizeof(double)) ;
std::memset(pfJetPx_, '\0', kMaxPFJet_ * sizeof(double)) ;
std::memset(pfJetPy_, '\0', kMaxPFJet_ * sizeof(double)) ;
std::memset(pfJetPz_, '\0', kMaxPFJet_ * sizeof(double)) ;
// b-jet-tagging information
// bTagCSVOnline
bTagCSVOnlineJetCounter_ = 0 ;
std::memset(bTagCSVOnlineJetPt_, '\0', kMaxBTagCSVOnline_ * sizeof(double)) ;
std::memset(bTagCSVOnlineJetEta_, '\0', kMaxBTagCSVOnline_ * sizeof(float)) ;
std::memset(bTagCSVOnlineJetPhi_, '\0', kMaxBTagCSVOnline_ * sizeof(float)) ;
std::memset(bTagCSVOnlineJetEt_, '\0', kMaxBTagCSVOnline_ * sizeof(double)) ;
std::memset(bTagCSVOnlineJetMass_, '\0', kMaxBTagCSVOnline_ * sizeof(double)) ;
std::memset(bTagCSVOnline_, '\0', kMaxBTagCSVOnline_ * sizeof(float)) ;
// bTagCSVOffline
bTagCSVOfflineJetCounter_ = 0 ;
std::memset(bTagCSVOfflineJetPt_, '\0', kMaxBTagCSVOffline_ * sizeof(double)) ;
std::memset(bTagCSVOfflineJetEta_, '\0', kMaxBTagCSVOffline_ * sizeof(float)) ;
std::memset(bTagCSVOfflineJetPhi_, '\0', kMaxBTagCSVOffline_ * sizeof(float)) ;
std::memset(bTagCSVOfflineJetEt_, '\0', kMaxBTagCSVOffline_ * sizeof(double)) ;
std::memset(bTagCSVOfflineJetMass_,'\0', kMaxBTagCSVOffline_ * sizeof(double)) ;
std::memset(bTagCSVOffline_, '\0', kMaxBTagCSVOffline_ * sizeof(float)) ;
}
// ------------ method called for each event ------------
void
bbtoDijetAnalyzer::analyze(const edm::Event& iEvent, const edm::EventSetup& iSetup)
{
// set handles
edm::Handle<edm::TriggerResults> triggerResultsHandle ;
edm::Handle<trigger::TriggerEvent> triggerEventHandle ;
edm::Handle<reco::CaloJetCollection> caloJetsHandle ;
edm::Handle<reco::PFJetCollection> pfJetsHandle ;
edm::Handle<reco::JetTagCollection> bTagCSVOnlineHandle ;
edm::Handle<reco::JetTagCollection> bTagCSVOfflineHandle ;
// get event header
eventHeader_.analyze(iEvent, outTree_);
// get trigger results
iEvent.getByToken(triggerResultsToken_, triggerResultsHandle) ;
edm::TriggerNames const& triggerNames = iEvent.triggerNames(*triggerResultsHandle) ;
for(unsigned int itrig = 0; itrig != triggerResultsHandle->size(); ++itrig) {
TString triggerName = triggerNames.triggerName(itrig);
if(firstEvent_){
outTree_->Branch(triggerName, &triggerPass_[itrig], triggerName+"/i");
}
bool accept = triggerResultsHandle->accept(itrig);
if(accept) triggerPass_[itrig] = 1;
else triggerPass_[itrig] = 0;
}
if(firstEvent_) firstEvent_ = false;
// if the required collections are available, fill the corresponding tree branches
// get jet-related information
// CaloJets
if(iEvent.getByToken(caloJetsToken_, caloJetsHandle)){
const reco::CaloJetCollection & caloJets = *(caloJetsHandle.product());
caloJetCounter_ = caloJets.size();
for(int i = 0; i != caloJetCounter_; ++i) {
caloJetPt_[i] = caloJets[i].pt() ;
caloJetEta_[i] = caloJets[i].eta() ;
caloJetPhi_[i] = caloJets[i].phi() ;
caloJetEt_[i] = caloJets[i].et() ;
caloJetMass_[i] = caloJets[i].mass() ;
caloJetEnergy_[i] = caloJets[i].energy() ;
caloJetPx_[i] = caloJets[i].px() ;
caloJetPy_[i] = caloJets[i].py() ;
caloJetPz_[i] = caloJets[i].pz() ;
}
}
// PFJets
if(iEvent.getByToken(pfJetsToken_, pfJetsHandle)){
const reco::PFJetCollection & pfJets = *(pfJetsHandle.product());
pfJetCounter_ = pfJets.size();
for(int i = 0; i != pfJetCounter_; ++i) {
pfJetPt_[i] = pfJets[i].pt() ;
pfJetEta_[i] = pfJets[i].eta() ;
pfJetPhi_[i] = pfJets[i].phi() ;
pfJetEt_[i] = pfJets[i].et() ;
pfJetMass_[i] = pfJets[i].mass() ;
pfJetEnergy_[i] = pfJets[i].energy() ;
pfJetPx_[i] = pfJets[i].px() ;
pfJetPy_[i] = pfJets[i].py() ;
pfJetPz_[i] = pfJets[i].pz() ;
}
}
// get b-jet-tagging information
// bTagCSVOnline
if(iEvent.getByToken(bTagCSVOnlineToken_, bTagCSVOnlineHandle)){
const reco::JetTagCollection & bTagCSVOnline = *(bTagCSVOnlineHandle.product());
bTagCSVOnlineJetCounter_ = bTagCSVOnline.size();
for(int i = 0; i != bTagCSVOnlineJetCounter_; ++i){
// save the tag and corresponding pt
// see https://twiki.cern.ch/twiki/bin/view/CMSPublic/WorkBookBTagEdAnalyzer17X
bTagCSVOnlineJetPt_[i] = bTagCSVOnline[i].first->pt() ;
bTagCSVOnlineJetEta_[i] = bTagCSVOnline[i].first->eta() ;
bTagCSVOnlineJetPhi_[i] = bTagCSVOnline[i].first->phi() ;
bTagCSVOnlineJetEt_[i] = bTagCSVOnline[i].first->et() ;
bTagCSVOnlineJetMass_[i] = bTagCSVOnline[i].first->mass() ;
bTagCSVOnline_[i] = bTagCSVOnline[i].second ;
}
}
// bTagCSVOffline
if(iEvent.getByToken(bTagCSVOfflineToken_, bTagCSVOfflineHandle)){
const reco::JetTagCollection & bTagCSVOffline = *(bTagCSVOfflineHandle.product());
bTagCSVOfflineJetCounter_ = bTagCSVOffline.size();
for(int i = 0; i != bTagCSVOfflineJetCounter_; ++i){
// save the tag and corresponding pt
// see https://twiki.cern.ch/twiki/bin/view/CMSPublic/WorkBookBTagEdAnalyzer17X
bTagCSVOfflineJetPt_[i] = bTagCSVOffline[i].first->pt() ;
bTagCSVOfflineJetEta_[i] = bTagCSVOffline[i].first->eta() ;
bTagCSVOfflineJetPhi_[i] = bTagCSVOffline[i].first->phi() ;
bTagCSVOfflineJetEt_[i] = bTagCSVOffline[i].first->et() ;
bTagCSVOfflineJetMass_[i] = bTagCSVOffline[i].first->mass();
bTagCSVOffline_[i] = bTagCSVOffline[i].second ;
}
}
outTree_->Fill();
}
// ------------ method called once each job just before starting event loop ------------
void
bbtoDijetAnalyzer::beginJob()
{
}
// ------------ method called once each job just after ending the event loop ------------
void
bbtoDijetAnalyzer::endJob()
{
}
// ------------ method called when starting to processes a run ------------
void
bbtoDijetAnalyzer::beginRun(edm::Run const &run, edm::EventSetup const &es)
{
bool changed;
if (!hltConfig_.init(run, es, processName_, changed)) {
edm::LogError("bbtoDijetAnalyzer") << "Initialization of HLTConfigProvider failed.";
return;
}
}
// ------------ method called when starting to processes a run ------------
void
bbtoDijetAnalyzer::endRun(edm::Run const&, edm::EventSetup const&)
{}
// ------------ method fills 'descriptions' with the allowed parameters for the module ------------
void
bbtoDijetAnalyzer::fillDescriptions(edm::ConfigurationDescriptions& descriptions) {
// Please change this to state exactly what you do use, even if it is no parameters
edm::ParameterSetDescription desc;
desc.add<std::string>("processName", "TEST");
desc.add<edm::InputTag>("triggerResults", edm::InputTag("TriggerResults::TEST"));
desc.add<edm::InputTag>("triggerEvent", edm::InputTag("hltTriggerSummaryAOD", "", "TEST"));
desc.add<edm::InputTag>("caloJets", edm::InputTag("ak4CaloJets::RECO"));
desc.add<edm::InputTag>("pfJets", edm::InputTag("ak4PFJets::RECO"));
desc.add<edm::InputTag>("bTagCSVOnline", edm::InputTag("hltCombinedSecondaryVertexBJetTagsCalo"));
desc.add<edm::InputTag>("bTagCSVOffline", edm::InputTag("pfCombinedSecondaryVertexV2BJetTags"));
descriptions.add("bbtoDijetAnalyzer", desc);
}
//define this as a plug-in
DEFINE_FWK_MODULE(bbtoDijetAnalyzer);
|
e084ae712e9f93c8949ded0740eddcfbcc17f950 | 7dc67a956d5516c8c8d9234861ec21b8d9111213 | /Leet2015/Leet2015/ReadNCharactersGivenRead4II.cpp | 1073e237cbba3c5a727195c574f6ea2fb0dedc6f | [] | no_license | flameshimmer/leet2015 | 285a1f4f0c31789e1012a7c056797915662611ba | 45297dfe330a16f001fb0b2c8cc3df99b2c76dda | refs/heads/master | 2021-01-22T05:15:40.849200 | 2015-08-15T19:46:43 | 2015-08-15T19:46:43 | 31,512,278 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,312 | cpp | ReadNCharactersGivenRead4II.cpp | #include "stdafx.h"
//The API : int read4(char *buf) reads 4 characters at a time from a file.
//
//The return value is the actual number of characters read.For example,
//it returns 3 if there is only 3 characters left in the file.
//
//By using the read4 API, implement the function int read(char *buf, int n)
//that reads n characters from the file.
//
//Note :
// The read function may be called multiple times.
namespace Solution1
{
/**
* @param buf Destination buffer
* @param n Maximum number of characters to read
* @return The number of characters read
*/
namespace II
{
// Read4 API.
int read4(char *buf){ return 4; }
char _buf[4];
int _bufIndex = 0;
int _readCount = 0;
int read(char* buf, int n)
{
int remain = n;
while (_bufIndex < _readCount && remain > 0)
{
*buf = _buf[_bufIndex];
buf++;
remain--;
_bufIndex++;
}
while (remain > 0)
{
_readCount = read4(_buf);
_bufIndex = 0;
for (; _bufIndex < _readCount && remain > 0; _bufIndex++)
{
*buf = _buf[_bufIndex];
buf++;
remain--;
}
if (_readCount < 4) { break; }
}
return n - remain;
}
}
void ReadNCharactersGivenRead4II()
{
string input = "ab";
char* in = (char*)(input.c_str());
II::read(in, 1);
II::read(in, 2);
}
} |
e207044189aa9d860126cbdfd809040ea4a0a46d | 877fff5bb313ccd23d1d01bf23b1e1f2b13bb85a | /app/src/main/cpp/dir521/dir522/dir572/dir2774/dir2775/file2795.cpp | cf50a34532cb9a929013281c9daadde1034e7b32 | [] | no_license | tgeng/HugeProject | 829c3bdfb7cbaf57727c41263212d4a67e3eb93d | 4488d3b765e8827636ce5e878baacdf388710ef2 | refs/heads/master | 2022-08-21T16:58:54.161627 | 2020-05-28T01:54:03 | 2020-05-28T01:54:03 | 267,468,475 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 111 | cpp | file2795.cpp | #ifndef file2795
#error "macro file2795 must be defined"
#endif
static const char* file2795String = "file2795"; |
82dddcbda0c811c78d5272aba5332e2d828bce56 | ffbfa3316a8ba24d056e871e06f7452f20417fa5 | /git-toy-compiler/main.cpp | d95643fe87c8deaeb46fac336b8e9c28d19d2f28 | [] | no_license | metabolean5/toy_compiler | 76bf245a55c0a961fcdaab6d3a16329a620134e0 | c89e1fe7be75f6a7461fec1a5d7dc2a49bae3e54 | refs/heads/master | 2020-04-29T14:16:31.955275 | 2019-03-19T21:42:49 | 2019-03-19T21:42:49 | 176,191,481 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,029 | cpp | main.cpp | #include <stdio.h>
#include <streambuf>
#include <algorithm>
#include <string>
#include <fstream>
#include <iostream>
#include "lexer.h"
#include "lexer.cpp"
#include "parser.h"
#include "parser.cpp"
#include "token.h"
#include "visitor.h"
#include "visitor.cpp"
using namespace std;
int main()
{
ifstream t("//home/meta1/Dev/git/compiler/toy_compiler/progSamples/sampleSem");
if(!t){
cout<< "Cannot open input file!" << endl;
return 1;
}
//LEXICAL ANALYSIS
Lexer lexer(t);
lexer.run_Lexer();
//lexer.displayTokenList();
vector<Token> wordList = lexer.returnWords();
//SYNTAX ANALYSIS
Parser parser(wordList);
bool success = parser.run();
Node * ast = parser.getASTroot();
parser.traverse(ast);
if (success){cout << "\nsuccessfuly parsed\n";}
//SEMANTIC ANALYSIS
Visitor * vis = new Visitor();
cout << "\n\n1ST PASS\n\n";
vis->traverse(ast);
vis->printSymbolTables();
vis->printErrors();
cout << "\n\n2ND PASS\n\n";
vis->traverse2(ast);
vis->printErrors();
return 0;
}
|
c867b6a6c9418ef0ce0401cbe4522c67c5eb9c2c | 7fa042fd796262090d4e8c10e1dd0616aee4461b | /301-400/387_FirstUniqueCharacterInAString/solution2.cpp | 9f224019f2f919ef0f5cc53a6f380b71eab9bf2a | [] | no_license | luowanqian/LeetCode | 81c4e2afb6e74d3bb8112faa7347c2bc8d42911c | 76896b644d6d9ccb9bbdb474331e23ecdc4a3e60 | refs/heads/master | 2023-07-07T02:38:15.977746 | 2023-07-06T14:46:56 | 2023-07-06T14:46:56 | 126,608,748 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 681 | cpp | solution2.cpp | #include <iostream>
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
int firstUniqChar(string s) {
int res = s.size();
vector<int> idxes(26, -1), counts(26, 0);
for (int i=0; i<s.size(); i++) {
int num = s[i] - 'a';
counts[num]++;
idxes[num] = i;
}
for (int i=0; i<26; i++) {
if (counts[i] == 1) {
res = idxes[i] < res ? idxes[i] : res;
}
}
return res == s.size() ? -1 : res;
}
};
int main()
{
string s = "loveleetcode";
Solution solu;
cout << solu.firstUniqChar(s) << endl;
return 0;
} |
b5ed36433fbed965dd435621a6ed4aa0203f1b7f | 2d98dfa782d988405f7374604380806e618295ff | /SKvideo.h | 824a1df9fa0ce5c67c07b50ab29f46d37a5e1f6a | [] | no_license | mlashcorp/skaut-backend | 3335c5071218038fae3123a3e8d09b3f7ce92d96 | ec8ef2b5a56887a52337e7d7d397d73a023d0cf0 | refs/heads/master | 2020-05-27T16:38:08.485989 | 2014-06-22T14:01:31 | 2014-06-22T14:01:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 807 | h | SKvideo.h | /*
* File: video-tools.h
* Author: cortereal
*
* Created on July 28, 2013, 11:48 AM
*/
#ifndef VIDEO_TOOLS_H
#define VIDEO_TOOLS_H
#include "opencv2/highgui/highgui.hpp"
#include <queue>
//These define the pre and after alarm event buffer sizes (4.5 seconds each at 30FPS)
#define VIDEO_BUFFER_SIZE 125
#define VIDEO_FORWARD_BUFFER_SIZE 125
class SKvideo {
public:
SKvideo();
SKvideo(const SKvideo& orig);
virtual ~SKvideo();
int start_video_feed(std::string arg);
private:
long process_frame(cv::Mat &frame);
void detect_faces(cv::Mat &frame);
int video_loop();
int process_alarm_event(long alarm_metric,std::queue<cv::Mat> buffer);
void alarm_state_update(long alarm_metric);
int encode_video(std::queue<cv::Mat> buffer);
};
#endif /* VIDEO_TOOLS_H */
|
91690389d5ac8c02a741b835adb70ee0bcb57aa4 | 0377a14136dd2ef226b96b0fb55d5b30cf943135 | /Cryptonite/multithreading.cpp | 85ed2693c190c1f9fc7f22bdc2eb4624fbbb5c18 | [] | no_license | FakeEmperor/Cryptonite | d406818a6abe446d0d08d48b0358d3240a7151bf | e1217ad81b3e16b5e9277fa129804c5274979aff | refs/heads/master | 2021-01-13T02:37:18.022905 | 2014-05-30T00:24:39 | 2014-05-30T00:24:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 19,704 | cpp | multithreading.cpp | #include "multithreading.h"
/*********** EVENTINFO Class (info for event class) ***************/
Multithreading::EventInfo::EventInfo():
type(EV_NONE), code(0), data(NULL), handle((HANDLE)CreateEvent(NULL, FALSE, TRUE, NULL)), mutex((HANDLE)CreateMutex(NULL, FALSE, NULL))
{
};
Multithreading::EventInfo::EventInfo(const EventType type, const long long int code, const std::string &str,
void* data, const HANDLE handle, const HANDLE mutex)
:type(type), code(code), str(str), data(data), handle(handle), mutex(mutex)
{
};
Multithreading::EventInfo::~EventInfo(){
if (this->handle) CloseHandle(this->handle);
if (this->mutex) CloseHandle(this->mutex);
};
/********** EVENT Class ***********/
Multithreading::Event::Event():info(new EventInfo()){
};
Multithreading::Event::Event(Multithreading::EventType type, long long int code,const std::string &str, void* data):
info(new EventInfo(type, code, str, data, (HANDLE)CreateEvent(NULL, FALSE, TRUE, NULL), (HANDLE)CreateMutex(NULL, FALSE, NULL))){
};
Multithreading::Event::Event(const Multithreading::Event &e):info(e.info){
};
#ifdef __HAS_C11
Multithreading::Event::Event(const Multithreading::Event&& e):info(e.info){
e.info->handle = NULL;
e.info->mutex = NULL;
}
#endif
Multithreading::Event& Multithreading::Event::operator = (const Multithreading::Event &e){
this->info = e.info;
return *this;
}
Multithreading::EventType Multithreading::Event::getType()const{
DWORD r = WaitForSingleObject(this->info->mutex, Multithreading::ThreadInfo::readMaxDelay);
if (r == WAIT_OBJECT_0 || r == WAIT_ABANDONED){
Multithreading::EventType res = this->info->type;
ReleaseMutex(this->info->mutex);
return res;
}
else {
ReleaseMutex(this->info->mutex);
return Multithreading::EV_NONE;
}
}
long long int Multithreading::Event::getCode()const{
DWORD r = WaitForSingleObject(this->info->mutex, Multithreading::ThreadInfo::readMaxDelay);
if (r == WAIT_OBJECT_0 || r == WAIT_ABANDONED){
DWORD res = this->info->code;
ReleaseMutex(this->info->mutex);
return res;
}
else {
ReleaseMutex(this->info->mutex);
return Multithreading::EV_NONE;
}
}
std::string Multithreading::Event::getStr()const{
DWORD r = WaitForSingleObject(this->info->mutex, Multithreading::ThreadInfo::readMaxDelay);
if (r == WAIT_OBJECT_0 || r == WAIT_ABANDONED){
std::string res = this->info->str;
ReleaseMutex(this->info->mutex);
return res;
}
else {
ReleaseMutex(this->info->mutex);
return "";
}
}
void* Multithreading::Event::getData()const{
DWORD r = WaitForSingleObject(this->info->mutex, Multithreading::ThreadInfo::readMaxDelay);
if (r == WAIT_OBJECT_0 || r == WAIT_ABANDONED){
void* res = this->info->data;
ReleaseMutex(this->info->mutex);
return res;
}
else {
ReleaseMutex(this->info->mutex);
return NULL;
}
}
const HANDLE Multithreading::Event::getHandle()const{
DWORD r = WaitForSingleObject(this->info->mutex, Multithreading::ThreadInfo::readMaxDelay);
if (r == WAIT_OBJECT_0 || r == WAIT_ABANDONED){
void* res = this->info->handle;
ReleaseMutex(this->info->mutex);
return res;
}
else {
ReleaseMutex(this->info->mutex);
return NULL;
}
}
int Multithreading::Event::setData(void* data){
DWORD r = WaitForSingleObject(this->info->mutex, Multithreading::ThreadInfo::writeMaxDelay);
if (r == WAIT_OBJECT_0 || r == WAIT_ABANDONED){
this->info->data = data;
ReleaseMutex(this->info->mutex);
return 0;
}
else {
ReleaseMutex(this->info->mutex);
return 1;
}
}
int Multithreading::Event::set(int setMask, Multithreading::EventType type, long long int code, std::string event_string, void* data){
DWORD r = WaitForSingleObject(this->info->mutex, Multithreading::ThreadInfo::writeMaxDelay);
if (r == WAIT_OBJECT_0 || r == WAIT_ABANDONED){
if (setMask & 1) this->info->type = type;
if (setMask & 2) this->info->code = code;
if (setMask & 4) this->info->str = event_string;
if (setMask & 8) this->info->data = data;
ReleaseMutex(this->info->mutex);
return 0;
}
else{
ReleaseMutex(this->info->mutex);
return setMask;
}
};
int Multithreading::Event::set(int setMask, const Multithreading::Event &e){
DWORD r = WaitForSingleObject(this->info->mutex, Multithreading::ThreadInfo::writeMaxDelay);
if (r == WAIT_OBJECT_0 || r == WAIT_ABANDONED){
if (setMask & 1) this->info->type = e.info->type;
if (setMask & 2) this->info->code = e.info->code;
if (setMask & 4) this->info->str = e.info->str;
if (setMask & 8) this->info->data = e.info->data;
ReleaseMutex(this->info->mutex);
return 0;
}
else{
ReleaseMutex(this->info->mutex);
return setMask;
}
};
int Multithreading::Event::triggerEvent(){
DWORD waitRes = WaitForSingleObject(this->info->mutex, Multithreading::ThreadInfo::readMaxDelay);
if (waitRes == WAIT_OBJECT_0 || waitRes == WAIT_ABANDONED){
int res = (this->info->mutex) ? (SetEvent(this->info->handle) ? 0 : 1) : 1;
ReleaseMutex(this->info->mutex);
return res;
}
else {
ReleaseMutex(this->info->handle);
return 1;
}
};
int Multithreading::Event::untriggerEvent(){
if (this->info->handle)
return ResetEvent(this->info->handle) ? 0 : 1;
else
return 1;
};
Multithreading::Event::~Event(){
}
/*********** THREADINFO Class (info for event class) ***************/
Multithreading::ThreadInfo::ThreadInfo() :
f(NULL), data(NULL), t_id(0), thread(NULL), options(0), status(Multithreading::TS_EMPTY),st_ev( (HANDLE)CreateEvent(NULL, 1, 0, NULL)),
stack_size(0),res_mutex((HANDLE)CreateMutex(NULL, 0, NULL)),recent(EV_NONE), event_locked(false)
{
};
Multithreading::ThreadInfo::ThreadInfo(ThreadFunction f, const HANDLE thread, void* data, const size_t t_id,
const size_t options, const size_t stack_size, const HANDLE res_mutex,
const ThreadStatus status, HANDLE st_ev, const Event &recent,
const bool event_locked, const int th_errno):
f(f), data(data), t_id(t_id), thread(thread), options(options),
status(status), st_ev(st_ev),
stack_size(stack_size), res_mutex(res_mutex),
recent(recent), event_locked(event_locked)
{
}
Multithreading::ThreadInfo::~ThreadInfo(){
if (this->status != TS_NONE){
if(this->st_ev)
CloseHandle(this->st_ev);
if (this->res_mutex)
ReleaseMutex(this->res_mutex);
if (this->res_mutex)
CloseHandle(this->res_mutex);
if (this->thread)
CloseHandle(this->thread);
}
};
/********** THREAD Class ***********/
unsigned int __stdcall Multithreading::defThreadFunction(void *arg){
Multithreading::Thread* th = (Multithreading::Thread*)arg;
//check if the thread already stopping
//Obtained temporary event variable
if (th->info->event_locked){
Multithreading::Event temp_e = th->getEvent();
if (temp_e.getType() == Multithreading::EV_SYSINFO && temp_e.getCode() == 1) {
th->setStatus(Multithreading::TS_FINISHED);
return Multithreading::TR_NOWORK;
}
}
th->setStatus(Multithreading::TS_WORKING);
ThreadResult res = th->info->f(th, th->info->data);
WaitForSingleObject(th->info->res_mutex, ThreadInfo::readMaxDelay);
th->setStatus(Multithreading::TS_FINISHED);
ReleaseMutex(th->info->res_mutex);
return (unsigned int)res;
};
int Multithreading::setJoin(Multithreading::Thread &what, const Multithreading::Thread &to) {
size_t opts = what.getOptions(), opts_t = to.getOptions();
if (opts_t == -1 || opts == -1)
return EFAULT;
else if ((opts | opts_t)&Multithreading::TO_DETACHED)
return EINVAL;
else if (&what == &to)
return ECANCELED;
what.pauseUntil(INFINITE, &to, Multithreading::TS_FINISHED);
return 0;
}
unsigned int __stdcall Multithreading::defPauseUntilFunction(void *arg){
return 0;
}
void Multithreading::Thread::setStatus(ThreadStatus ts){
DWORD r = WaitForSingleObject(this->info->res_mutex, ThreadInfo::readMaxDelay);
if (r == WAIT_ABANDONED || r == WAIT_OBJECT_0){
this->info->status = ts;
ReleaseMutex(this->info->res_mutex);
}
PulseEvent(this->info->st_ev);
};
void Multithreading::Thread::syncStatus(){
//Check if thread is a) not created, b) running, c) suspended, d) finished
const size_t wait_time = 5;
//First things first: wait for the thread some small time
DWORD res = WaitForSingleObject(this->info->thread, wait_time);
//a
if (this->info->t_id == 0 || this->info->thread == NULL || res == WAIT_FAILED) {
this->info->status = Multithreading::TS_EMPTY;
return;
}
//b
if (res == WAIT_TIMEOUT && !(this->info->status == Multithreading::TS_CREATED || this->info->status == Multithreading::TS_WORKING)) {
this->info->status = Multithreading::TS_CREATED;
}
//c
/** USING UNDOCUMENTED FEATURE **/
else if (res == WAIT_ABANDONED && this->info->status != TS_PAUSED) {
this->info->status = TS_PAUSED;
}
/*^^^^ NOW ALL IS DOCUMENTED ^^^^*/
//d
else if (res == WAIT_OBJECT_0 && this->info->status != TS_FINISHED){
this->info->status = TS_FINISHED;
}
}
void Multithreading::Thread::setLockEvent(bool lock_status){
this->info->event_locked = lock_status;
};
int Multithreading::Thread::sendEvent(const Event& e){
DWORD result;
if (!this->info->event_locked){
result = WaitForSingleObject(this->info->res_mutex, Multithreading::ThreadInfo::writeMaxDelay);
if (result == WAIT_ABANDONED || result == WAIT_OBJECT_0){
/*if (result == WAIT_ABANDONED)*/ //send debug info to thread management system
this->info->recent.set(0x0F, e);
this->info->recent.triggerEvent();
ReleaseMutex(this->info->res_mutex);
return 0;
}
else{
ReleaseMutex(this->info->res_mutex);
return result;
}
}
else return 1;
};
const Multithreading::Event& Multithreading::Thread::getEvent() const{
DWORD r = WaitForSingleObject(this->info->res_mutex, ThreadInfo::readMaxDelay);
if (r == WAIT_ABANDONED || r == WAIT_OBJECT_0){
auto &res = this->info->recent;
ReleaseMutex(this->info->res_mutex);
return res;
}
else{
ReleaseMutex(this->info->res_mutex);
//force return
return this->info->recent;
}
};
Multithreading::Thread::Thread(): info(new ThreadInfo()){
};
Multithreading::Thread::Thread(ThreadFunction f, void* data, bool autostart, size_t stack_size, size_t opts):
info(new ThreadInfo(f, NULL, data, 0, opts, stack_size, (HANDLE)CreateMutex(NULL, 0, NULL), TS_EMPTY,
(HANDLE)CreateEvent(NULL, 1, 0, NULL),*new Event(EV_NONE),false, 0 ))
{
this->info->thread = (HANDLE)_beginthreadex(NULL, stack_size, defThreadFunction,
(void*)this, autostart ? 0 : CREATE_SUSPENDED, &this->info->t_id);
if (!this->info->thread){
this->sendEvent(Event(Multithreading::EV_ERROR, errno, "Thread created unsuccessfully"));
this->setStatus(Multithreading::TS_ERROR);
}
else this->setStatus(Multithreading::TS_CREATED);
};
Multithreading::Thread::Thread(const Multithreading::Thread &thread):info(thread.info){
}
#ifdef __HAS_C11
Multithreading::Thread::Thread(Multithreading::Thread &&thread):info(thread.info) {
thread.info->status = TS_NONE;
}
#endif
Multithreading::Thread::~Thread(){
//send stop signal, kill if thread is not responding
//release all handles
if (this->info.use_count() <= 1){
if (this->getStatus() & (TS_CREATED | TS_WORKING | TS_PAUSED))
if (this->stop(ThreadInfo::closeMaxDelay))
this->kill();
}
};
int Multithreading::Thread::assign(ThreadFunction f, void* data, size_t stack_size){
size_t status = this->getStatus();
if (status & (Multithreading::TS_EMPTY | Multithreading::TS_FINISHED | Multithreading::TS_CREATED )){
//Well, if status is TS_CREATED, then we have to stop thread (or kill it), remove handle, and reset all variables
if (status & (Multithreading::TS_FINISHED | Multithreading::TS_CREATED)){
if (status == Multithreading::TS_CREATED)
if (this->stop())
this->kill();
}
//Just assign all values and create thread handle - easy
HANDLE saved_mutex = this->info->res_mutex, saved_st_ev = this->info->st_ev;
this->info->res_mutex = 0;
this->info->st_ev = 0;
this->info = *new ThreadInfo(f, NULL, data, 0, this->info->options, stack_size,
saved_mutex, TS_NONE, saved_st_ev, *new Event(EV_NONE), false, 0 );
this->info->thread = (HANDLE)_beginthreadex(NULL, stack_size, defThreadFunction, (void*)this, CREATE_SUSPENDED, &this->info->t_id);
if (!this->info->thread){
this->sendEvent(Event(Multithreading::EV_ERROR, errno, "Thread created unsuccessfully"));
this->setStatus(Multithreading::TS_ERROR);
}
else
this->setStatus(Multithreading::TS_CREATED);
return 0;
}
else
return 1;
};
int Multithreading::Thread::start(){
switch (this->info->status){
case Multithreading::TS_CREATED:
{
ResumeThread(this->info->thread);
this->setStatus(TS_WORKING);
return 0;
}
break;
case Multithreading::TS_FINISHED:
{
CloseHandle(this->info->thread);
setLockEvent(false);
this->info->thread = (HANDLE)_beginthreadex(NULL, info->stack_size, defThreadFunction, (void*)this, 0, &this->info->t_id);
if (!this->info->thread){
this->sendEvent(*new Event(Multithreading::EV_ERROR, errno, "Thread created unsuccessfully"));
this->setStatus(TS_ERROR);
}
return 0;
}
break;
default:
return this->info->status;
}
};
int Multithreading::Thread::stop(size_t wait){
if (this->info->status == Multithreading::TS_WORKING || this->info->status == Multithreading::TS_CREATED){
sendEvent(Event(Multithreading::EV_SYSINFO, 1));
setLockEvent(true);
// if (this->info->status == Multithreading::TS_CREATED) ResumeThread(this->info->thread);
return WaitForSingleObject(this->info->thread, wait);
}
else
return this->info->status;
};
int Multithreading::Thread::pause(){
if (this->info->status == Multithreading::TS_WORKING){
SuspendThread(this->info->thread);
this->setStatus(TS_PAUSED);
return 0;
}
else return this->info->status;
};
int Multithreading::Thread::kill(){
if(this->info->thread)
TerminateThread(this->info->thread, Multithreading::TR_HALTED);
this->setStatus(Multithreading::TS_CREATED);
return 0;
};
int Multithreading::Thread::pauseUntil(DWORD miliseconds, const Multithreading::Thread *thread, Multithreading::ThreadStatus status){
//1st option - only timeout
//2nd option - timeout & status
if (miliseconds){
void* data = (void*) new char[sizeof(miliseconds)+2 * sizeof(thread)+sizeof(status)];
int addr = (int)this;
std::memcpy(data, &miliseconds, sizeof(miliseconds));
std::memcpy((char*)data + sizeof(miliseconds), &thread, sizeof(thread));
std::memcpy((char*)data + (sizeof(miliseconds)+sizeof(thread)), &addr, sizeof(thread));
std::memcpy((char*)data + (sizeof(miliseconds)+2 * sizeof(thread)), &status, sizeof(status));
HANDLE waiter = (HANDLE)_beginthreadex(NULL, 1024, Multithreading::defPauseUntilFunction, data, CREATE_SUSPENDED, NULL);
if (!waiter)
return 1;
else
ResumeThread(waiter);
this->pause();
}
else if (thread &&status != TS_NONE){
this->pause();
Multithreading::ThreadStatus res = thread->getStatus();
if (res != TS_NONE&&res != status)
return 2;
}
return 0;
}
int Multithreading::Thread::join()const{
//wait until thread closes
DWORD res = WaitForSingleObject(this->info->thread, INFINITE);
return (res == WAIT_OBJECT_0) ? 0 : 1;
}
int Multithreading::Thread::detach(){
this->info->options |= Multithreading::ThreadOption::TO_DETACHED;
this->info->thread = NULL;
//remove thread handle in all references if it is not singleton instance
return 0;
};
Multithreading::Event Multithreading::Thread::waitForEvent(DWORD milliseconds) const{
DWORD res;
const int epsilon = 100;
Multithreading::ThreadStatus st;
__time64_t begin = _time64(NULL), end; //this won't work in the year 2038 :D. No, seriously guys :)
do{
res = WaitForSingleObject(this->info->recent.getHandle(), milliseconds);
end = _time64(NULL);
if ((res == WAIT_ABANDONED || res == WAIT_OBJECT_0)){
if (this->info->status == TS_NONE || ((st = this->getStatus()) != TS_NONE && st == this->info->status))
return this->getEvent();
}
else if (res != WAIT_TIMEOUT)
return Event(EV_NONE, 1);
} while (abs(_difftime64(begin, end) * 1000 - milliseconds) < epsilon);
return Event(EV_NONE, 2);
}
int Multithreading::Thread::waitForStatus(DWORD milliseconds, Multithreading::ThreadStatus status)const{
DWORD res;
Multithreading::ThreadStatus st;
unsigned long long begin = GetTickCount(), end; //This is very dangerous solution for time count
do{
res = WaitForSingleObject(this->info->st_ev, milliseconds);
st = status;
ReleaseMutex(this->info->st_ev);
end = GetTickCount();
//check and fix time
if (end < begin) {
end = begin + end;
}
if ((res == WAIT_ABANDONED || res == WAIT_OBJECT_0)){
if (st == TS_NONE || ((st = this->getStatus()) != TS_NONE && st & status))
return 0;
}
else if (res != WAIT_TIMEOUT)
return 1;
} while ((end - begin)<milliseconds);
return 2;
}
Multithreading::Thread& Multithreading::Thread::operator = (Multithreading::Thread &thread){
if (this->getStatus() & (TS_CREATED | TS_WORKING | TS_PAUSED))
if (this->stop(ThreadInfo::closeMaxDelay))
this->kill();
this->info = thread.info;
return *this;
}
Multithreading::Thread& Multithreading::Thread::operator >> (const Multithreading::Thread &thread){
size_t opts = this->getOptions(), opts_t = thread.getOptions();
if (opts == -1 || opts == -1)
throw EFAULT;
else if ((opts | opts_t)&Multithreading::TO_DETACHED)
throw EINVAL;
else if (this == &thread)
throw ECANCELED;
//wait until finished
this->waitForStatus(INFINITE, Multithreading::TS_FINISHED);
return *this;
}
Multithreading::Thread& Multithreading::Thread::operator << (const Multithreading::Thread &thread) {
size_t opts = this->getOptions(), opts_t = thread.getOptions();
if (opts == -1 || opts == -1)
throw EFAULT;
else if ((opts | opts_t)&Multithreading::TO_DETACHED)
throw EINVAL;
else if (this == &thread)
throw ECANCELED;
thread.waitForStatus(INFINITE, Multithreading::TS_FINISHED);
return *this;
}
/* DELETED: setOption() is redundant
size_t Multithreading::Thread::setOptions(size_t options){
DWORD r = WaitForSingleObject(this->res_mutex, this->readMaxDelay);
size_t old;
if (r == WAIT_ABANDONED || r == WAIT_OBJECT_0){
//if WAIT_ABANDONED, signal to thread management system
old = this->options;
this->options = options;
ReleaseMutex(this->res_mutex);
return old;
}
else return -1;
}
*/
size_t Multithreading::Thread::getOptions()const{
DWORD r = WaitForSingleObject(this->info->res_mutex, ThreadInfo::readMaxDelay);
if (r == WAIT_ABANDONED || r == WAIT_OBJECT_0){
//if WAIT_ABANDONED, signal to thread management system
auto res = this->info->options;
ReleaseMutex(this->info->res_mutex);
return res;
}
else return -1;
};
size_t Multithreading::Thread::getThreadId() const {
DWORD r = WaitForSingleObject(this->info->res_mutex, ThreadInfo::readMaxDelay);
if (r == WAIT_ABANDONED || r == WAIT_OBJECT_0){
//if WAIT_ABANDONED, signal to thread management system
auto res = this->info->t_id;
ReleaseMutex(this->info->res_mutex);
return res;
}
else return -1;
}
Multithreading::ThreadStatus Multithreading::Thread::getStatus()const{
DWORD r = WaitForSingleObject(this->info->res_mutex, ThreadInfo::readMaxDelay);
if (r == WAIT_ABANDONED || r == WAIT_OBJECT_0){
//if WAIT_ABANDONED, signal to thread management system
auto res = this->info->status;
ReleaseMutex(this->info->res_mutex);
return res;
}
else return Multithreading::TS_NONE;
};
int Multithreading::Thread::getLastError()const {
int res = 0;
DWORD r = WaitForSingleObject(this->info->res_mutex, ThreadInfo::readMaxDelay);
if (r == WAIT_ABANDONED || r == WAIT_OBJECT_0){
//if WAIT_ABANDONED, signal to thread management system
auto res = this->info->th_errno;
ReleaseMutex(this->info->res_mutex);
return res;
}
return -1;
};
|
c88736f1d69ffd85caaae9039e195ed214ca06ff | 2665a15e2df499310831b1e9b4546a75a562661e | /GApplication.cpp | 1e8a05e89929cc9f12ce99857fe0296c3352e33a | [] | no_license | RaymonSHan/GLdb | 3c6c92c47932f29c183fd6acd927ab73f5d4a4f4 | 9e4bab88a98f0b9269366b661ada9793cb00ab4a | refs/heads/master | 2020-05-19T19:44:07.613950 | 2015-04-30T07:23:31 | 2015-04-30T07:23:31 | 29,387,223 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,068 | cpp | GApplication.cpp | /*
* GLdb APPLICATION implement file
*
* GLdb is a Multi-thread customed Key-Value No-SQL memory database.
* GLdb atomic insert voucher & update balance, provide interface for ERP.
* GLdb have its own Async IO system, support Windows & Linux by IOCP & epoll.
* GLdb request large memory, so only support 64bit system.
*
* Copyright (c) 2015 Raymon SHan <quickhorse77 at gmail dot com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modifica-
* tion, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MER-
* CHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPE-
* CIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTH-
* ERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "GMemory.hpp"
#include "GApplication.hpp"
#include "GEncapsulate.hpp"
/*
* pPeer relation
*
* Client Context and Server Context are peer. every context may point to NULL,
* self, its peer. so there are nine conditions, as following
*
* 1. cli->pPeer = NULL; ser->pPeer = NULL;
* 2. cli->pPeer = NULL; ser->pPeer = ser;
* 3. cli->pPeer = NULL; ser->pPeer = cli;
* 4. cli->pPeer = cli; ser->pPeer = NULL;
* 5. cli->pPeer = cli; ser->pPeer = ser;
* 6. cli->pPeer = cli; ser->pPeer = cli;
* 7. cli->pPeer = ser; ser->pPeer = NULL;
* 8. cli->pPeer = ser; ser->pPeer = ser;
* 9. cli->pPeer = ser; ser->pPeer = cli;
*/
RESULT GNoneApplication::OnAccept(
PCONT pcont, PBUFF &pbuff, UINT size)
{
(void) size;
__TRY
PCONT clicont, sercont = 0;
PBUFF newbuff = 0;
HANDLE iocphandle;
#ifdef __PROCESS_APPLICATION
DF(NoneOnAccept);DN;
#endif // __PROCESS_APPLICATION
__DOe(pcont == 0,
GL_IOCP_INPUT_ZERO);
__DOe(pbuff == 0,
GL_IOCP_INPUT_ZERO);
__DOe(pcont->pPeer == NULL,
GL_IOCP_INPUT_ZERO);
if (IS_NETWORK(pcont)) {
__DO (GetBufferSmall(newbuff));
__DO (NoneProFunc(fPostAccept)
(pcont, newbuff, SIZE_BUFF_S, OP_ACCEPT));
}
pbuff->nOper = OP_CLIENT_READ;
clicont = (PCONT)pbuff->oLapped.accSocket;
__DOe(clicont == 0,
GL_IOCP_INPUT_ZERO);
pbuff->oLapped.accSocket = 0;
iocphandle = CreateIoCompletionPort(
clicont, pcont->pApplication->handleIOCP, (ULONG_PTR)clicont, 0);
__DO (iocphandle == 0);
/*
* pcont->pPeer->pPeer != NULL means pcont == pcont->pPeer in normal
* or duplicate all info from CONT, which created by CreateRemote()
*/
if (pcont->pPeer->pPeer != NULL) {
clicont->pPeer = clicont;
__DO (NoneProFunc(fPostReceive)
(clicont, pbuff, SIZE_BUFF_S, OP_CLIENT_READ, OPSIDE_CLIENT));
} else {
__DO (GetDupContext(sercont, pcont->pPeer, true));
clicont->pPeer = sercont;
sercont->pPeer = clicont;
__DO (NoneProFunc(fPostConnect)
(sercont, pbuff, 0, OP_CONNECT));
}
__CATCH_BEGIN
if (newbuff) FreeBuffer(newbuff);
if (sercont) FreeContext(sercont);
__CATCH_END
};
RESULT GNoneApplication::OnConnect(
PCONT pcont, PBUFF &pbuff, UINT size)
{
(void) size;
__TRY
PBUFF newbuff = 0;
#ifdef __PROCESS_APPLICATION
DF(NoneOnConnect);DN;
#endif // __PROCESS_APPLICATION
__DO (NoneProFunc(fPostReceive)
(pcont->pPeer, pbuff, SIZE_BUFF_S, OP_CLIENT_READ, OPSIDE_CLIENT));
if (IS_DUPLEX(pcont)) {
__DO (GetBufferSmall(newbuff));
__DO (NoneProFunc(fPostReceive)
(pcont, newbuff, SIZE_BUFF_S, OP_SERVER_READ, OPSIDE_SERVER));
}
__CATCH_BEGIN
if (newbuff) FreeBuffer(newbuff);
__CATCH_END
};
RESULT GNoneApplication::OnClientRead(
PCONT pcont, PBUFF &pbuff, UINT size)
{
__TRY
__DO (AppFunc(pcont, fOnClientRead)
(pcont, pbuff, size));
__CATCH
};
RESULT GNoneApplication::OnClientWrite(
PCONT pcont, PBUFF &pbuff, UINT size)
{
(void) size;
__TRY
__DO (NoneProFunc(fPostReceive)
(pcont->pPeer, pbuff, SIZE_BUFF_S, OP_SERVER_READ, OPSIDE_SERVER));
__CATCH
};
RESULT GNoneApplication::OnServerRead(
PCONT pcont, PBUFF &pbuff, UINT size)
{
__TRY
__DO (AppFunc(pcont, fOnServerRead)
(pcont, pbuff, size));
__CATCH
};
RESULT GNoneApplication::OnServerWrite(
PCONT pcont, PBUFF &pbuff, UINT size)
{
(void) size;
__TRY
__DO (NoneProFunc(fPostReceive)
(pcont->pPeer, pbuff, SIZE_BUFF_S, OP_CLIENT_READ, OPSIDE_CLIENT));
__CATCH
};
RESULT GNoneApplication::OnClose(
PCONT pcont, PBUFF &pbuff, UINT size)
{
(void) size;
(void) pbuff;
__TRY
static LOCK inClose = NOT_IN_PROCESS;
static PBUFF isNULL = NULL;
PCONT peer;
#ifdef __PROCESS_APPLICATION
DF(NoneOnClose);DN;
#endif // __PROCESS_APPLICATION
if (pbuff) {
FreeBuffer(pbuff);
}
if (!pcont) __BREAK_OK;
__LOCK(inClose);
peer = pcont->pPeer;
if (peer && peer->pPeer == pcont) {
peer->pPeer = NULL; // change this line, old is peer->pPeer = peer;
pcont->pPeer = NULL;
__FREE(inClose);
OnClose(peer, isNULL, 0);
} else {
__FREE(inClose);
}
FreeProtocolContext(pcont);
__CATCH
};
RESULT GNoneApplication::OnPassby(
PCONT pcont, PBUFF &pbuff, UINT size)
{ return 0; };
RESULT GMultiApplication::AddPeerGroup(
PCONT pcont, PSTRING keyword, PSTRING host)
{
__TRY
PCONT sercont = ZERO;
UINT peernumber;
PGROUP nowpeer;
ADDR addr;
__DO (PeerNumber == MAX_PEER_GROUP);
peernumber = LockInc(PeerNumber);
nowpeer = &ServerPeer[peernumber];
nowpeer->peerKeyword = *keyword;
nowpeer->peerHost = *host;
addr = host->strStart;
__DO (GetDupContext(sercont, pcont));
__DO (ProFunc(sercont, fCreateRemote)(sercont, addr, host->strLen()));
nowpeer->peerCont = sercont;
__CATCH_BEGIN
if (sercont) FreeContext(sercont);
__CATCH_END
};
RESULT GMultiApplication::PreparePeer(
PCONT &pcont, PSTRING keyword)
{
__TRY
UINT i;
for (i=0; i<PeerNumber; i++) {
if (ServerPeer[i].peerKeyword == *keyword) {
__DO(GetDupContext(pcont, ServerPeer[i].peerCont));
__BREAK_OK;
}
}
pcont = 0;
__BREAK;
__CATCH
};
RESULT GEchoApplication::OnClientRead(
PCONT pcont, PBUFF &pbuff, UINT size)
{
__TRY
#ifdef __PROCESS_APPLICATION
DF(EchoOnClientRead);DN;
#endif // __PROCESS_APPLICATION
__DO (NoneProFunc(fPostSend)
(pcont, pbuff, size, OP_SERVER_WRITE, OPSIDE_CLIENT));
__CATCH
};
RESULT GForwardApplication::OnClientRead(
PCONT pcont, PBUFF &pbuff, UINT size)
{
__TRY
#ifdef __PROCESS_APPLICATION
DF(ForwardOnClientRead);DN;
#endif // __PROCESS_APPLICATION
__DO (NoneProFunc(fPostSend)
(pcont->pPeer, pbuff, size, OP_SERVER_WRITE, OPSIDE_SERVER));
__CATCH
};
RESULT GForwardApplication::OnServerRead(
PCONT pcont, PBUFF &pbuff, UINT size)
{
__TRY
#ifdef __PROCESS_APPLICATION
DF(ForwardOnServerRead);DN;
#endif // __PROCESS_APPLICATION
__DO (NoneProFunc(fPostSend)
(pcont->pPeer, pbuff, size, OP_CLIENT_WRITE, OPSIDE_CLIENT));
__CATCH
};
|
e54b01f5cd5b12bbe8ce47d3d6271dd43afd8232 | 790070309a3910e861ee2fd0d14e78edfe698ed6 | /board.h | 1e5862d64e38c4e91e343a8c5e5edef38c07c313 | [] | no_license | Jooeeee/Go-game | 301c2609a8600ccdf8bbba3c1ad6013a017efe04 | f648166faa2a7f5c69e7cae34c0b7ec40154ab08 | refs/heads/master | 2020-12-07T15:36:38.467961 | 2017-06-27T11:41:56 | 2017-06-27T11:41:56 | 95,550,854 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 139 | h | board.h | #pragma once
#include <QLabel>
class board : public QLabel//
{
Q_OBJECT
public:
board(QWidget *parent=0);
//~board();
};
|
7eb4ac324d4a65c819ce501c1957e14afb1b4a79 | 96fefafdfbb413a56e0a2444fcc1a7056afef757 | /MQ2Map/MQ2Map.h | 31172359879e01fe1cd562c0591cce0e60e70438 | [] | no_license | kevrgithub/peqtgc-mq2-sod | ffc105aedbfef16060769bb7a6fa6609d775b1fa | d0b7ec010bc64c3f0ac9dc32129a62277b8d42c0 | refs/heads/master | 2021-01-18T18:57:16.627137 | 2011-03-06T13:05:41 | 2011-03-06T13:05:41 | 32,849,784 | 1 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 3,301 | h | MQ2Map.h | #include <map>
using namespace std;
#ifdef ISXEQ
#include "ISXEQMap.h"
#endif
#define MAPFILTER_All 0
#define MAPFILTER_PC 1
#define MAPFILTER_PCConColor 2
#define MAPFILTER_Group 3
#define MAPFILTER_Mount 4
#define MAPFILTER_NPC 5
#define MAPFILTER_NPCConColor 6
#define MAPFILTER_Untargetable 7
#define MAPFILTER_Pet 8
#define MAPFILTER_Corpse 9
#define MAPFILTER_Chest 10
#define MAPFILTER_Trigger 11
#define MAPFILTER_Trap 12
#define MAPFILTER_Timer 13
#define MAPFILTER_Ground 14
#define MAPFILTER_Target 15
#define MAPFILTER_TargetLine 16
#define MAPFILTER_TargetRadius 17
#define MAPFILTER_TargetMelee 18
#define MAPFILTER_Vector 19
#define MAPFILTER_Custom 20
#define MAPFILTER_CastRadius 21
#define MAPFILTER_NormalLabels 22
#define MAPFILTER_ContextMenu 23
#define MAPFILTER_SpellRadius 24
#define MAPFILTER_Aura 25
#define MAPFILTER_Object 26
#define MAPFILTER_Banner 27
#define MAPFILTER_Campfire 28
#define MAPFILTER_PCCorpse 29
#define MAPFILTER_Mercenary 30
#define MAPFILTER_NUMBER 31
#define MAPFILTER_Invalid (-1)
// normal labels
typedef struct _MAPFILTER {
PCHAR szName;
//DWORD Index;
DWORD Default;
DWORD DefaultColor;
BOOL bIsToggle;
DWORD RequiresOption;
BOOL RegenerateOnChange;
PCHAR szHelpString;
DWORD Enabled;
DWORD Color;
} MAPFILTER, *PMAPFILTER;
extern unsigned long bmMapRefresh;
extern DWORD HighlightColor;
extern CHAR MapNameString[MAX_STRING];
extern CHAR MapTargetNameString[MAX_STRING];
extern SEARCHSPAWN MapFilterCustom;
extern MAPFILTER MapFilterOptions[];
extern CHAR MapSpecialClickString[16][MAX_STRING];
/* COMMANDS */
VOID MapFilters(PSPAWNINFO pChar, PCHAR szLine);
VOID MapFilterSetting(PSPAWNINFO pChar, DWORD nMapFilter, PCHAR szValue=NULL);
VOID MapHighlightCmd(PSPAWNINFO pChar, PCHAR szLine);
VOID MapHideCmd(PSPAWNINFO pChar, PCHAR szLine);
VOID MapShowCmd(PSPAWNINFO pChar, PCHAR szLine);
VOID MapNames(PSPAWNINFO pChar, PCHAR szLine);
VOID MapClickCommand(PSPAWNINFO pChar, PCHAR szLine);
/* API */
VOID MapInit();
VOID MapClear();
VOID MapGenerate();
DWORD MapHighlight(SEARCHSPAWN *pSearch);
DWORD MapHide(SEARCHSPAWN &Search);
DWORD MapShow(SEARCHSPAWN &Search);
VOID MapUpdate();
VOID MapAttach();
VOID MapDetach();
VOID MapSelectTarget();
#ifndef ISXEQ
BOOL dataMapSpawn(PCHAR szIndex, MQ2TYPEVAR &Ret);
#else
bool dataMapSpawn(int argc, char *argv[], LSTYPEVAR &Ret);
#endif
struct _MAPSPAWN* AddSpawn(PSPAWNINFO pNewSpawn,BOOL ExplicitAllow=false);
bool RemoveSpawn(PSPAWNINFO pSpawn);
void AddGroundItem(PGROUNDITEM pGroundItem);
void RemoveGroundItem(PGROUNDITEM pGroundItem);
static inline BOOL IsOptionEnabled(DWORD Option)
{
if (Option==MAPFILTER_Invalid)
return true;
return (MapFilterOptions[Option].Enabled && IsOptionEnabled(MapFilterOptions[Option].RequiresOption));
}
static inline BOOL RequirementsMet(DWORD Option)
{
if (Option==MAPFILTER_Invalid)
return true;
return (IsOptionEnabled(MapFilterOptions[Option].RequiresOption));
}
|
fa41e842390a5c1fd2aa2b6f6ddd62f5dc6857eb | 4da2af52dc3ca9673847792d1e6b40027077e638 | /zerojudge/b870.cpp | 32494d2ff11ec1a4caaf9567404514c615aaf3b2 | [] | no_license | LJH-coding/code | 64519594d335ecf74e92f68c3ffd7539e7951041 | d45c516287f121d187be9819baff844053c7df88 | refs/heads/main | 2023-07-15T02:41:23.688977 | 2021-09-05T14:33:00 | 2021-09-05T14:33:00 | 364,233,120 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,160 | cpp | b870.cpp | #include<bits/stdc++.h>
using namespace std;
#define int long long
#define IOS ios::sync_with_stdio(0),cin.tie(0),cout.tie(0)
#define endl '\n'
#define pb push_back
const int N = 1e5+5;
int a[N] = {},n,k,vis[N] = {};
vector<int>point;
bool check(int m){
point.clear();
memset(vis,0,sizeof(vis));
int cnt = 0;
for(int i = 0;i<n;++i){
if(point.size()==0){
point.pb(a[i]+m);
cnt++;
}
if(abs(a[i]-point.back())>m){
point.pb(a[i]+m);
cnt++;
}
}
return cnt<=k;
}
signed main(){
IOS;
int t;
cin>>t;
while(t--){
cin>>n>>k;
if(n==k){
cout<<0<<endl;
continue;
}
for(int i = 0;i<n;++i){
cin>>a[i];
}
sort(a,a+n);
int l = 0,r = a[n-1],ans;
while(l<=r){
int m = (l+r)/2;
if(check(m)){
/*
cout<<m<<endl;
for(auto seg:point){
cout<<seg<<' ';
}
cout<<endl;
*/
ans = m;
r = m-1;
}
else{
l = m+1;
}
}
cout<<ans<<endl;
}
}
|
359e7828b76b270ad7fa12c88e4ac6e3f9c2e6dc | c563c2c9a2e4634edd8112a6dec8980f0e21d855 | /MiniServer/Include/Protocol.hpp | 778e17c507d5cbc0b079b08293a922438f7693c1 | [] | no_license | Markyparky56/MiniServer | 2f2997192d0561bb168231d70e7b242aded246cb | 62b13406995003cd4aa5be6bb20753440c6eeab6 | refs/heads/master | 2020-06-14T19:42:54.960117 | 2016-12-05T04:56:54 | 2016-12-05T04:56:54 | 75,353,237 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,111 | hpp | Protocol.hpp | #pragma once
#include <cstdint>
#include <ctime>
#include "Transform.hpp"
/*************************** Protocol Over TCP ***************************/
enum class TCPMessageType : uint8_t // Might as well keep these small since we don't need to have a million message types
{
IWantToConnectIPv4,
IWantToConnectIPv6, // This is not going to be used, but I'm including it to show off how clever I am.
YouAreConnected,
IAmDisconnecting,
ConnectTell,
DisconnectTell,
Snapshot,
Ping, // Only implement this if you have time
Pong // Response to a ping, workout roundtrip time
};
enum class DisconnectType : uint8_t
{
Standard // Could be expanded to include things like connection timeout or being kicked for too high a ping
};
#pragma pack(push, 1)
struct PlayerRecord
{
uint8_t id;
Transform transform;
};
#pragma pack(pop)
#pragma pack(push, 1)
struct TCPMessageIWantToConnectIPv4Data
{
TCPMessageIWantToConnectIPv4Data() {}
TCPMessageIWantToConnectIPv4Data(const uint8_t InId, const char InHost[], const char InService[])
{
id = InId;
memcpy(host, InHost, 16);
memcpy(service, InService, 5);
}
// Data to setup an endpoint for the udp messages
uint8_t id;
char host[16]; // Address
char service[5]; // Port
};
#pragma pack(pop)
#pragma pack(push, 1)
struct TCPMessageIWantToConnectIPv6Data
{
TCPMessageIWantToConnectIPv6Data() {}
TCPMessageIWantToConnectIPv6Data(const uint8_t InId, const char InHost[], const char InService[])
{
id = InId;
memcpy(host, InHost, 46);
memcpy(service, InService, 5);
}
// Data to setup an endpoint for the udp messages
uint8_t id;
char host[46]; // Address (ipv6 address can be looooong)
char service[5]; // Port
};
#pragma pack(pop)
#pragma pack(push, 1)
struct TCPMessageYouAreConnectedData
{
TCPMessageYouAreConnectedData() {}
TCPMessageYouAreConnectedData(uint8_t InId) : id(InId) {}
uint8_t id; // The id assigned to the newly connected client
};
#pragma pack(pop)
#pragma pack(push, 1)
struct TCPMessageIAmDisconnectingData
{
TCPMessageIAmDisconnectingData() {}
TCPMessageIAmDisconnectingData(uint8_t InId) : id(InId) {}
uint8_t id;
};
#pragma pack(pop)
#pragma pack(push, 1) // Pack as tightly as possible to reduce bandwidth
struct TCPMessageConnectTellData
{
TCPMessageConnectTellData() {}
TCPMessageConnectTellData(PlayerRecord &record) : newPlayer(record) {}
PlayerRecord newPlayer;
};
#pragma pack(pop)
#pragma pack(push, 1)
struct TCPMessageDisconnectTellData
{
TCPMessageDisconnectTellData() {}
TCPMessageDisconnectTellData(uint8_t InId, DisconnectType InType) : id(InId), disconnectType(InType) {}
uint8_t id;
DisconnectType disconnectType;
};
#pragma pack(pop)
#pragma pack(push, 1)
struct TCPMessageSnapshotData
{
TCPMessageSnapshotData() {}
TCPMessageSnapshotData(PlayerRecord InRecords[16])
{
memcpy(&records, &InRecords, 16);
}
PlayerRecord records[16]; // 16 should technically be the maximum number of users on the server
// A way to cut this down would be to only send deltas, but this'll work for now
};
#pragma pack(pop)
#pragma pack(push, 1)
struct TCPMessagePingPongData
{
TCPMessagePingPongData() {}
// Empty
};
#pragma pack(pop)
union TCPMessageData
{
TCPMessageData() {}
TCPMessageIWantToConnectIPv4Data ipv4ConnectData;
TCPMessageIWantToConnectIPv6Data ipv6ConnectData;
TCPMessageYouAreConnectedData youAreConnectedData;
TCPMessageIAmDisconnectingData iAmDisconnectingData;
TCPMessageConnectTellData connectTellData;
TCPMessageDisconnectTellData disconnectTellData;
TCPMessageSnapshotData snapshotData;
TCPMessagePingPongData pingPongData;
};
#pragma pack(push, 1)
struct TCPMessage
{
TCPMessageType type;
uint64_t unixTimestamp;
TCPMessageData data;
};
#pragma pack(pop)
#define TCPMessageSize sizeof(TCPMessage)
/*************************** Protocol Over UDP ***************************/
enum class UDPMessageType : uint8_t
{
PlayerUpdate,
ActuallyUpdate,
StillThere,
StillHere
};
enum class UDPMessageSender : uint8_t
{
Client,
Server
};
#pragma pack(push, 1)
struct UDPPlayerUpdateData
{
PlayerRecord playerData;
UDPMessageSender sender;
};
#pragma pack(pop)
#pragma pack(push, 1)
struct UDPActuallyUpdate
{
PlayerRecord playerData;
UDPMessageSender sender;
};
#pragma pack(pop)
#pragma pack(push, 1)
struct UDPStillThereData
{
UDPMessageSender sender;
};
#pragma pack(pop)
#pragma pack(push, 1)
struct UDPStillHereData
{
uint8_t id;
UDPMessageSender sender;
};
#pragma pack(pop)
union UDPMessageData
{
UDPMessageData() {}
UDPPlayerUpdateData playerUpdateData;
UDPActuallyUpdate actuallyUpdateData;
UDPStillThereData stillThereData;
UDPStillHereData stillHereData;
};
#pragma pack(push, 1)
struct UDPMessage
{
UDPMessageType type;
uint64_t unixTimestamp;
UDPMessageData data;
};
#pragma pack(pop)
#define UDPMessageSize sizeof(UDPMessage)
|
ccf302b72f464fae9a5619e9772f9aec0eca53fb | 9432c8bb7ea6dd745c5085a8720ef961c9090d57 | /fragmentprocessor.h | 20ea30262f7536233bf10816b5731e24fb0b2641 | [] | no_license | gzmuszynski/pepelepew | 0f2078e2b8631c10df4ef12e02a57d6fd14fa306 | f66a92696534acb00ade2d51f645948050ffa2de | refs/heads/master | 2021-09-15T06:56:20.064449 | 2018-05-27T17:46:05 | 2018-05-27T17:46:05 | 119,704,403 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,037 | h | fragmentprocessor.h | #ifndef FRAGMENTPROCESSOR_H
#define FRAGMENTPROCESSOR_H
#include "buffer.h"
#include "curvilineartrianglefunction.h"
#include "vertexprocessor.h"
class FragmentShader;
class FragmentProcessor
{
public:
FragmentProcessor();
VertexProcessor* vp;
FragmentShader* fragmentShader;
TriangleFunction* triangleFunction;
void rasterize(Buffer &buffer);
float4 minmax(Vertex* &triangle);
QVector<int4> triangleBuffer;
QVector<Material> materialBuffer;
float4 triangleBounds(Vertex *&triangle);
};
class Fragment
{
public:
Fragment(float4 color, float4 depth, float4 normal, float4 position) :
color(color),
depth(depth),
normal(normal),
position(position) {}
float4 color;
float4 depth;
float4 normal;
float4 position;
};
class FragmentShader
{
public:
FragmentShader(FragmentProcessor* fp);
virtual Fragment process(Vertex* &triangle, Hit &hit, Material &material);
protected:
FragmentProcessor* fp;
};
#endif // FRAGMENTPROCESSOR_H
|
2af7b1248fe1caba5d5bba3ff5d94c6df165f688 | c3bcfc898dbf33396baacecd6a56fa261b0fe664 | /include/d_store.h | 03e2f9e907abc922b23c95f77b5c733d1e7a51be | [] | no_license | yunnis/DataStructureWithCPlusPlusUsingSTL | f61c7c26bfedf3bc9a70b6ea1be0dd387480431d | d3c6e2794038dd36228f46a2de8a6db46c6808b6 | refs/heads/master | 2020-04-03T08:55:22.370037 | 2018-11-02T05:25:56 | 2018-11-02T05:25:56 | 155,149,207 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,008 | h | d_store.h | #ifndef D_STORE_H_INCLUDED
#define D_STORE_H_INCLUDED
#include <iostream>
#include <ostream>
// 累的模板版本(模板类)
template <typename T>
class store
{
public:
// 使用 item 或 类型T 的默认对象进行初始化
store(const T& item = T() );
// 检索并返回数据成员值
T getValue() const;
// 将数据成员值更新为item
// 使用嵌入码
void setValue(const T& item)
{
value = item;
};
// 以"value = "的形式显示输出
// 这个模板类,在使用某个具体类型引用类时, 必须包括类名和角括号中的模板类型T
/// 注意友元函数本身不是类模板, 必须要地难以其具体化
friend std::ostream& operator<< (std::ostream& ostr, const store<T>& obj)
{
ostr << "Value = " << obj.value;
return ostr;
}
private:
T value;
};
// 使用初始化列表赋值
template <typename T>
store<T>::store (const T& item) : value(item)
{}
template <typename T>
T store<T>::getValue() const
{
return value;
}
#endif // D_STORE_H_INCLUDED
|
d4499792ba6cf70dd7ab3de85c3cbf5f54106f75 | 785df77400157c058a934069298568e47950e40b | /TnbGeo/include/Merge_PntAlg.hxx | 851c41c01f11488846d4e02c16e3d68c9aed8217 | [] | no_license | amir5200fx/Tonb | cb108de09bf59c5c7e139435e0be008a888d99d5 | ed679923dc4b2e69b12ffe621fc5a6c8e3652465 | refs/heads/master | 2023-08-31T08:59:00.366903 | 2023-08-31T07:42:24 | 2023-08-31T07:42:24 | 230,028,961 | 9 | 3 | null | 2023-07-20T16:53:31 | 2019-12-25T02:29:32 | C++ | UTF-8 | C++ | false | false | 199 | hxx | Merge_PntAlg.hxx | #pragma once
#ifndef _Merge_PntAlg_Header
#define _Merge_PntAlg_Header
namespace tnbLib
{
enum Merge_PntAlg
{
Merge_PntAlg_Mean,
Merge_PntAlg_Substitude
};
}
#endif // !_Merge_PntAlg_Header |
49f9a2a5284a5ce007934cd009d200bd7f5bff8e | d138deda43e36f6c79c5e3a9ef1cc62c6a92e881 | /paddle/fluid/distributed/table/tensor_table.cc | d8e1be7a9815c4aad21cd24733fd6747f3e0d56b | [
"Apache-2.0"
] | permissive | seiriosPlus/Paddle | 51afd6f5c85c3ce41dd72953ee659d1539c19f90 | 9602a182b2a4979247c09df1ec283fc39cb4a981 | refs/heads/develop | 2021-08-16T16:05:10.848535 | 2020-12-27T15:15:19 | 2020-12-27T15:15:19 | 123,257,829 | 2 | 0 | Apache-2.0 | 2019-12-10T08:22:01 | 2018-02-28T08:57:42 | C++ | UTF-8 | C++ | false | false | 3,404 | cc | tensor_table.cc | // Copyright (c) 2020 PaddlePaddle Authors. 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 "paddle/fluid/distributed/table/tensor_table.h"
#include "paddle/fluid/distributed/common/utils.h"
namespace paddle {
namespace distributed {
int32_t DenseTensorTable::initialize() {
_shards_task_pool.resize(10);
for (int i = 0; i < _shards_task_pool.size(); ++i) {
_shards_task_pool[i].reset(new ::ThreadPool(1));
}
return 0;
}
int32_t DenseTensorTable::initialize_tensor(framework::Scope *scope,
framework::ProgramDesc *program,
framework::Executor *executor) {
scope_ = scope;
program_ = program;
executor_ = executor;
auto tensor_config = _config.tensor();
if (tensor_config.has_common_block_map()) {
auto block_maps =
paddle::string::split_string(tensor_config.common_block_map(), "#");
for (auto &block_map : block_maps) {
auto block = paddle::string::split_string(block_map, ":");
auto block_id = std::stoi(block[0]);
std::vector<int> block_ids{block_id};
auto block_cmd = block[1];
auto prepared = executor_->Prepare(*program_, block_ids);
(*prepared_ctx_)[block_cmd] = prepared[0];
}
}
}
int32_t DenseTensorTable::pull_dense(float *values, size_t numel) {
PADDLE_ENFORCE_EQ(numel, _data.numel(),
paddle::platform::errors::PreconditionNotMet(
"pull dense error, excepted numel %d, but actually %d.",
_data.numel(), numel));
GetBlas<float>().VCOPY(numel, _data.data<float>(), values);
return 0;
}
int32_t DenseTensorTable::push_dense(const float *values, size_t numel) {
auto varname = _config.tensor().grad();
auto local_scope = scope_->NewTmpScope();
auto *var = local_scope->Var(varname);
auto *t = var->GetMutable<framework::LoDTensor>();
auto dims = paddle::framework::make_ddim({});
auto ctx = paddle::platform::CPUDeviceContext();
t->mutable_data<float>(_data.dims(), ctx.GetPlace());
GetBlas<float>().VCOPY(numel, values, t->data<float>());
executor_->RunPreparedContext((*prepared_ctx_)["push"].get(),
local_scope.get());
}
int32_t DenseTensorTable::push_dense_param(const float *values, size_t numel) {
auto ctx = paddle::platform::CPUDeviceContext();
if (_data.IsInitialized()) {
PADDLE_ENFORCE_EQ(
numel, _data.numel(),
paddle::platform::errors::PreconditionNotMet(
"pull dense error, excepted numel %d, but actually %d.",
_data.numel(), numel));
} else {
_data.mutable_data<float>(
framework::make_ddim({static_cast<int64_t>(numel), 1}), ctx.GetPlace());
}
GetBlas<float>().VCOPY(numel, values, _data.data<float>());
return 0;
}
} // namespace distributed
} // namespace paddle
|
55f885f7cf83569b8f9c8c06a546ef1a7e638d3b | 7065ae03809c28f18acc5b0e32d7cb2c371ca2f9 | /P195 string容器-字符串插入和删除/P195 string容器-字符串插入和删除.cpp | d8091ee137cf9789061ae40e5ca47964e3e7647a | [] | no_license | callmer00t/cpp_learning | 63d6bd12879590d20da117cfe5c67cf8791b4252 | 703bf026a723c59a8dde592b0b3b0769086cbfd4 | refs/heads/master | 2023-07-22T02:38:40.705882 | 2021-08-17T07:07:33 | 2021-08-17T07:07:33 | 386,171,041 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 456 | cpp | P195 string容器-字符串插入和删除.cpp | #include<iostream>
using namespace std;
#include<string>
//字符插入和删除
void test1()
{
string str = "hello";
str.insert(1, "111"); //第一个参数是从X个索引位置插入,第二个参数是插入的内容
cout << "str = " << str << endl;
str.erase(1, 3); //第一个参数是从X索引位置开始删除,第二个参数是删除X个字符
cout << "str = " << str << endl;
}
int main()
{
test1();
system("pause");
return 0;
} |
01b46b07d4467360ad27f7c68e685d68d8302f97 | 484e44c0f1476c905230327bd1276e4a9376b22e | /LinkedList.cpp | 52810fa0af75ecd8eca8bd86ef9ed8a32e6bb569 | [] | no_license | DaveStorey/Linked_list | 7ffb4f67b3466a95fa7fe9b789855914d9ff37ce | a8e768476a6df0c01fc8b9e393b045a3cf9d2691 | refs/heads/master | 2020-12-30T15:54:44.512138 | 2017-05-13T15:43:51 | 2017-05-13T15:43:51 | 91,184,866 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,203 | cpp | LinkedList.cpp | /*
* LinkedList.cpp
*
* Created on: May 1, 2017
* Author: David Storey
*/
#include "LinkedList.h"
#include <iostream>
using namespace std;
//Constructor
NumberList::NumberList() {
head = nullptr;
tail = nullptr;
}
//Destructor
NumberList::~NumberList()
{
ListNode *nodePtr;
ListNode *nextNode;
nodePtr = head;
while (nodePtr != nullptr)
{
nextNode = nodePtr->next;
delete nodePtr;
nodePtr = nextNode;
}
}
//Adds a value to the end of the list
void NumberList::appendNode(int num)
{
ListNode *newNode;
newNode = new ListNode;
newNode->value = num;
newNode->next = nullptr;
newNode->previous = nullptr;
//If statement creating the list if no list previously existed.
if (!head){
head = newNode;
tail = newNode;
}
//Else statement using tail to append the node.
else
{
newNode->previous = tail;
tail->next = newNode;
tail = newNode;
}
}
//Adds the value before the first number that is greater in the list
void NumberList::insertNodeInSortedOrder(int num)
{
ListNode *newNode = nullptr;
ListNode *nodePtr = nullptr;
ListNode *previousNode = nullptr;
newNode = new ListNode;
newNode->value = num;
//If statement placing node at the head if it is the first node created.
if(!head)
{
head = newNode;
tail = newNode;
newNode->next = nullptr;
}
else
{
nodePtr = head;
//Traversing the list
while (nodePtr != nullptr && nodePtr->value < num)
{
previousNode = nodePtr;
nodePtr = nodePtr->next;
}
/*If/else if statements to deal with cases at the beginning and end of the list without creating seg
faults, as well as ensure proper placement of head and tail pointers.*/
if (previousNode == nullptr)
{
head = newNode;
newNode->next = nodePtr;
}
else if (nodePtr != nullptr)
{
nodePtr->previous = newNode;
previousNode->next = newNode;
newNode->next = nodePtr;
newNode->previous = previousNode;
}
else if (nodePtr == nullptr)
{
previousNode->next = newNode;
newNode->next = nullptr;
newNode->previous = previousNode;
tail = newNode;
}
}
}
void NumberList::addToStart(int value)
{
ListNode *newNode;
ListNode *nodePtr;
newNode = new ListNode;
newNode->value = value;
//If statement creating the list if no list previously existed.
if (!head){
newNode->next = nullptr;
head = newNode;
tail = newNode;
}
//Else statement placing new node at the front, using the head pointer.
else
{
nodePtr = head;
head = newNode;
newNode->next = nodePtr;
nodePtr->previous = newNode;
}
}
void NumberList::insertNodeAtLoc(int loc)
{
int value, count = 0;
ListNode *nodePtr;
ListNode *previousNode;
ListNode *newNode;
//Dyanmically allocating new node, getting value for it, and placing user-defined value in the node.
newNode = new ListNode;
cout << "What value would you like to insert at position " << loc << "?";
cin >> value;
newNode->value = value;
nodePtr = head;
previousNode = nullptr;
//Traversing the list with a trailer keeping track of previous node position.
while(nodePtr != nullptr && count < loc)
{
previousNode = nodePtr;
nodePtr = nodePtr->next;
count++;
}
/*If/Else if statements as sanity check, as well as dealing with cases at the beginning and end
of the lists without creating seg faults and ensuring proper placement of head and tail pointers.*/
if (nodePtr == nullptr && count < loc)
cout << "The list is not that long!\n";
else if (nodePtr == nullptr && count == loc)
{
previousNode->next = newNode;
newNode->previous = previousNode;
newNode->next = nullptr;
tail = newNode;
}
else if (nodePtr != nullptr && count == loc)
{
previousNode->next = newNode;
newNode->previous = previousNode;
newNode->next = nodePtr;
nodePtr->previous = newNode;
}
}
//Function returning the value of a user-specified list location.
int NumberList::getNodeValueAtLocation(int loc)
{
int value, count = 0;
ListNode *nodePtr;
//If statement with an early return if no list created.
if (!head)
{
cout << "List not yet created.\n";
return 0;
}
nodePtr = head;
//Traversing the list while keeping track of what number node it is on.
while(nodePtr != nullptr && count < loc)
{
nodePtr = nodePtr->next;
count++;
}
//If/else if statement as sanity check on list length.
if (nodePtr == nullptr && count < loc)
cout << "The list isn't that long!\n";
else if (count == loc)
value = nodePtr->value;
return value;
}
//Function merging two nodes, stored the summed value in the first node and deleting the second.
void NumberList::mergeTwoNodes(int a, int b)
{
ListNode *nodePtrA;
ListNode *nodePtrB;
ListNode *previous;
ListNode *temp;
int valueA, valueB, countA = 0, countB = 0;
bool beyondTheList = false;
nodePtrA = head;
//Finding the location of the first node.
while(nodePtrA != nullptr && countA < (a-1))
{
nodePtrA = nodePtrA->next;
countA++;
}
//If/else if statement as sanity check on list length.
if (nodePtrA == nullptr)
{
cout << "Location "<< a << "is beyond the list!\n";
beyondTheList = true;
}
else if (countA == (a - 1))
valueA = nodePtrA->value;
nodePtrB = head;
//Finding the location of the second node.
while(nodePtrB != nullptr && countB < (b-1))
{
previous = nodePtrB;
nodePtrB = nodePtrB->next;
countB++;
}
//If/else if statement as sanity check on list length.
if (nodePtrB == nullptr)
{
cout << "Location "<< b << "is beyond the list!\n";
beyondTheList = true;
}
else if (countB == (b - 1))
valueB = nodePtrB->value;
//If statement checking that neither location is beyond the list length.
if (!beyondTheList)
{
nodePtrA->value = valueA + valueB;
temp = nodePtrB->next;
previous->next = temp;
/*Dual if/else if statements dealing with the second location being at the front or back of the list
without creating seg faults, and deleting the second node to avoid memory leaks. */
if (temp != nullptr)
temp->previous = previous;
else if (temp == nullptr)
tail = previous;
if (nodePtrB->previous == nullptr)
head = nodePtrB->next;
delete nodePtrB;
}
}
//Function swapping two nodes position in the list, while maintaining their value and addresses.
void NumberList::swapNodes(int a, int b)
{
ListNode *nodePtrA;
ListNode *nodePtrB;
ListNode *previousA;
ListNode *previousB;
ListNode *nextA;
ListNode *nextB;
int countA = 0, countB = 0;
bool beyondTheList = false;
//If statement with an early return if no list created.
if (!head)
{
cout << "List not yet created.\n";
return;
}
nodePtrA = head;
//Locating the first node.
while(nodePtrA != nullptr && countA < (a-1))
{
previousA = nodePtrA;
nodePtrA = nodePtrA->next;
countA++;
}
//If statement checking to see if first location is beyond the list.
if (nodePtrA == nullptr)
{
cout << "Location "<< a << "is beyond the list!\n";
beyondTheList = true;
}
nodePtrB = head;
//Locating the second node.
while(nodePtrB != nullptr && countB < (b-1))
{
previousB = nodePtrB;
nodePtrB = nodePtrB->next;
countB++;
}
//If statement checking to see if second location is beyond the list.
if (nodePtrB == nullptr)
{
cout << "Location "<< b << "is beyond the list!\n";
beyondTheList = true;
}
//If statement checking that neither location is beyond the list.
if (!beyondTheList)
{
//Getting addresses of previous and next nodes in the list independent of the nodes to be swapped.
nextA = nodePtrA->next;
nextB = nodePtrB->next;
nodePtrA->previous = previousB;
nodePtrA->next = nextB;
nodePtrB->next = nextA;
nodePtrB->previous = previousA;
/*Dual if/else if statements for each node, dealing with either being at the front or back without
seg faults, as well as properly placing head and tail pointers.*/
if (previousA != nullptr)
previousA->next = nodePtrB;
else if (previousA == nullptr)
head = nodePtrB;
if(previousB != nullptr)
previousB->next = nodePtrA;
else if (previousB == nullptr)
head = nodePtrA;
if (nextA != nullptr)
nextA->previous = nodePtrB;
else if (nextA == nullptr)
tail = nodePtrB;
if (nextB != nullptr)
nextB->previous = nodePtrA;
else if (nextB == nullptr)
tail = nodePtrA;
}
}
//Function to remove all duplicates from the list
void NumberList::removeAllDuplicates()
{
ListNode *nodePtr;
ListNode *nodePtrDup;
ListNode *nodePtrDupNext;
ListNode *nodePtrDupPrev;
int value;
//If statement with early termination if there is no list created yet.
if (!head)
{
cout << "List not yet created.\n";
return;
}
nodePtr = head;
/*Nested while statements to search for duplicates of each node, and cut the duplicate out of the list,
deleting the duplicate node to avoid memory leaks.*/
while (nodePtr != nullptr)
{
value = nodePtr->value;
nodePtrDup = nodePtr->next;
while (nodePtrDup != nullptr)
{
nodePtrDupNext = nodePtrDup->next;
nodePtrDupPrev = nodePtrDup->previous;
if (nodePtrDup->value == value)
{
if (nodePtrDupPrev != nullptr)
nodePtrDupPrev->next = nodePtrDupNext;
if (nodePtrDupNext != nullptr)
nodePtrDupNext->previous = nodePtr;
else if (nodePtrDupNext == nullptr)
tail = nodePtrDupPrev;
delete nodePtrDup;
}
nodePtrDup = nodePtrDupNext;
}
nodePtr = nodePtr->next;
}
}
//Function for deleting a node of specified value
void NumberList::deleteNodeOfValue(int num)
{
ListNode *nodePtr;
ListNode *previousNode;
ListNode *temp;
//If statement with an early return if no list created.
if (!head)
{
cout << "List not yet created.\n";
return;
}
//If statement dealing with if the head is the value to be deleted.
if (head->value == num)
{
nodePtr = head->next;
delete head;
head = nodePtr;
}
else
{
nodePtr = head;
while (nodePtr != nullptr && nodePtr->value != num)
{
previousNode = nodePtr;
nodePtr = nodePtr->next;
if (nodePtr != nullptr)
nodePtr->previous = previousNode;
}
if (nodePtr)
{
temp = nodePtr->next;
previousNode->next = temp;
/*If/else if statement to ensure proper placement of the tail and avoid seg faults, deleting
specified node to avoid memory leaks.*/
if (temp != nullptr)
temp->previous = previousNode;
else if (temp == nullptr)
tail = previousNode;
delete nodePtr;
}
}
}
//Function for deleting a node at a user specified location
void NumberList::deleteNodeAtLocation(int loc)
{
ListNode *nodePtr;
ListNode *previous = nullptr;
ListNode *next;
int count = 0;
nodePtr = head;
//Locating the proper node.
while(nodePtr != nullptr && count < loc)
{
previous = nodePtr;
nodePtr = nodePtr->next;
count++;
}
//Sanity check
if (nodePtr == nullptr && count < loc)
cout << "The list isn't that long!\n";
else if (count == loc)
{
next = nodePtr->next;
//If/else if statement to ensure proper placement of the tail and avoid seg faults.
if (next != nullptr && previous != nullptr)
{
next->previous = previous;
previous->next = next;
}
else if (next == nullptr)
{
previous->next = nullptr;
tail = previous;
}
else if (previous == nullptr)
{
next->previous = nullptr;
head = next;
}
//Deleting the node to avoid memory leaks.
delete nodePtr;
}
}
//Function for displaying the list, including an option for displaying the list with memory address pointers.
void NumberList::displayList() const
{
ListNode *nodePtr;
char memChoice;
nodePtr = head;
cout << "Would you like to display the list with memory locations included? (y/n)";
cin >> memChoice;
//If/else if/else statements to deal with yes, no, or improperly formatted user choice.
if (memChoice =='y' || memChoice == 'Y')
{
cout << "Head = " << head << endl;
while (nodePtr)
{
cout << "Previous address: "<< nodePtr->previous << ", value: " << nodePtr->value << ", next address: " << nodePtr->next << "\n";
nodePtr = nodePtr->next;
}
cout << "Tail = " << tail << endl;
}
else if (memChoice == 'n' || memChoice == 'N')
{
while (nodePtr)
{
cout << "Value: " << nodePtr->value << endl;
nodePtr = nodePtr->next;
}
}
else
cout << "Invalid choice, returning to main menu.\n";
}
|
a0abb20acdc8bc022c77bb6dd6b0edc29e7a1f1c | 363a553ff7b23eb1618259e6aa93b9f184a77fb5 | /Bomberman/Intermediate/Build/Win64/UE4Editor/Inc/Bomberman/BombermanCharacter.gen.cpp | 97fefd8eebbc0c88c570c0019a9580ed096a4f5e | [] | no_license | zakkar/IKA | a98112e05e82dfe5c325c9e115fdb912a6b40553 | 6217a342db98d090e0774b97617f5fb819c3a0fd | refs/heads/master | 2021-05-06T14:45:06.799142 | 2017-12-16T14:17:23 | 2017-12-16T14:17:23 | 113,393,229 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,224 | cpp | BombermanCharacter.gen.cpp | // Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
/*===========================================================================
Generated code exported from UnrealHeaderTool.
DO NOT modify this manually! Edit the corresponding .h files instead!
===========================================================================*/
#include "GeneratedCppIncludes.h"
#include "BombermanCharacter.h"
#ifdef _MSC_VER
#pragma warning (push)
#pragma warning (disable : 4883)
#endif
PRAGMA_DISABLE_DEPRECATION_WARNINGS
void EmptyLinkFunctionForGeneratedCodeBombermanCharacter() {}
// Cross Module References
BOMBERMAN_API UClass* Z_Construct_UClass_ABombermanCharacter_NoRegister();
BOMBERMAN_API UClass* Z_Construct_UClass_ABombermanCharacter();
ENGINE_API UClass* Z_Construct_UClass_ACharacter();
UPackage* Z_Construct_UPackage__Script_Bomberman();
BOMBERMAN_API UFunction* Z_Construct_UFunction_ABombermanCharacter_FillInventory();
BOMBERMAN_API UFunction* Z_Construct_UFunction_ABombermanCharacter_Init();
// End Cross Module References
void ABombermanCharacter::StaticRegisterNativesABombermanCharacter()
{
UClass* Class = ABombermanCharacter::StaticClass();
static const FNameNativePtrPair Funcs[] = {
{ "FillInventory", (Native)&ABombermanCharacter::execFillInventory },
{ "Init", (Native)&ABombermanCharacter::execInit },
};
FNativeFunctionRegistrar::RegisterFunctions(Class, Funcs, ARRAY_COUNT(Funcs));
}
UFunction* Z_Construct_UFunction_ABombermanCharacter_FillInventory()
{
static UFunction* ReturnFunction = nullptr;
if (!ReturnFunction)
{
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[] = {
{ "ModuleRelativePath", "BombermanCharacter.h" },
};
#endif
static const UE4CodeGen_Private::FFunctionParams FuncParams = { (UObject*(*)())Z_Construct_UClass_ABombermanCharacter, "FillInventory", RF_Public|RF_Transient|RF_MarkAsNative, nullptr, (EFunctionFlags)0x00020401, 0, nullptr, 0, 0, 0, METADATA_PARAMS(Function_MetaDataParams, ARRAY_COUNT(Function_MetaDataParams)) };
UE4CodeGen_Private::ConstructUFunction(ReturnFunction, FuncParams);
}
return ReturnFunction;
}
UFunction* Z_Construct_UFunction_ABombermanCharacter_Init()
{
static UFunction* ReturnFunction = nullptr;
if (!ReturnFunction)
{
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[] = {
{ "ModuleRelativePath", "BombermanCharacter.h" },
};
#endif
static const UE4CodeGen_Private::FFunctionParams FuncParams = { (UObject*(*)())Z_Construct_UClass_ABombermanCharacter, "Init", RF_Public|RF_Transient|RF_MarkAsNative, nullptr, (EFunctionFlags)0x04020401, 0, nullptr, 0, 0, 0, METADATA_PARAMS(Function_MetaDataParams, ARRAY_COUNT(Function_MetaDataParams)) };
UE4CodeGen_Private::ConstructUFunction(ReturnFunction, FuncParams);
}
return ReturnFunction;
}
UClass* Z_Construct_UClass_ABombermanCharacter_NoRegister()
{
return ABombermanCharacter::StaticClass();
}
UClass* Z_Construct_UClass_ABombermanCharacter()
{
static UClass* OuterClass = nullptr;
if (!OuterClass)
{
static UObject* (*const DependentSingletons[])() = {
(UObject* (*)())Z_Construct_UClass_ACharacter,
(UObject* (*)())Z_Construct_UPackage__Script_Bomberman,
};
static const FClassFunctionLinkInfo FuncInfo[] = {
{ &Z_Construct_UFunction_ABombermanCharacter_FillInventory, "FillInventory" }, // 2199507394
{ &Z_Construct_UFunction_ABombermanCharacter_Init, "Init" }, // 84751288
};
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Class_MetaDataParams[] = {
{ "HideCategories", "Navigation" },
{ "IncludePath", "BombermanCharacter.h" },
{ "ModuleRelativePath", "BombermanCharacter.h" },
};
#endif
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_OffsetBombSpawn_MetaData[] = {
{ "Category", "BombermanCharacter" },
{ "ModuleRelativePath", "BombermanCharacter.h" },
{ "ToolTip", "Used to offset spawwning bomb to avoid physics problem" },
};
#endif
static const UE4CodeGen_Private::FFloatPropertyParams NewProp_OffsetBombSpawn = { UE4CodeGen_Private::EPropertyClass::Float, "OffsetBombSpawn", RF_Public|RF_Transient|RF_MarkAsNative, 0x0010000000000005, 1, nullptr, STRUCT_OFFSET(ABombermanCharacter, OffsetBombSpawn), METADATA_PARAMS(NewProp_OffsetBombSpawn_MetaData, ARRAY_COUNT(NewProp_OffsetBombSpawn_MetaData)) };
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_MaxBombInventory_MetaData[] = {
{ "Category", "BombermanCharacter" },
{ "ModuleRelativePath", "BombermanCharacter.h" },
{ "ToolTip", "Number of maximum Bomb that the player can carry(including upgrades)" },
};
#endif
static const UE4CodeGen_Private::FUnsizedIntPropertyParams NewProp_MaxBombInventory = { UE4CodeGen_Private::EPropertyClass::Int, "MaxBombInventory", RF_Public|RF_Transient|RF_MarkAsNative, 0x0010000000000004, 1, nullptr, STRUCT_OFFSET(ABombermanCharacter, MaxBombInventory), METADATA_PARAMS(NewProp_MaxBombInventory_MetaData, ARRAY_COUNT(NewProp_MaxBombInventory_MetaData)) };
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_MaxBombCanBeSpawned_MetaData[] = {
{ "Category", "BombermanCharacter" },
{ "ModuleRelativePath", "BombermanCharacter.h" },
{ "ToolTip", "Number of maximum Bomb that the player can spawn from the start" },
};
#endif
static const UE4CodeGen_Private::FUnsizedIntPropertyParams NewProp_MaxBombCanBeSpawned = { UE4CodeGen_Private::EPropertyClass::Int, "MaxBombCanBeSpawned", RF_Public|RF_Transient|RF_MarkAsNative, 0x0010000000000005, 1, nullptr, STRUCT_OFFSET(ABombermanCharacter, MaxBombCanBeSpawned), METADATA_PARAMS(NewProp_MaxBombCanBeSpawned_MetaData, ARRAY_COUNT(NewProp_MaxBombCanBeSpawned_MetaData)) };
static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[] = {
(const UE4CodeGen_Private::FPropertyParamsBase*)&NewProp_OffsetBombSpawn,
(const UE4CodeGen_Private::FPropertyParamsBase*)&NewProp_MaxBombInventory,
(const UE4CodeGen_Private::FPropertyParamsBase*)&NewProp_MaxBombCanBeSpawned,
};
static const FCppClassTypeInfoStatic StaticCppClassTypeInfo = {
TCppClassTypeTraits<ABombermanCharacter>::IsAbstract,
};
static const UE4CodeGen_Private::FClassParams ClassParams = {
&ABombermanCharacter::StaticClass,
DependentSingletons, ARRAY_COUNT(DependentSingletons),
0x00800080u,
FuncInfo, ARRAY_COUNT(FuncInfo),
PropPointers, ARRAY_COUNT(PropPointers),
"Game",
&StaticCppClassTypeInfo,
nullptr, 0,
METADATA_PARAMS(Class_MetaDataParams, ARRAY_COUNT(Class_MetaDataParams))
};
UE4CodeGen_Private::ConstructUClass(OuterClass, ClassParams);
}
return OuterClass;
}
IMPLEMENT_CLASS(ABombermanCharacter, 2381980662);
static FCompiledInDefer Z_CompiledInDefer_UClass_ABombermanCharacter(Z_Construct_UClass_ABombermanCharacter, &ABombermanCharacter::StaticClass, TEXT("/Script/Bomberman"), TEXT("ABombermanCharacter"), false, nullptr, nullptr, nullptr);
DEFINE_VTABLE_PTR_HELPER_CTOR(ABombermanCharacter);
PRAGMA_ENABLE_DEPRECATION_WARNINGS
#ifdef _MSC_VER
#pragma warning (pop)
#endif
|
39a9e2183bf0b3c0eaa676d10ee8ec5d95638d94 | da03930f45319ebc3af391f92352657030a46c25 | /src/treeeventnode.cpp | b998c3bd45e8f544101b7adbbf5c2d3d98ff4a5d | [] | no_license | cran/TraMineR | 7c5a47bf44b60d0aa8e798b893b766359a106122 | f69de43d018da19df8247a9090ebd1c01803d246 | refs/heads/master | 2023-04-11T10:25:42.257555 | 2023-03-31T17:20:02 | 2023-03-31T17:20:02 | 17,693,958 | 12 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 4,207 | cpp | treeeventnode.cpp | #include "treeeventnode.h"
#include "treeeventmap.h"
#include "constraint.h"
int TreeEventNode::nodeCount=0;
int TreeEventNode::getNodeCount() {
return nodeCount;
}
void TreeEventNode::getSubsequences(SEXP result, double * isupport, Sequence *s, int *index,const double &step, SEXP classname,EventDictionary * ed) {
this->brother.getSubsequences(result,isupport,s,index,step, classname,ed);
this->child.getSubsequences(result,isupport,s,index,step+1, classname,ed);
}
//Type of this event
/**
*TreeEventNode
Prefix Tree base node
*/
//Ctor
TreeEventNode::TreeEventNode(const int& t):type(t),support(0),lastID(-1) {
nodeCount++;
}
//Dtor
TreeEventNode::~TreeEventNode() {
TreeEventMapIterator it;
nodeCount--;
this->brother.clearAllPointers();
this->child.clearAllPointers();
//REprintf("Node deleted (DTOR finished)%i\n",nodeCount);
}
//Main function to build the tree
void TreeEventNode::addSequenceInternal(Sequence *s, SequenceEventNode * en, Constraint * cst, const double &gapConsumed, const double& currentAge, const int& k, const int¤tK) {
//If we already reached this point with the specified sequence, don't increment
/*if (this->lastID!=s->getIDpers()) {
this->support++;//
this->lastID=s->getIDpers();
}*/
// If we count several by sequences, or the last element added was from another sequence, we had this element to support.
if (cst->getcountMethod()==2 || this->lastID != s->getIDpers()) {
this->support+=s->getWeight();//
this->lastID=s->getIDpers();
}
if (!en->hasNext())return;
if (currentK>k)return;
//Current Gap for next subsequence search
double currentGap=0;
//next subsequences
SequenceEventNode *n=en;
//Iterator to search for brother and child
TreeEventMapIterator it;
TreeEventNode *ten=NULL;
while (n->hasNext()) {
n=n->getNext();//Get Next element
currentGap+=n->getGap(); //Increment current gap
//3 terminations conditions
if ( gapConsumed+currentGap>cst->getwindowSize() //current window Size too big
||currentGap>cst->getmaxGap() //current gap too big
||currentGap+currentAge>cst->getageMaxEnd() //current age too big
) {
break;
}
//IF the gap is >0, then we have children
if (currentGap>0) {
it=this->child.find(n->getType());//Search for child
if (it!=this->child.end()) { //if exist
ten=it->second;
} else if (k==currentK) { //Build new child
ten=new TreeEventNode(n->getType());
this->child[n->getType()]=ten;
} else {
ten=NULL;
}
} else { //currentGap==0
it=this->brother.find(n->getType());
if (it!=this->brother.end()) {
ten =it->second;
} else if (k==currentK) { //Build new brother
ten=new TreeEventNode(n->getType());
this->brother[n->getType()]=ten ;
} else {
ten=NULL;
}
}
if (ten!=NULL)ten->addSequenceInternal(s,n,cst,gapConsumed+currentGap, currentAge+currentGap,k,currentK+1);//Increment support and continue
}//end while(hasNext())
}
void TreeEventNode::simplifyTree(double minSup) {
this->brother.simplifyTreeMap(minSup);
this->child.simplifyTreeMap(minSup);
}
void TreeEventNode::print(const int & prof, const bool& isbrother) {
for (int i=0;i<prof;i++) {
Rprintf((char*)" ");
}
if (isbrother) {
Rprintf((char*)"|--(%i:%f)[%i]\n",this->type,this->support,this->lastID);
} else {
Rprintf((char*)"|__(%i:%f)[%i]\n",this->type,this->support,this->lastID);
}
this->brother.print(prof+1,isbrother);
//print each child branches
this->child.print(prof+1,isbrother);
}
int TreeEventNode::countSubsequence(double minSup) {
return 1+this->brother.countSubsequence(minSup)+this->child.countSubsequence(minSup);
}
void TreeEventNode::clearSupport() {
this->support=0;
this->lastID = -1;
this->child.clearSupport();
this->brother.clearSupport();
}
|
3d2501c08080c99392483b4b76de6c21e447a575 | 0dd5b46b598959741afc6a16c15c9f0492ca2bc5 | /common/_Utils.cc | 09eab405f7c904349f4246121cb9fd9656ad255b | [] | no_license | xaccc/webrtc-everywhere | 45ee2fa4048f315b4d44e5e1e39fb64e9f44a332 | c5a2d414ad552355e2494daf7fe035fc712b79ac | refs/heads/master | 2021-01-18T11:59:37.430001 | 2014-06-29T05:55:45 | 2014-06-29T05:55:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,892 | cc | _Utils.cc | #include "_Utils.h"
#include "_RTCDisplay.h"
#include "_AsyncEvent.h"
#include "_Debug.h"
#include "_Common.h"
#if WE_UNDER_WINDOWS
#include "windows.h"
#include "talk/base/win32socketinit.h"
#endif
#include "talk/base/ssladapter.h"
static bool g_bInitialized = false;
_Utils::_Utils()
{
}
_Utils::~_Utils()
{
}
WeError _Utils::Initialize(WeError(*InitializeAdditionals) (void) /*= NULL*/)
{
if(!g_bInitialized) {
#if 0
StartDebug();
#endif
#if WE_UNDER_WINDOWS
talk_base::EnsureWinsockInit();
#endif
talk_base::InitializeSSL();
g_bInitialized = true;
}
if (InitializeAdditionals) {
return InitializeAdditionals();
}
return WeError_Success;
}
WeError _Utils::DeInitialize(void)
{
if (g_bInitialized) {
talk_base::CleanupSSL();
}
return WeError_Success;
}
WeError _Utils::StartDebug(void)
{
#if WE_UNDER_WINDOWS
if (AllocConsole()) {
freopen("CONIN$", "r", stdin);
freopen("CONOUT$", "w", stdout);
freopen("CONOUT$", "w", stderr);
SetConsoleTitleA("WebRTC extension for Safari, Opera, FireFox and IE");
return WeError_Success;
}
return WeError_OutOfMemory;
#else
return WeError_Success;
#endif
}
WeError _Utils::StopDebug(void)
{
#if WE_UNDER_WINDOWS
return (FreeConsole() == TRUE) ? WeError_Success : WeError_System;
#else
return WeError_Success;
#endif
}
std::string _Utils::ToString(long val)
{
char str[22];
sprintf(str, "%ld", val);
return std::string(str);
}
class _NPAsyncData {
public:
_NPAsyncData(HWND _hWnd, UINT _uMsg, WPARAM _wParam, LPARAM _lParam)
: hWnd(_hWnd)
, uMsg(_uMsg)
, wParam(_wParam)
, lParam(_lParam)
{}
HWND hWnd;
UINT uMsg;
WPARAM wParam;
LPARAM lParam;
};
static void _NPWndProc(void *npdata)
{
_NPAsyncData* _npdata = dynamic_cast<_NPAsyncData*>((_NPAsyncData*)npdata);
_Utils::WndProc(_npdata->hWnd, _npdata->uMsg, _npdata->wParam, _npdata->lParam);
delete _npdata;
}
bool _Utils::RaiseCallback(LONGLONG handle, _BrowserCallback* cb)
{
if (!cb) {
return false;
}
HWND hWnd = reinterpret_cast<HWND>(handle);
bool ret = false;
// retain() callback object
cb->RetainObject();
#if WE_UNDER_WINDOWS
if (hWnd) {
ret = (PostMessage(hWnd, cb->GetMsgId(), reinterpret_cast<WPARAM>(cb), NULL) == TRUE);
}
else {
WE_DEBUG_WARN("Not handle associated to the window yet");
_Utils::WndProc(hWnd, cb->GetMsgId(), reinterpret_cast<WPARAM>(cb), NULL);
ret = true;
}
#elif WE_UNDER_APPLE
_NPAsyncData* _npdata = new _NPAsyncData(hWnd, msg, reinterpret_cast<WPARAM>(*cb), NULL);
if (_npdata) {
dispatch_async(dispatch_get_main_queue(), ^{
_NPWndProc(_npdata);
});
ret = true;
}
#else
#error "Not implemented"
#endif
// release() callback object
if (ret) {
// all is ok -> object will be freed by the async functin
}
else {
cb->ReleaseObject();
}
return ret;
}
LRESULT CALLBACK _Utils::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch (uMsg) {
#if WE_UNDER_WINDOWS
case WM_PAINT:
{
_RTCDisplay* display = dynamic_cast<_RTCDisplay*>(reinterpret_cast<_RTCDisplay*>(GetWindowLongPtr(hWnd, GWLP_USERDATA)));
if (display && display->PaintFrame()) {
return 0;
}
else {
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hWnd, &ps);
RECT rc;
GetClientRect(hWnd, &rc);
// Set Clip region to the rectangle specified by di.prcBounds
HRGN hRgnOld = NULL;
if (GetClipRgn(hdc, hRgnOld) != 1) {
hRgnOld = NULL;
}
bool bSelectOldRgn = false;
HRGN hRgnNew = CreateRectRgn(rc.left, rc.top, rc.right, rc.bottom);
if (hRgnNew != NULL) {
bSelectOldRgn = (SelectClipRgn(hdc, hRgnNew) != ERROR);
}
Rectangle(hdc, rc.left, rc.top, rc.right, rc.bottom);
SetTextAlign(hdc, TA_CENTER | TA_BASELINE);
LPCTSTR pszText = TEXT("ATL 8.0 : WebRTC Plugin");
#ifndef _WIN32_WCE
TextOut(hdc,
(rc.left + rc.right) / 2,
(rc.top + rc.bottom) / 2,
pszText,
lstrlen(pszText));
#else
ExtTextOut(hdc,
(rc.left + rc.right) / 2,
(rc.top + rc.bottom) / 2,
ETO_OPAQUE,
NULL,
pszText,
ATL::lstrlen(pszText),
NULL);
#endif
if (bSelectOldRgn) {
SelectClipRgn(hdc, hRgnOld);
}
EndPaint(hWnd, &ps);
}
break;
}
#endif /* WE_UNDER_WINDOWS */
case WM_SUCCESS:
case WM_ERROR:
case WM_GETUSERMEDIA_SUCESS:
case WM_GETUSERMEDIA_ERROR:
case WM_CREATEOFFER_SUCCESS:
case WM_CREATEOFFER_ERROR:
case WM_ONNEGOTIATIONNEEDED:
case WM_ONICECANDIDATE:
case WM_ONSIGNALINGSTATECHANGE:
case WM_ONADDSTREAM:
case WM_ONREMOVESTREAM:
case WM_ONICECONNECTIONSTATECHANGE:
{
_BrowserCallback* _cb = reinterpret_cast<_BrowserCallback*>(wParam);
if (_cb) {
_cb->Invoke();
_cb->ReleaseObject();
}
break;
}
}
#if WE_UNDER_WINDOWS
return DefWindowProc(hWnd, uMsg, wParam, lParam);
#else
return 0;
#endif /* WE_UNDER_WINDOWS */
} |
75f6a7edf6bc30106d3ee29c349205ea52155fa7 | 49872bd87748ef3e371fa6be657b5d1e50579297 | /src/utils/ArgumentParser.cpp | 86ffc92ec3e48629250e042c9b6f1c94b4a36434 | [
"MIT"
] | permissive | alexws54tk/rubik | 6ecee9ce57d01d45e410574290b2b1512a300727 | 86bab6527583a545e13265412301742dcc7052da | refs/heads/master | 2020-04-05T18:29:36.006371 | 2015-06-14T18:13:23 | 2015-06-14T18:13:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,269 | cpp | ArgumentParser.cpp | /*
* Copyright (c) 2013 Pavlo Lavrenenko
*
* 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 "ArgumentParser.h"
#include <getopt.h>
#include <libgen.h> // basename()
#include <iomanip>
#include <sstream>
#include <vector>
#include <algorithm>
namespace Rubik {
namespace Utils {
bool ArgumentParser::addArgument(const std::string& longName, const std::string& description, ArgumentType type) {
auto status = std::find_if_not(longName.begin(), longName.end(), [](char c) -> bool {
return (std::isalnum(c) || c == '-');
});
if (status != longName.end()) {
return false;
}
if (this->arguments.find(longName) != this->arguments.end()) {
return false;
}
this->pushArgument(0, longName, description, type);
return true;
}
bool ArgumentParser::addArgument(char name, const std::string& longName,
const std::string& description, ArgumentType type) {
if (name < '0' || (name > '9' && name < 'A') || (name > 'Z' && name < 'a') || name > 'z') {
return false;
}
if (this->aliases.find(name) != this->aliases.end()) {
return false;
}
auto status = std::find_if_not(longName.begin(), longName.end(), [](char c) -> bool {
return (std::isalnum(c) || c == '-');
});
if (status != longName.end()) {
return false;
}
if (this->arguments.find(longName) != this->arguments.end()) {
return false;
}
this->pushArgument(name, longName, description, type);
this->aliases[name] = longName;
return true;
}
bool ArgumentParser::parse(int argc, char** argv) {
std::stringstream shortOptions;
std::vector<struct option> longOptions;
struct option longOption;
for (auto& argument: this->arguments) {
longOption.name = argument.first.c_str();
longOption.flag = nullptr;
longOption.val = 0;
longOption.has_arg = (argument.second->type == ArgumentType::TYPE_BOOL) ? no_argument : required_argument;
longOptions.push_back(longOption); // vector::emplace_back() kills gcc, how unfortunate
if (argument.second->shortOption) {
shortOptions << argument.second->shortOption;
if (argument.second->type != ArgumentType::TYPE_BOOL) {
shortOptions << ":";
}
}
}
int i = 0;
auto optionsArray = std::unique_ptr<struct option[]>(new struct option[longOptions.size() + 1]);
for (auto& option: longOptions) {
optionsArray[i++] = option;
}
optionsArray[i].name = nullptr;
optionsArray[i].flag = nullptr;
optionsArray[i].val = 0;
optionsArray[i].has_arg = no_argument;
int optionIndex = 0;
bool parseFailed = false;
std::shared_ptr<Argument> argument;
int option;
while ((option = getopt_long(argc, argv, shortOptions.str().c_str(), optionsArray.get(), &optionIndex)) != -1) {
switch (option) {
case 0:
argument = this->arguments.at(optionsArray[optionIndex].name);
if (optionsArray[optionIndex].has_arg != no_argument) {
if ((parseFailed = !this->validate(argument, optarg)) == false) {
argument->value = optarg;
argument->set = true;
}
} else {
argument->set = true;
}
break;
default:
auto alias = this->aliases.find(option);
if (alias != this->aliases.end()) {
argument = this->arguments.at(alias->second);
if (argument->type != ArgumentType::TYPE_BOOL) {
if ((parseFailed = !this->validate(argument, optarg)) == false) {
argument->value = optarg;
argument->set = true;
}
} else {
argument->set = true;
}
} else {
parseFailed = true;
}
}
if (parseFailed) {
break;
}
}
if (!parseFailed && optind < argc) {
parseFailed = true;
}
if (this->isSet("version")) {
this->printVersion();
} else if (this->isSet("help") || parseFailed) {
this->printHelp(basename(argv[0]));
}
return !parseFailed;
}
void ArgumentParser::printHelp(char* application) const {
std::cout << "Usage: " << application << " [option]..." << std::endl;
if (!this->description.empty()) {
std::cout << this->description << std::endl;
}
std::cout << std::endl << "Available options:" << std::endl;
for (auto& argument: this->arguments) {
std::stringstream option;
if (argument.second->shortOption) {
option << std::setw(5) << "-" << argument.second->shortOption << ", --";
} else {
option << std::setw(10) << "--";
}
std::stringstream longName;
longName << argument.first;
switch (argument.second->type) {
case ArgumentType::TYPE_INT:
longName << "=[int]";
break;
case ArgumentType::TYPE_FLOAT:
longName << "=[float]";
break;
case ArgumentType::TYPE_STRING:
longName << "=[string]";
break;
default:
break;
}
std::cout << option.str()
<< std::left << std::setw(25) << longName.str()
<< argument.second->description << std::endl;
}
}
bool ArgumentParser::validate(const std::shared_ptr<Argument>& argument, const char* value) const {
std::stringstream testValue(value);
int intValue;
float floatValue;
switch (argument->type) {
case ArgumentType::TYPE_FLOAT:
testValue >> std::noskipws >> floatValue;
break;
case ArgumentType::TYPE_INT:
testValue >> std::noskipws >> intValue;
break;
default:
return true;
}
return (testValue.eof() && !testValue.fail());
}
} // namespace Utils
} // namespace Rubik
|
cf08105d0334281164bb202be01059361ea14908 | 47c5c5b194dff3fb8a95721effc599591e90519a | /solved/1600.cpp | 1819653445495e34186f80280812b83b8f3b0f6f | [] | no_license | LEECHHE/acmicpc | 75ba56e3cd7a2d8d9c43f83e151632a58823840f | 8717bc33b53ac44037d9f58ee1d0b58014084648 | refs/heads/master | 2020-04-06T06:57:07.679362 | 2018-12-10T09:12:06 | 2018-12-10T09:12:06 | 65,816,339 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,644 | cpp | 1600.cpp | #include<iostream>
#include<queue>
using namespace std;
typedef pair<int, int> intPair;
typedef pair<intPair, int> State;
int k, w, h;
int grid[205][205];
int visited[205][205][35] = { 0 };
int dx[12] = { 0, 0, 1, -1 , 2, 2, 1, 1, -1, -1, -2, -2};
int dy[12] = { 1, -1, 0, 0 , 1, -1, 2, -2, 2, -2, 1, -1};
bool isValid(int x, int y) {
return 0 <= x && x < h && 0 <= y && y < w;
}
int main() {
scanf("%d", &k);
scanf("%d%d", &w, &h);
for (int i = 0 ; i < h ; ++i) {
for( int j = 0 ; j < w ; ++j) {
scanf("%d", &grid[i][j]);
for ( int k = 0 ; k < 35 ; ++k) {
visited[i][j][k] = grid[i][j] ? -1 : INT_MAX;
}
}
}
queue<State> q;
q.push(State(intPair(0, 0), k));
visited[0][0][k] = 0;
int step = 0;
int answer = -1;
while(!q.empty()) {
int count = q.size();
for (int i = 0 ; i < count ; ++i) {
State curState = q.front();
q.pop();
intPair curPos = curState.first;
int jumpRemain = curState.second;
printf("State(%d,%d)%d\n", curPos.first, curPos.second, jumpRemain);
if (curPos.first == h - 1 && curPos.second == w - 1) {
answer = step;
break;
}
for (int d = 0 ; d < 12 ; ++d) {
int nextX = curPos.first + dx[d];
int nextY = curPos.second + dy[d];
if (d >= 4 && jumpRemain <= 0) {
break;
}
if (!isValid(nextX, nextY)) {
continue;
}
int jumpIndex = jumpRemain - (d >= 4);
if (visited[nextX][nextY][jumpIndex] < INT_MAX) {
continue;
}
visited[nextX][nextY][jumpIndex] = step + 1;
q.push(State(intPair(nextX, nextY), jumpIndex));
}
}
if (answer >= 0) {
break;
}
++step;
}
printf("%d", answer);
return 0;
}
|
4deefb0fb07f723adfba79570191461a2f73a77e | 5c2fc684d83fdc984a84eef423341176481b2f32 | /VisualProjects/MiaInterface/MiaInterface.cpp | f6742cdf7e3ef10c90ee5fff7de40fc23f92176a | [] | no_license | InsanePony/Mia | e4d2c65a31b5b1abee0445277873b8ebf75851f7 | c06ef45d9d33985886cc4217485bb967f52b3d87 | refs/heads/master | 2021-09-14T21:00:08.915610 | 2018-05-19T14:11:48 | 2018-05-19T14:11:48 | 105,539,141 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,239 | cpp | MiaInterface.cpp | #include <functional>
#include "MiaInterface.h"
#include "DataLoader.h"
#include "DialogNetworkCreation.h"
#include "Utils.h"
#include "qfiledialog.h"
#include "qmessagebox.h"
MiaInterface::MiaInterface(QWidget *parent)
: QMainWindow(parent)
{
ui.setupUi(this);
m_pNetwork = nullptr;
m_pDigitDrawer = new DigitDrawer(this);
DataLoader* loader = new DataLoader();
std::string path;
if (Utils::IsInVisual())
path = "../..";
else
path = Utils::GetExePath();
std::vector<std::array<std::vector<double>, 2>> data = loader->LoadData(path + "/MNIST data/train-data-pixels-value", path + "/MNIST data/train-data-numbers", 60000);
m_vavdTrainData = std::vector<std::array<std::vector<double>, 2>>(data.begin(), data.begin() + 50000);
m_vavdEvaluationData = std::vector<std::array<std::vector<double>, 2>>(data.begin() + 50000, data.end());
m_vavdTestData = loader->LoadData(path + "/MNIST data/test-data-pixels-value", path + "/MNIST data/test-data-numbers", 10000);
for (int idx = 0; idx < 60000; ++idx)
m_vvdDigits.push_back(data[idx][0]);
for (int idx = 0; idx < 10000; ++idx)
m_vvdDigits.push_back(m_vavdTestData[idx][0]);
m_pDigitViewer = new DigitViewer(ui.digit);
m_pDigitViewer->ShowDigit(m_vavdTrainData[0][0]);
m_pMiaResponse = new DigitViewer(ui.miaResponse);
m_pAskMiaButton = ui.askMiaButton;
QObject::connect(ui.digitSpinBox, static_cast<void(QSpinBox::*)(int)>(&QSpinBox::valueChanged), this, &MiaInterface::ChangeDigit);
QObject::connect(ui.actionNewNetwork, &QAction::triggered, this, &MiaInterface::CreateNetwork);
QObject::connect(ui.actionLoadNetwork, &QAction::triggered, this, &MiaInterface::LoadNetwork);
QObject::connect(ui.actionNewEntry, &QAction::triggered, this, &MiaInterface::NewEntry);
QObject::connect(ui.askMiaButton, &QPushButton::pressed, this, &MiaInterface::AskMia);
QObject::connect(m_pDigitDrawer, &DigitDrawer::EntryFinished, this, &MiaInterface::TestNewEntry);
}
MiaInterface::~MiaInterface()
{
if (m_pNetwork)
delete m_pNetwork;
delete m_pDigitDrawer;
delete m_pDigitViewer;
delete m_pMiaResponse;
}
void MiaInterface::CreateNetwork()
{
QMessageBox::StandardButton saveFileQuestion = QMessageBox::question(this, "Mia Interface", "Save Network after ?", QMessageBox::Yes | QMessageBox::No);
DialogNetworkCreation dialog(this, saveFileQuestion == QMessageBox::Yes);
if (dialog.exec() == QDialog::Accepted)
{
dialog.hide();
m_pAskMiaButton->setEnabled(false);
#undef GetForm
m_pNetwork = new Network(dialog.GetForm(), dialog.GetFileName());
m_pNetwork->OnLearningEnd(std::bind(&MiaInterface::NetworkFinishLearningPhase, this));
m_pNetwork->StartLearning(m_vavdTrainData, dialog.GetNumberGenerations(), dialog.GetLearningRate(), dialog.GetBatchSize(), (dialog.GetTrackProgress()) ? m_vavdTestData : std::vector<std::array<std::vector<double>, 2>>());
}
}
void MiaInterface::LoadNetwork()
{
QString filePath = QFileDialog::getOpenFileName(this, "Open Network file", QDir::homePath(), "Network file (*.mia)");
if (filePath.size() > 0)
{
m_pNetwork = new Network(new NetworkLoader(filePath.toLatin1().constData()));
m_pAskMiaButton->setEnabled(true);
}
}
void MiaInterface::NewEntry()
{
m_pDigitDrawer->Show();
}
void MiaInterface::TestNewEntry(QImage* image)
{
if (m_pAskMiaButton->isEnabled())
{
QImage forMiaImage = image->scaled(28, 28, Qt::AspectRatioMode::IgnoreAspectRatio, Qt::TransformationMode::FastTransformation);
std::vector<double> imageAsData;
imageAsData.resize(784);
for (int idx = 0; idx < 784; ++idx)
{
int rowIdx = idx / 28;
int columnIdx = idx % 28;
imageAsData[idx] = (255 - forMiaImage.pixelColor(columnIdx, rowIdx).red()) / 255.0;
}
m_pMiaResponse->ShowDigit(m_pNetwork->GetResponse(imageAsData));
}
}
void MiaInterface::ChangeDigit(int value)
{
m_pDigitViewer->ShowDigit(m_vvdDigits[value]);
currDigitIndex = value;
}
void MiaInterface::AskMia()
{
m_pMiaResponse->ShowDigit(m_pNetwork->GetResponse(m_vvdDigits[currDigitIndex]));
}
void MiaInterface::NetworkFinishLearningPhase()
{
QMessageBox::StandardButton networkFinishInformation = QMessageBox::information(this, "Mia Interface", "Learning phase finished", QMessageBox::Ok);
m_pAskMiaButton->setEnabled(true);
}
|
42428be8f4aada12070a1c6be24ddacd7e0f441e | 009cca46aed9599d633441b044987ae78b60685a | /src/QweakSimUserCerenkov_MainEvent.cc | 1ff9c6d18644768dda409cc6d18e4624a81ce7a0 | [] | no_license | cipriangal/QweakG4DD | 0de40f6c2693021db44916e03d8d55703aa37387 | 5c8f55be4ba0ec3a3898a40c4e1ff8eb42c550ad | refs/heads/master | 2021-01-23T10:29:53.163237 | 2018-06-25T19:03:24 | 2018-06-25T19:03:24 | 29,534,503 | 0 | 4 | null | 2017-03-27T21:06:14 | 2015-01-20T14:45:37 | C++ | UTF-8 | C++ | false | false | 1,620 | cc | QweakSimUserCerenkov_MainEvent.cc | //=============================================================================
//
// ---------------------------
// | Doxygen File Information |
// ---------------------------
//
/**
\file QweakSimUserCerenkov_MainEvent.cc
$Revision: 1.2 $
$Date: 2005/12/27 19:16:49 $
\author Klaus Hans Grimm
*/
//=============================================================================
//=============================================================================
// -----------------------
// | CVS File Information |
// -----------------------
//
// Last Update: $Author: grimm $
// Update Date: $Date: 2005/12/27 19:16:49 $
// CVS/RCS Revision: $Revision: 1.2 $
// Status: $State: Exp $
//
// ===================================
// CVS Revision Log at end of file !!
// ===================================
//
//============================================================================
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo....
#include "QweakSimUserCerenkov_MainEvent.hh"
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo....
ClassImp(QweakSimUserCerenkov_MainEvent)
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo....
QweakSimUserCerenkov_MainEvent::QweakSimUserCerenkov_MainEvent()
{
//Octant.clear();
//Octant.resize(8);
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo....
QweakSimUserCerenkov_MainEvent::~QweakSimUserCerenkov_MainEvent()
{;}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo....
|
a51e6d9d315d019cc724ad48fab97731ea3b524f | bbcf9a3dbca573d4c123ddca5dc359aa39ebecc6 | /Advanced Classes Project/Project V/Part IV/CourseGrades.h | e6cdf53302cc19672e0ec3d3f606b86ad4089a23 | [] | no_license | Darosan404/CPP | 1d5c623d5735b19704f5d60cc57535554ff6cc23 | 5bc55c7cb126c1efee6cd589724f1a95fbd7c98d | refs/heads/main | 2023-04-22T23:14:59.862063 | 2021-05-05T02:15:16 | 2021-05-05T02:15:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 348 | h | CourseGrades.h | #ifndef COURSEGRADES_H
#define COURSEGRADES_H
class CourseGrades
{
public:
CourseGrades();
~CourseGrades();
void setLab(int index, GradedActivity lab);
void setPassFailExam(int index, PassFailExam passFailExam);
void setEssay(int index, GradedActivity essay);
void setFinalExam(int index, FinalExam finalExam);
protected:
};
#endif
|
9b8aeb0d489aa44be327d443b44ba3a8a7b95128 | 69a81ce2bad77fac0a19575573f79f26cb179ef4 | /Number/number_ruleplusplus.cpp | 6b13ecc174b07bf1cfbc9041ebf17319337e47a8 | [] | no_license | fezvez/DSN4 | 0965ac3bd17bc1ec192d75d29adb1bb2da21a0ba | 94048672b1cc98835d22e1a0fd4700e0862d81c0 | refs/heads/master | 2021-01-10T22:28:39.472976 | 2016-02-13T07:42:48 | 2016-02-13T07:42:48 | 30,161,901 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,552 | cpp | number_ruleplusplus.cpp | #include "number_ruleplusplus.h"
#include <QDebug>
Number_RulePlusPlus::Number_RulePlusPlus(NRelation h, QList<NRelation> b):Number_Rule(h,b)
{
unifyVariables();
}
void Number_RulePlusPlus::unifyVariables(){
mapString2Variables.clear();
unifyVariables(head);
for(NRelation relation : body){
unifyVariables(relation);
}
}
void Number_RulePlusPlus::unifyVariables(NRelation relation){
QList<NTerm> body = relation->getBody();
int size = body.size();
for(int i=0; i<size; ++i){
NTerm term = body[i];
NVariable variable = term.staticCast<Number_Variable>();
if(variable){
NVariable newVariable = insertVariable(variable);
body[i] = newVariable.dynamicCast<Number_Term>();
continue;
}
NConstant constant = term.staticCast<Number_Constant>();
if(constant){
continue;
}
NFunction function = term.staticCast<Number_Function>();
if(function){
unifyVariables(function);
continue;
}
Q_ASSERT(false);
}
}
void Number_RulePlusPlus::unifyVariables(NFunction function){
QList<NTerm> body = function->getBody();
int size = body.size();
for(int i=0; i<size; ++i){
NTerm term = body[i];
NVariable variable = term.staticCast<Number_Variable>();
if(variable){
NVariable newVariable = insertVariable(variable);
body[i] = newVariable.dynamicCast<Number_Term>();
continue;
}
NConstant constant = term.staticCast<Number_Constant>();
if(constant){
continue;
}
NFunction subFunction = term.staticCast<Number_Function>();
if(subFunction){
unifyVariables(subFunction);
continue;
}
Q_ASSERT(false);
}
}
NVariable Number_RulePlusPlus::insertVariable(NVariable variable){
QString name = variable->toString();
if(mapString2Variables.contains(name)){
return mapString2Variables[name];
}
mapString2Variables[name] = variable;
return variable;
}
NRelation Number_RulePlusPlus::getFirstUngroundedRelation(){
for(NRelation relation : body){
bool isGround = relation->isGround();
if(isGround){
continue;
}
return relation;
}
Q_ASSERT(false);
}
void Number_RulePlusPlus::debug(){
qDebug() << "Debug RulePP";
for(QString string : mapString2Variables.keys()){
qDebug() << "\t" << string;
}
}
|
c4c2520c56354f056874096528ccdd19a1886475 | 142d4891e3d1d732bacac9abea0381733c05a494 | /RayTracer/RayTracer/Camera.cpp | 0b1aa99bc664ec9e929ab3549c807f05bb8aea8e | [] | no_license | wr4909/RayTracer | d88ebeb02ac36bb7526abdeea6a7e38660f2a6ba | b11781efd8743fc67131f324e64b07fcf29bf8ed | refs/heads/master | 2016-09-12T01:27:39.549372 | 2016-05-02T15:27:54 | 2016-05-02T15:27:54 | 51,008,348 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,256 | cpp | Camera.cpp | // #419begin #type=3 #src=http://www.raytracegroundup.com/downloads/
#include "Camera.hpp"
#include "World.hpp"
#include <stdio.h>
Camera::Camera(){
eye(0, 0, 500);
lookat(0, 0, 0);
ra = 0.0;
up(0, 1, 0);
u(1, 0, 0);
v(1, 0, 0);
w(0, 0, 1);
updateViewPlane();
}
Camera::Camera(Camera& c){
eye(c.eye);
lookat(c.lookat);
ra = c.ra;
up(c.up);
u(c.u);
v(c.v);
w(c.w);
updateViewPlane();
}
Camera::~Camera(){
}
Camera&
Camera::operator= (Camera& rhs){
if (this == &rhs)
return (*this);
eye = rhs.eye;
lookat = rhs.lookat;
ra = rhs.ra;
up = rhs.up;
u = rhs.u;
v = rhs.v;
w = rhs.w;
return (*this);
}
void
Camera::compute_uvw(){
w = eye - lookat; //w is opposite of view plane
w.normalize();
u = up.cross(w).hat();
v = w.cross(u);
if (eye.x == lookat.x && eye.z == lookat.z){
if (eye.y > lookat.y){
u = Vector3D(0, 0, 1);
v = Vector3D(1, 0, 0);
w = Vector3D(0, 1, 0);
}
if (eye.y < lookat.y){
u = Vector3D(1, 0, 0);
v = Vector3D(0, 0, 1);
w = Vector3D(0, -1, 0);
}
}
}
// #419end
void Camera::updateViewPlane(){
viewPlane(Point3D(0,0,0),Vector3D(1024,0,0),Vector3D(0,1024,0),1024,1024);
}
void Camera::render_scene(World& world, PNG& image){
double rayCount = 0;
double totalCount = image.width()*image.height();
GeometricObject* object = NULL;
RGBAPixel pixelColor(255,255,255);
for(int i = 0; i < image.width(); i++){
for(int j = 0; j < image.height(); j++){
Ray viewRay(eye,Vector3D(eye,viewPlane.getPoint(i,j)),"view"); //from eyePt to viewPlane
Point3D hitPt;
object = world.getFirstObjectHit(viewRay,world.shapes,hitPt);
if(object != NULL)
pixelColor = object->rayTrace(world.ptLight, hitPt, viewRay,world.shapes);
*image(i,j) = pixelColor;
pixelColor(255,255,255);
object = NULL;
rayCount ++;
cout << rayCount / totalCount * 100 << endl;
}
}
world.rayCount += (int)rayCount;
} |
86c0e04e83a5bb616768e273b616285fae542db6 | 772d932a0e5f6849227a38cf4b154fdc21741c6b | /CPP_Joc_Windows_Android/SH_Client_Win_Cpp_Cmake/App/src/sh/scenarios/startarea_a_v1/gw/view/mainui/MainInGameUIView.cpp | 1e09be9b0193391be45b700c4a89e0aecf3b4e50 | [] | no_license | AdrianNostromo/CodeSamples | 1a7b30fb6874f2059b7d03951dfe529f2464a3c0 | a0307a4b896ba722dd520f49d74c0f08c0e0042c | refs/heads/main | 2023-02-16T04:18:32.176006 | 2021-01-11T17:47:45 | 2021-01-11T17:47:45 | 328,739,437 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 870 | cpp | MainInGameUIView.cpp | #include "MainInGameUIView.h"
#include <base/util/AppStyles.h>
#include <base/menu/util/MenuItemConfig_Visual.h>
#include <base/menu/util/MenuItemConfig_Data.h>
#include <base/visual2D/util/VCC_Group.h>
#include <base/visual2D/util/VCC_Sprite.h>
#include <base/visual2D/util/VCC_TouchArea.h>
#include <base/exceptions/LogicException.h>
#include <functional>
#include <base/statics/StaticsInit.h>
using namespace startarea_a_v1;
ArrayList<MenuItemConfig*>* MainInGameUIView::viewItemConfigs = base::StaticsInit::AddCbGeneral<ArrayList<MenuItemConfig*>*>(1, []() {
viewItemConfigs = (new ArrayList<MenuItemConfig*>())
->appendDirect_chain(super::viewItemConfigs);
});
MainInGameUIView::MainInGameUIView(IApp* app, base::IGameWorld* gw)
: super(app, viewItemConfigs, viewAnimationDurations, gw)
{
//void
}
MainInGameUIView::~MainInGameUIView() {
//void
}
|
85deae07cd3a7807bb2f431789cc87a301b011a2 | f96901169a6960ca236660b6f50a7fd95daadbce | /Urvashi/milestone-03&04(while loops)/sum of all prime numbers from 1 to n.cpp | 13bcc66d3bc98f9feb5ee1cb971de47b3b5e2fad | [] | no_license | HarpreetSinghNagi/Beginner-CPP-Submissions | a8f1c20b13d4cd3bc6a1894235f21581e10fe52f | 862ca6b1cab311cec05e7405dba5488871adb434 | refs/heads/master | 2022-12-15T03:12:15.209979 | 2020-09-05T15:28:27 | 2020-09-05T15:28:27 | 271,482,952 | 1 | 0 | null | 2020-06-11T07:40:17 | 2020-06-11T07:40:16 | null | UTF-8 | C++ | false | false | 331 | cpp | sum of all prime numbers from 1 to n.cpp | #include<iostream>
using namespace std;
int main ()
{
int num , i , end, sum=0 , isprime;
cout<<"print all prime numbers from 1 to n "<<endl;
cin >>end;
for(i=2; i<=end;i++)
{
isprime=1;
for(num=2; num<=i/2; num++)
{
if(i%num==0)
isprime=0;
}
if(isprime==1)
sum+=i;
}
cout<<"sum of all prime numbers from 1 to n is"<<sum;
}
|
a2f7ae317b3f9bc54dd7f519962e9d4d32c88e51 | 87b5a05f3ea591b761791f88e342f7a8ecf94750 | /Editor/input.h | 4051ba4090bbbdb2e245b925b7d9ccb3821c8618 | [] | no_license | JoAlvarez/Magnetic | 48ed1265621c7d8477b416d9b51b4430235c062e | c2e5b00b63768a67050cc5dd41a89c76a8d49f91 | refs/heads/master | 2020-05-03T20:19:56.551582 | 2012-09-10T02:37:35 | 2012-09-10T02:37:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,820 | h | input.h | ///@file
///@brief File for the Input class.
///
/// This will be able to handle all the forms of input:
///
/// Buffered and unbuffered Keyboard input, Mouse tracking,
/// and joystick inputs.
///
///Copyright 2008, Roby Atadero
///
///Please give credit if using this in your software.
///
///@author Roby Atadero
///@version 0.70
///@date 2008
///@addtogroup userclasses User Classes
///All classes that the programmer will directly use.
///@{
#ifndef __INPUT_H__
#define __INPUT_H__
#include <SDL/SDL.h>
#include <vector>
#include <string>
#include <map>
#include "window.h"
#include "joystick.h"
#include "point.h"
using namespace std;
///@brief Class that handles the input.
///
/// This will take care of all the input checking and handling.
class Input
{
private:
static Input* instance; //Singleton pointer to the
//Input object.
static int referenceCount; //Number of things that currently
//have the singleton pointer available.
SDL_Event event; //Event variable that holds
//events to be processed.
bool mouseLeftDown; //Is left mouse down.
bool mouseRightDown; //Is right mouse down.
bool mouseMiddleDown; //Is middle mouse down.
double mouseXlocation;
double mouseYlocation;
double mouseXMoveRelative; //Tracks relative mouse x
//movement.
double mouseYMoveRelative; //Tracks relative mouse y
//movement.
int mouseScrollRelative; //Tracks relative mouse
//scroll movement.
std::string keyInput; //Holds the keyboard input.
std::string joyInput; //Holds the joystick input.
std::string mouseInput; //Holds the mouse input.
int numJoysticks; //Holds the number of
//joysticks detected.
std::vector<Joystick> joystick; //Vector that holds all the
//detected joysticks.
std::map<std::string, SDLKey> keyMap; //Map that corrolates key
//presses to SDLKeys.
Window* window; //Singleton pointer to the
//Window object.
/// @brief Default constructor for the Input class.
Input();
/// @brief Initializes the Input object to be used.
void init();
/// @brief Destroys and frees all the memory from this class.
void destroy();
public:
/// @brief Gets the instance of the Input object.
///
/// Use this to obtain the instance of the input object for the window.
/// @return Input* A pointer to the instance of the Input object.
static Input* getInstance();
/// @brief Releases the instance of the Input object obtained.
///
/// Release the instance of the Input obtained from getInstance().
/// This must be called on the pointer obtained from getInstance() to
/// ensure that no memory leaks occur and that the Input object is
/// destroyed when nobody has an instance of the object.
void release();
/// @brief Will handle all events that have occured
///
/// Will handle all of the events that have occured since last calling
/// this function. This must be called to ensure that tracking of the
/// mouse pointer is done as well as recieving all of the buffered keyboard
/// input. If false has been returned, then the program has been asked to be quit.
/// @return bool True means the program is doing fine and false means the program has been
/// asked to be quit. If false was returned, the programmer must quit the program
/// to ensure that the program quits when asked to.
bool handleEvents();
/// @brief Clears all the values in the input variables.
///
/// Will reset all of the calculated inputs in handleEvents back to
/// cleared. This must be called at the end of the simulation loop to
/// make sure that a certain input is not seen to have been pressed
/// when actually it was pressed along time ago in the passed.
void resetInput();
/// @brief Checks to see if a keyboard key is pressed.
///
/// Will return whether or not a certain key is being pressed.
/// @param key The string value of the key in question.
/// Example: "a" => A key, "esc" => esc key, "space" => space key
/// @return bool Whether or not the key in question is pressed.
bool isKeyDown(std::string key);
/// @brief Checks to see if a certain joystick button is pressed.
///
/// Returns whether or not a certain joystick button is down.
/// @param joyButton The joystick button in question. Must be in the
/// format "Joy# But#". So "Joy0 But5" is asking whether or not button
/// 5 on joystick 0 is being pressed.
/// @return bool Whether or not that button was down.
bool isJoyButtonDown(std::string joyButton);
/// @brief Checks to see if a hat direction is being pressed.
///
/// Returns whether or not a certain direction on the hat is down.
/// @param joyHatDir The hat direction in question. Must be in the format
/// "Joy# Hat'Dir'". So "Joy2 HatLEFT" is asking whether or not the left
/// direction is being pressed on the hat of joystick 2.
/// @return bool Whether or not that hat direction is being pressed.
bool isHatDirPressed(std::string joyHatDir);
/// @brief Sees how far in either direction a certain axis on an analog stick is being pressed.
///
/// Returns a percentage of how far a certain analog axis is being pressed. The returned value will
/// be between 1.0 and -1.0.
/// @param joystickNum Which joystick in question.
/// @axisNum The analog axis in question. X_AXIS_LEFT means the X axis
/// of the left analog stick. Y_AXIS_RIGHT means the Y axis of the
/// right analog stick. Etc.
/// @return double The percentage of how far that joystick is being
/// pressed in the given axis. Ranges in between 1.0 and -1.0. 0.0
/// means it is in the center.
double getJoystickAxisPos(int joystickNum, int axisNum);
/// @brief Gets the value of the buffered keyboard input.
///
/// Returns the string value of the key that was pressed in the
/// buffered input. Use this function instead of isKeyDown for
/// things where you just want to know if that key was pressed
/// down at that instant. Such examples might be for typing input
/// or moving through a menu in a game.
/// @return string The key that was being pressed if any. Empty string returned if no key was pressed.
std::string getKeyInput();
/// @brief Gets the value of the joystick input.
///
/// Returns the string value of the joystick button or hat direction
/// that was hit at that instant if any.
/// @return string The string that represents what joystick input was
/// recieved. Will be in the form "Joy# But#" or "Joy# Hat'Dir'".
/// Examples: "Joy3 But1" or "Joy2 HatCENTERED" or "Joy4 HatDOWN".
std::string getJoyInput();
/// @brief Gets the value of the mouse input.
///
/// Returns the string value of what mouse buttons were hit or released
/// at that instanct if any.
/// @return string The string that represents what mouse button was hit
/// or released. Example: "Left Down" means that left mouse click was
/// pressed down. "Right Up" means the right mouse click was just released.
std::string getMouseInput();
/// @brief Gets the value of how far the mouse moved in the X during the last frame.
///
/// Returns how far the mouse moved in the X direction in the last frame.
/// Will be relevant to the coordinate system that is being used at the time.
/// @return double How far the mouse moved in the X direction during the last frame.
double getMouseXRel();
/// @brief Gets the value of how far the mouse moved in the Y during the last frame.
///
/// Returns how far the mouse moved in the Y direction in the last frame.
/// Will be relevant to the coordinate system that is being used at the time.
/// @return double How far the mouse moved in the Y direction during the last frame.
double getMouseYRel();
/// @brief Whether or not the left mouse button is down.
///
/// Will return whether or not the left mouse button is currently being pressed.
/// @return bool Whether or not it is being pressed.
bool leftMouseDown();
/// @brief Whether or not the right mose button is down.
///
/// Will return whether or not the right mouse button is currently being pressed.
/// @return bool Whether or not it is being pressed.
bool rightMouseDown();
/// @brief Gets the current X location of the mouse in the coordinate system.
///
/// Returns at what specific location the mouse is at in the current coordinate system.
/// @return double The X value of the location of the mouse.
double getMouseXloc();
/// @brief Gets the current Y location of the mouse in the coordinate system.
///
/// Returns at what specific location the mouse is at in the current coordinate system.
/// @return double The Y value of the location of the mouse.
double getMouseYloc();
/// @brief Gets the current point location of the mouse in the coordinate system.
///
/// Returns at what specific location the mouse is at in the current coordinate system.
/// @return Point The Point value of the location of the mouse.
Point getMouseLoc();
/// @brief Gets the percentage of how far the x of the mouse is on the screen.
///
/// Returns the percentage of how far right the x of the mouse is on the screen.
/// 0.0 means the mouse is on the far left of the screen. 1.0 means its on the far right.
/// 0.5 means it is in the middle.
/// @return double The percentage of how far the x of the mouse is on the screen. Ranges from 0.0 to 1.0.
double getMouseXPercentage();
/// @brief Gets the percentage of how far the y of the mouse is on the screen.
///
/// Returns the percentage of how far verticle the y of the mouse is on the screen.
/// 0.0 means the mouse is on the bottom of the screen. 1.0 means its on the top.
/// 0.5 means it is in the middle.
/// @return double The percentage of how far the y of the mouse is on the screen. Ranges from 0.0 to 1.0.
double getMouseYPercentage();
/// @brief Sets the x mouse coordinate to the given value.
///
/// This should not be used by the programmer. This is specifically used
/// by the input class and window class when changing coordinate systems.
/// @param mouseX The new x mouse location.
void setMouseX(double mouseX);
/// @brief Sets the y mouse coordinate to the given value.
///
/// This should not be used by the programmer. This is specifically used
/// by the input class and window class when changing coordinate systems.
/// @param mouseY The new y mouse location.
void setMouseY(double mouseY);
};
#endif
///@}
|
63ffffc8fa8978a45986d17dfc65368096d4223a | c4d2f6d4d5ce480d2d9160f8850a18cda1c45745 | /cstack.h | 912a3185675a128e45da8355c7e0ee3e5dd4372b | [] | no_license | caleb-clark/cstack | e92d71f598505d04d8214e08bb3babc13586bed5 | 2748f289e44ccc36d743aa36a2d26f738e3888e1 | refs/heads/master | 2021-01-19T20:36:33.652800 | 2017-03-05T22:42:05 | 2017-03-05T22:42:05 | 83,759,546 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,327 | h | cstack.h | #pragma once
#include <iostream>
#include <string>
#include <climits>
#include <cstring>
#include "linked_list.h"
template <class T>
class cstack
{
private:
linked_list * l;
int size_;
public:
//constructor
cstack();
//destructor
~cstack();
//copy contructor
cstack(const cstack<T> & cs);
//copy assignment operator
cstack & operator=(const cstack<T> & cs);
//push element onto stack
bool push(const T & elem);
//remove top element from stack
T pop();
//returns value of top element
T top();
//returns size of stack
int size();
};
//constructor
template <typename T>
cstack<T>::cstack()
{
size_ = 0;
l = new linked_list();
l->Init(8*(sizeof(T)+sizeof(node)),sizeof(T)+sizeof(node));
}
//destructor
template <typename T>
cstack<T>::~cstack()
{
delete l;
l = NULL;
}
//copy contructor
template <typename T>
cstack<T>::cstack(const cstack<T> & cs)
{
l = cs;
}
//copy assignment operator
template <typename T>
cstack<T> & cstack<T>::operator=(const cstack<T> & cs)
{
l = cs;
}
//push element onto stack
template <typename T>
bool cstack<T>::push(const T & elem)
{
T tmp = elem;
T * ptr = &tmp;
l->Insert(size_, (char*)ptr, sizeof(elem));
size_++;
return true;
}
//remove top element from stack
template <typename T>
T cstack<T>::pop()
{
if (size_ < 1) {
std::cout << "No elements to pop" << std::endl;
return T();
}
node * n = l->getFreePointer();
n++;
T * tmp = (T*)n;
if (l->RemoveLast()){
size_--;
return *tmp;
} else {
return T();
}
}
//returns value of top element
template <typename T>
T cstack<T>::top()
{
if (size_ < 1) {
std::cout << "No elements" << std::endl;
return T();
}
node * n = l->getFreePointer();
// std::cout << sizeof(node) << std::endl;
n += sizeof(node);
T * tmp = (T*)n;
return *tmp;
}
template <typename T>
int cstack<T>::size()
{
return size;
}
|
13eabe5103b65aa64307eaa5cca9c966ba09fd64 | 832ee0652f623dadb67c479d6015e73034a5218b | /src/Lista.cpp | e823da7b7bf7dc0a4826ba19401a3171639a6f63 | [] | no_license | bukisha/Micro-kernel | b263a6eea0ec482b86ebf8d31c41cacf815c73ee | 89d16344f1e9223a21d72fbb3c82c2243943af6b | refs/heads/master | 2020-03-27T16:32:29.723845 | 2018-08-30T18:50:05 | 2018-08-30T18:50:05 | 146,790,515 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,918 | cpp | Lista.cpp | #include "Lista.h"
#include "PCB.h"
#include "System.h"
#include "lock.h"
Lista::Lista() {
lock;
first=last=0;
len=0;
unlock;
}
Lista::~Lista() {
lock;
Element* temp;
while(first!=0)
{
temp=first;
first=first->next;
delete temp;
len--;
}
unlock;
}
void Lista::put(PCB* p) {
lock;
Element* temp=new Element(p);
if(!first)
{
first=temp;
last=temp;
} else
{
last->next=temp;
temp->prev=last;
last=last->next;
}
len++;
unlock;
}
PCB* Lista::get() {
lock;
Element* temp=first;
PCB* old;
if(!first) return 0;
if(!(first->next))
{
temp=first;
old=temp->pcb; //obrati paznju ovde si drkao sa brisanjem tempa
first=last=0;
} else
{
temp=first;
old=temp->pcb;
first=first->next;
first->prev=0;
}
delete temp;
len--;
unlock;
return old;
}
int Lista::size() const {
return len;
}
void Lista::remove(ID id) {
lock;
Element* temp=first;
Element* old;
while(temp->pcb->myID!=id) {
temp=temp->next;
}
if(temp==first) {
old=temp;
first=first->next;
first->prev=0;
len--;
delete old;
unlock;
return;
}
if(temp!=first && temp!=last) {
old=temp;
Element* p=temp->prev;
Element* s=temp->next;
p->next=s;
s->prev=p;
len--;
delete old;
unlock;
return;
}
if(temp==last) {
old=temp;
last=last->prev;
last->next=0;
len--;
delete old;
unlock;
return;
}
}//end remove
void Lista::writeList() {
lock;
Element* t=first;
//printf("\nPOCETAK");
//cout<<"\n"<<t->pcb->myThread->getName()<<endl;
//printf("\nKRAJ");
if(t==0){
printf("\nLista prazna");
return;
}
printf("\nPOCETAK LISTE");
while(t!=0) {
cout<<"\n"<<t->pcb->myThread->getName()<<t->pcb->myThread->getId()<<"["<<t->pcb->sleepCNT<<"]"<<endl;
t=t->next;
}
printf("\nVelicina liste je: %d",size());
printf("\nKRAJ LISTE");
unlock;
} |
51b872636d3d8952bbb402cecd6ed9dc80a7d239 | 9d13d7fc23e96cb35ddc0f5bba309d0478b4a253 | /codeforces/problemset/1200A.cpp | 4fa6264a65dea28a0ac41366b2ec51f542420408 | [] | no_license | mayankDhiman/cp | 68941309908f1add47855bde188d43fe861b9669 | c04cd4aaff9cedb6328dff097675307498210374 | refs/heads/master | 2021-07-22T04:05:46.968566 | 2021-02-05T16:17:58 | 2021-02-05T16:17:58 | 241,451,797 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 749 | cpp | 1200A.cpp | #include <bits/stdc++.h>
using namespace std;
int main()
{
vector <int> ans(10, 0);
int n; cin >> n;
string a; cin >> a;
for (int i = 0; i < a.size(); i ++)
{
if (a[i] == 'L'){
for (int j = 0; j < 10; j ++){
if (ans[j] == 0){
ans[j] = 1;
break;
}
}
}
else if (a[i] == 'R'){
for (int j = 10; j >= 0; j --){
if (ans[j] == 0){
ans[j] = 1;
break;
}
}
}
else{
ans[a[i] - '0'] = 0;
}
}
for (int i = 0; i < 10; i ++){
cout << ans[i];
}
cout << "\n";
}
|
ca0ccb5d9bad4369b7d91cc8bf687833c4886c86 | f6f7caf4d42b9442e4664b856a4d2456603a4343 | /Source/Timeborne/InGame/Model/GameObjects/ObjectToNodeMapping/ObjectToNodeMapping.h | a4ac2025b9be8cef4d41ce673230f46948be81b3 | [] | no_license | TamasSzep/Timeborne | a8902c3fa5f6d4a87466c857679c7af19ba12e12 | 5966731443a042943ad2fc997fc71230a0e07315 | refs/heads/main | 2023-03-05T04:47:50.628254 | 2021-02-14T18:24:32 | 2021-02-14T18:24:32 | 326,774,530 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,376 | h | ObjectToNodeMapping.h | // Timeborne/InGame/Model/GameObjects/ObjectToNodeMapping/ObjectToNodeMapping.h
#pragma once
#include <Core/SingleElementPoolAllocator.hpp>
#include <Core/DataStructures/SimpleTypeVector.hpp>
#include <Timeborne/InGame/Model/GameObjects/GameObjectId.h>
#include <cassert>
#include <utility>
#include <vector>
class TerrainTree;
template <typename TKey, typename TData>
class ObjectToNodeMapping_IndexMapping
{
std::vector<Core::SimpleTypeVectorU<TData>> m_Mappings;
Core::IndexVectorU m_UnusedVectors;
Core::FastStdMap<TKey, unsigned> m_VectorIndices;
public:
void Add(TKey key, TData value)
{
auto sIt = m_VectorIndices.find(key);
if (sIt == m_VectorIndices.end())
{
unsigned mappingIndex;
if (m_UnusedVectors.IsEmpty())
{
mappingIndex = (unsigned)m_Mappings.size();
m_Mappings.emplace_back();
}
else
{
mappingIndex = m_UnusedVectors.PopBackReturn();
}
sIt = m_VectorIndices.insert(std::make_pair(key, mappingIndex)).first;
}
m_Mappings[sIt->second].PushBack(value);
}
void Remove(TKey key, TData value)
{
auto mappingIndex = m_VectorIndices[key];
auto& values = m_Mappings[mappingIndex];
auto countValues = values.GetSize();
for (unsigned i = 0; i < countValues; i++)
{
if (values[i] == value)
{
values.RemoveWithLastElementCopy(i);
break;
}
}
if (values.IsEmpty())
{
m_UnusedVectors.PushBack(mappingIndex);
m_VectorIndices.erase(key);
}
}
void Remove(TKey key)
{
auto mappingIndex = m_VectorIndices[key];
m_Mappings[mappingIndex].Clear();
m_UnusedVectors.PushBack(mappingIndex);
m_VectorIndices.erase(key);
}
void RemoveMappings(TKey key)
{
auto mappingIndex = m_VectorIndices[key];
m_Mappings[mappingIndex].Clear();
}
const Core::SimpleTypeVectorU<TData>* GetValues(TKey key) const
{
auto sIt = m_VectorIndices.find(key);
if (sIt == m_VectorIndices.end()) return nullptr;
return &m_Mappings[sIt->second];
}
};
template <typename TDerived>
class ObjectToNodeMapping
{
ObjectToNodeMapping_IndexMapping<unsigned, GameObjectId> m_NodeToObjectsMapping;
ObjectToNodeMapping_IndexMapping<GameObjectId, unsigned> m_ObjectToNodesMapping;
TDerived& Crtp()
{
return static_cast<TDerived&>(*this);
}
void AddMappings(GameObjectId objectId)
{
auto countNodeIndices = m_CurrentNodeIndices.GetSize();
for (unsigned i = 0; i < countNodeIndices; i++)
{
auto nodeIndex = m_CurrentNodeIndices[i];
m_NodeToObjectsMapping.Add(nodeIndex, objectId);
m_ObjectToNodesMapping.Add(objectId, nodeIndex);
}
}
void RemoveNodeToObjectMappings(GameObjectId objectId)
{
auto nodeIndices = m_ObjectToNodesMapping.GetValues(objectId);
assert(nodeIndices != nullptr);
auto countNodes = nodeIndices->GetSize();
for (unsigned i = 0; i < countNodes; i++)
{
m_NodeToObjectsMapping.Remove((*nodeIndices)[i], objectId);
}
}
protected:
Core::IndexVectorU m_CurrentNodeIndices;
const TerrainTree* m_TerrainTree = nullptr;
public:
explicit ObjectToNodeMapping(const TerrainTree& terrainTree)
: m_TerrainTree(&terrainTree)
{
}
void SetTerrainTree_KeepingMappings(const TerrainTree& terrainTree)
{
m_TerrainTree = &terrainTree;
}
template <typename... TArgs>
void AddObject(GameObjectId objectId, TArgs&&... args)
{
Crtp()._UpdateCurrentNodeIndices(objectId, std::forward<TArgs>(args)...);
AddMappings(objectId);
}
template <typename... TArgs>
void SetObject(GameObjectId objectId, TArgs&&... args)
{
Crtp()._UpdateCurrentNodeIndices(objectId, std::forward<TArgs>(args)...);
auto oldNodeIndices = m_ObjectToNodesMapping.GetValues(objectId);
assert(oldNodeIndices != nullptr);
if (*oldNodeIndices != m_CurrentNodeIndices)
{
RemoveNodeToObjectMappings(objectId);
m_ObjectToNodesMapping.RemoveMappings(objectId);
AddMappings(objectId);
}
}
void RemoveObject(GameObjectId objectId)
{
RemoveNodeToObjectMappings(objectId);
m_ObjectToNodesMapping.Remove(objectId);
}
const Core::SimpleTypeVectorU<GameObjectId>* GetObjectsForNode(unsigned nodeIndex) const
{
return m_NodeToObjectsMapping.GetValues(nodeIndex);
}
const Core::IndexVectorU* GetNodesForObject(GameObjectId objectId) const
{
return m_ObjectToNodesMapping.GetValues(objectId);
}
template <typename TFilter>
bool IsObjectColliding(GameObjectId objectId, bool assertExistingMapping, TFilter&& objectFilter) const
{
auto nodesPtr = GetNodesForObject(objectId);
assert(!assertExistingMapping || nodesPtr != nullptr);
if (nodesPtr != nullptr)
{
auto& nodes = *nodesPtr;
auto countNodes = nodes.GetSize();
for (unsigned i = 0; i < countNodes; i++)
{
auto objectIdsPtr = GetObjectsForNode(nodes[i]);
if (objectIdsPtr != nullptr)
{
auto& objectIds = *objectIdsPtr;
auto countObjects = objectIds.GetSize();
if (countObjects > 1) // The same object is always contained. Early-continue in most cases.
{
for (unsigned j = 0; j < countObjects; j++)
{
auto otherObjectId = objectIds[j];
if (otherObjectId != objectId && objectFilter(otherObjectId))
{
return true;
}
}
}
}
}
}
return false;
}
bool IsObjectColliding(GameObjectId objectId, bool assertExistingMapping) const
{
return IsObjectColliding(objectId, assertExistingMapping, [](GameObjectId otherObjectId) { return true; });
}
}; |
53e75bbebf77fc405b568a57670f32e94df79f67 | e140c1c7087d6a4e130ebde2ce7962c40ee7fd0c | /codeforces/490/C.cpp | aaac5fab66920a8f0e7f3317e5fe49ae21257eaa | [] | no_license | diptayan2k/CP-Submissions | 543ccf94b4d43b6f040f975ccce834e883a5efc7 | dc32f1dd474cf250f71795f991132f3d52cc1771 | refs/heads/master | 2023-02-05T15:26:51.480986 | 2018-07-03T14:25:00 | 2020-12-21T10:20:15 | 323,290,119 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,480 | cpp | C.cpp | #include <iostream>
#include<bits/stdc++.h>
#define ll long long int
#define lld long double
#define F first
#define S second
#define f(i,a,b) for(int i=a;i<=b;i++)
#define g(i,a,b) for(int i=a;i>=b;i--)
#define mp make_pair
#define pb push_back
#define mh make_heap
#define ph push_heap
#define pq priority_queue
#define bits(x) __builtin_popcountll(x)
#define op(x) cout<<"Case #"<<x<<": "
#define op1(x) cout<<"Scenario #"<<x<<": "
using namespace std;
const ll mod = 1000000007;
const ll INF = 1e18;
const int N = 21;
void solve(int t)
{
string s;
cin >> s;
ll a, b;
cin >> a >> b;
ll n = s.length();
ll pr[n + 1] = {0}, sf[n + 1] = {0};
ll power[n + 1];
power[0] = 1;
for (int i = 1; i <= n; i++) power[i] = (power[i - 1] * 10) % b;
for (int i = 1; i <= n; i++)
{
pr[i] = ((pr[i - 1] * 10) % mod + (s[i - 1] - '0')) % a;
}
sf[n] = (s[n - 1] - '0') % b;
for (int i = n - 1; i >= 1; i--)
sf[i] = ((power[n - i] * (ll)(s[i - 1] - '0')) % b + sf[i + 1]) % b;
for (int i = 1; i < n; i++)
{
if (pr[i] == 0 and sf[i + 1] == 0 and s[i] != '0')
{
cout << "YES" << endl;
cout << s.substr(0, i) << endl;
cout << s.substr(i, n - i) << endl;
return;
}
}
cout << "NO" << endl;
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
int t = 1;
//cin >> t;
for (int i = 1; i <= t; i++)
{
solve(i);
}
} |
72ab1ad3274102170577254033ad22bb5dccdccf | 30657278fc951ba486d782a0f89ade4fed3037f9 | /informatik3/words/main.cpp | d9cc6511aa499f5e58dae6952aae8f34b4b09041 | [] | no_license | mschaufe/FHGR | fe028793fb288439edc8fb4f9e5beb3a66173289 | 7d368b280eb65e72736ecfc0d91e9a88f8bc17bc | refs/heads/master | 2023-01-24T07:22:58.875767 | 2020-11-26T09:01:31 | 2020-11-26T09:01:31 | 153,422,956 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 295 | cpp | main.cpp | #include <iostream>
#include "dictionary.h"
int main()
{
try
{
Dictionary dict;
dict.loadFromFile("/usr/share/dict/words");
dict.checkFile("input.txt", "output.txt");
}
catch (std::exception &ex)
{
std::cout << "Something went wrong: " << ex.what() << std::endl;
}
return 0;
}
|
52fa977074f5a67af380ea03e6e184cad02d3f65 | 2b703dc1e5020bb408b2a6e57cc5b80edf98ae1a | /justChecking/Robot.cpp | be872d0c684b555ee019a84902385af8e75435c7 | [] | no_license | infiBoy/EshcerRoom | d32af21435a87b741fcdefadd41c3077ced68400 | c846bed8425a822daa600bccd52762e63a5a1e9a | refs/heads/master | 2016-08-05T08:14:12.512650 | 2014-12-27T10:02:25 | 2014-12-27T10:02:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,731 | cpp | Robot.cpp | #include "Robot.h"
#include "Robot.h"
#include "stdio.h"
#include <GL\glut.h>
#include "DataModel.h"
#define degree 0.0174532925 //1degree = (2pi / 360)radian
#include <math.h>
const Vec3d robotEyeOffset = Vec3d(0, 4.5, 0); //Vec3d(0.5,4,-2);
#define PI 3.14159265358979323846264
//Constructor to initiliaze the values
Robot::Robot()
{
//reset to default values
robot_Pos = Vec3d(-7, 1.3, 32); //this shouldn't be hard-coded , it's need to be able take those values in the arguments of the constructors
viewDirection = Vec3d(0, 0, 1);
viewHeadDirection = Vec3d(0, 0, -1);
up = Vec3d(0, 1, 0);
right = (right.cross(viewDirection, up)*-1);
//right.x = -4; //right.y = 0; //right.z = -15;
}
void Robot::draw()
{
GLfloat rotateAngle = (GLfloat)viewDirection.convertViewVectorToAngle(Vec3d(0, 0, 1) );
//draw the body and the Head
glPushMatrix();
glPushMatrix();
glColor3f(1.0, 1.0, 0.0);
glTranslatef(this->robot_Pos.x, this->robot_Pos.y, this->robot_Pos.z); // Place the robot on the the x-z board
glRotatef(rotateAngle, 0, 1, 0); //move the robot according to user request
//need to be computed from the view direction :)
glPushMatrix();
//This is the Head
glPushMatrix();
glTranslatef(0, 2.5, 0);
glRotatef(-this->headYAngle, 0, 1, 0);
glRotatef(-this->headXAngle, 1, 0, 0);
//glTranslatef(0, -0.0, 0);
glutSolidSphere(1.0, 10, 10);
glColor3f(0.0, 1, 0); //the color of eyes..
glPushMatrix(); //Eye
glTranslatef(0.3, 0.5, -0.8);
glutSolidSphere(0.2, 10, 10);
glPopMatrix();
glPushMatrix(); //Eye
glTranslatef(-0.6, 0.5, -0.8);
glutSolidSphere(0.2, 10, 10);
glPopMatrix();
glPopMatrix();
//This is the Body
glPushMatrix();
glColor3f(0.5, 0.9, 0.0);
glutSolidCube(3.0);
glPopMatrix();
glTranslatef(2.0, 1.0, 0);
glRotatef(90, 0.0, 1, 0.0);
//The Left hand of the robot
/****************/
/*Draw robot arm*/
/****************/
glColor3f(0.8, 0.1, 0.0);
//draw shoulder
glPushMatrix();
glTranslatef(-1.0, 0.0, 0.0);
glRotatef((GLfloat)this->shoulderAngle, 0.0, 0.0, 1.0);
glTranslatef(1.0, 0.0, 0.0);
glPushMatrix();
glScalef(2.0, 0.4, 1.0);
glutSolidCube(1.0);
glPopMatrix();
//draw elbow
glTranslatef(1.0, 0.0, 0.0);
glRotatef((GLfloat)this->elbowAngle, 0.0, 0.0, 1.0);
glTranslatef(1.0, 0.0, 0.0);
glPushMatrix();
glScalef(2.0, 0.4, 1.0);
glutSolidCube(1.0);
glPopMatrix();
//one plier
glTranslatef(1.0, 0.0, 0.0);
glRotatef((GLfloat)this->wristAngle, 0.0, 0.0, 1.0);
glRotatef(45 - this->plierAngle, 0.0, 0.0, 1.0);
glTranslatef(1.0, 0.0, 0.0);
glPushMatrix();
glScalef(2.0, 0.4, 1.0);
glutSolidCube(1.0);
glPopMatrix();
//Second plier
glTranslatef(-1.0, 0.0, 0.0);
glRotatef(-90 + 2 * this->plierAngle, 0.0, 0.0, 1.0);
glTranslatef(1.0, 0.0, 0.0);
glPushMatrix();
glScalef(2.0, 0.4, 1.0);
glutSolidCube(1.0);
glPopMatrix();
glPopMatrix();
//The legs
glPushMatrix();
glTranslatef(0, -3, -1);
glScalef(1, 2, 1);
glColor3f(0.5, 0.5, 0.5);
glutSolidCube(1.0);
glTranslated(0, -0.6, 0); //The feet
glColor3f(0.0, 0.0, 0.5);
glutSolidSphere(0.3, 10, 10);
glPopMatrix();
glColor3f(1.0, 1.0, 1.0);
glPushMatrix();
glTranslatef(0, -3, -3);
glScalef(1, 2, 1);
glColor3f(0.5, 0.5, 0.5);
glutSolidCube(1.0);
glTranslated(0, -0.6, 0); //The second feet
glColor3f(0.0, 0.0, 0.5);
glutSolidSphere(0.3, 10, 10);
glPopMatrix();
glColor3f(1.0, 1.0, 1.0);
glPopMatrix();
glPopMatrix();
}
//rotate the head up and down according to angle
void Robot::rotateHeadUPDOWN(int angle)
{
this->headXAngle = (this->headXAngle + angle) % 360;
//restrict the head movement to 60 degree
if (headXAngle > 60)
headXAngle = 60;
if (headXAngle < -60)
headXAngle = -60;
viewHeadDirection.y = -sin(headXAngle* PI / 180);
//convert also the Head view vector according
}
//rotate the head to the sides (left , right)
void Robot::rotateHeadToTheSIDES(int angle)
{
this->headYAngle = (this->headYAngle + angle) % 360;
//Restrict the head movement to 60 degree
if (headYAngle > 60)
headYAngle = 60;
if (headYAngle < -60)
headYAngle = -60;
Vec3d temp = viewDirection*-1;
//Rotate also the Head view vector in function of the viewDirection
this->viewHeadDirection.x = (float)(cos(headYAngle*PI / 180)*temp.x - sin(headYAngle*PI / 180)*temp.z);
this->viewHeadDirection.z = (float)(sin(headYAngle*PI / 180)*temp.x + cos(headYAngle*PI / 180)*temp.z);
viewHeadDirection.normalize();
}
//move the position robot forward
void Robot::move_forward()
{
this->robot_Pos += viewDirection*-1;
}
//move the position robot backward
void Robot::move_backward()
{
this->robot_Pos += viewDirection;
}
//move a side , positive value means move right,
// negative value means move left
void Robot::move_a_side(float delta)
{
this->robot_Pos+= (right*delta);
}
//Rotate body according to the angle
void Robot::rotate_body(float angle)
{
bodyYangle += (int)angle % 360;
Vec3d temp = this->viewDirection;//this->viewDirection-this->robot_Pos; //
this->viewDirection.x = (float)(cos(angle*PI/180)*temp.x - sin(angle*PI/180)*temp.z); // perform a rotation matrix around the y -axis
this->viewDirection.z = (float)(sin(angle*PI/180)*temp.x + cos(angle*PI/180)*temp.z);
this->viewDirection.normalize();// is it matter? the matrix rotation should be unitary...s
//Re-compute the right vector for later calculation
this->right = temp.cross(viewDirection, up)*-1;
////// Rotate the head with the body
temp = viewDirection*-1;
//rotate also the Head view vector in function of the viewDirection
this->viewHeadDirection.x = (float)(cos(headYAngle*PI / 180)*temp.x - sin(headYAngle*PI / 180)*temp.z); // perform a rotation matrix around the y - axis
this->viewHeadDirection.z = (float)(sin(headYAngle*PI / 180)*temp.x + cos(headYAngle*PI / 180)*temp.z);
viewHeadDirection.normalize();
}
//Rotate shoulder by an angle
void Robot::rotateShoulder(int angle)
{
if (angle > 0)
{
if (shoulderAngle < 70)//restriction on the angle of rotation
{
shoulderAngle = (shoulderAngle + 5) % 360;
}
}
else
{
if (shoulderAngle > -70)//restriction on the angle of rotation
{
shoulderAngle = (shoulderAngle - 5) % 360;
}
}
}
//Rotate the elbow by an angle
void Robot::rotateElbow(int angle)
{
if (angle > 0)
{
if (elbowAngle < 70)//restriction on the angle of rotation
{
elbowAngle = (elbowAngle + 5) % 360;
}
}
else
{
if (elbowAngle > -70)//restriction on the angle of rotation
{
elbowAngle = (elbowAngle - 5) % 360;
}
}
}
//Rotate the Wrist by an angle
void Robot::rotateWrist(int angle)
{
if (angle > 0)
{
if (wristAngle < 70)//restriction on the angle of rotation
{
wristAngle = (wristAngle + 5) % 360;
}
}
else
{
if (wristAngle > -70)//restriction on the angle of rotation
{
wristAngle = (wristAngle - 5) % 360;
}
}
}
//open the "Pliers" of the robot
void Robot::rotateWristAngle(int angle)
{
if (angle > 0)
{
if (plierAngle < 35)//restriction on the angle of rotation
{
plierAngle = (plierAngle + 5) % 360;
}
}
else
{
if (plierAngle > -35)//restriction on the angle of rotation
{
plierAngle = (plierAngle - 5) % 360;
}
}
}
//set the look into the robot eyes
void Robot::look()
{
Vec3d eyePosition = robot_Pos + robotEyeOffset ; // compute the position where we look according to the robot position.
Vec3d center = eyePosition + viewHeadDirection;
gluLookAt(eyePosition.x , eyePosition.y, eyePosition.z, //make the position exactly at the robot eye
center.x , center.y , center.z, //make the direction as the head
0 , 1 , 0); //Up vector
}
|
e9eadc322335f7185d5dd6d3b8449253929286f4 | b367fe5f0c2c50846b002b59472c50453e1629bc | /xbox_leak_may_2020/xbox trunk/xbox/private/test/online/server/surge/httpclient/httpclient.cpp | ce96d76573b84b12ca2bb1a7ff5e250b5a59fc8b | [] | no_license | sgzwiz/xbox_leak_may_2020 | 11b441502a659c8da8a1aa199f89f6236dd59325 | fd00b4b3b2abb1ea6ef9ac64b755419741a3af00 | refs/heads/master | 2022-12-23T16:14:54.706755 | 2020-09-27T18:24:48 | 2020-09-27T18:24:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 22,525 | cpp | httpclient.cpp | /*
Copyright (C) 1999-2000 Microsoft Corporation
Module Name:
HttpClient.cpp
Abstract:
Author:
Josh Poley (jpoley) 1-1-1999
Revision History:
NOTE: Include files with error codes:
SSL <winerror.h>
Sockets <winsock2.h>
HTTP <wininet.h>
*/
#include "stdafx.h"
#include <time.h>
#include "SecureSocketLayer.h"
#include "HttpClient.h"
#include <mswsock.h>
// timeout in seconds + msec
#define RECV_TIMEOUT_S 2
#define RECV_TIMEOUT_US 0
#define DEFAULT_PORT 80
#define DEFAULT_PROXY_PORT DEFAULT_PORT
#define DEFAULT_SSL_PORT 443
extern int followDomainRules;
#ifdef _DEBUG
#define DEBUGLOG "HttpClient.log"
// NOTE: There is no critical section around the logging.
// Keep this in mind when viewing the log from a
// multithreaded app.
// NOTE: You can #define _DEBUG_RAW_DUMP to dump raw information
// to the log file. (Hex output is default).
void Report(LPCTSTR lpszFormat, ...);
void PrintHexDump(const char * buffer, DWORD length);
#endif
/*/////////////////////////////////////////////////////////////////////////////
Routine Description:
Arguments:
Return value:
*/
CHttpClient::CHttpClient()
{
// windows socket initialization
sock = INVALID_SOCKET;
nextsock = INVALID_SOCKET;
wPort = DEFAULT_PORT;
dataLen = 0;
dest.sin_family = PF_INET;
// Proxy
wProxyPort = DEFAULT_PROXY_PORT;
bUseProxy = FALSE;
szProxyServerName[0] = '\0';
// SSL
SSL = NULL;
// timeouts
timeout.tv_sec = RECV_TIMEOUT_S;
timeout.tv_usec = RECV_TIMEOUT_US;
// timers
sendTime = 0;
ttfbTime = 0;
ttlbTime = 0;
}
CHttpClient::~CHttpClient()
{
if(sock != INVALID_SOCKET) Disconnect();
if(nextsock != INVALID_SOCKET)
{
closesocket(nextsock);
nextsock = INVALID_SOCKET;
}
if(SSL) delete SSL;
}
long CHttpClient::Open(void)
{
#ifdef _DEBUG
Report("Sock Opened\n");
#endif
wPort = DEFAULT_PORT;
dest.sin_family = PF_INET;
// Proxy
wProxyPort = DEFAULT_PROXY_PORT;
bUseProxy = FALSE;
// SSL
if(SSL)
{
delete SSL;
SSL = NULL;
}
if(nextsock != INVALID_SOCKET)
{
sock = nextsock;
nextsock = INVALID_SOCKET;
}
else
{
sock = socket(PF_INET, SOCK_STREAM, 0);
if(sock == INVALID_SOCKET) return (long)WSAGetLastError();
}
return 0;
}
int CHttpClient::GetHTTPStatus(void)
{
char *beginning = strstr(data, "HTTP/");
if(!beginning) return 0;
beginning += 9;
int res = atoi(beginning);
// if first HTTP status found is 100, look if there is another one
// IIS 5 sends HTTP 100 and then actual data
if (res == 100)
{
char *nextcode = strstr(beginning, "HTTP/");
if (nextcode)
{
nextcode += 9;
res = atoi(nextcode);
}
}
return res;
}
char* CHttpClient::GetBody(void)
{
char *body = strstr(data, "\r\n\r\n");
if(!body) return NULL;
return body + 4;
}
inline char* CHttpClient::GetData(void)
{
return data;
}
inline int CHttpClient::GetDataLen(void)
{
return dataLen;
}
long CHttpClient::Connect(IN_ADDR server, const char *serverName)
{
// NOTE: if connecting through a proxy, 'server' must be the address of
// the proxy, and 'serverName' the final destination
if(!serverName) return WSAHOST_NOT_FOUND;
dest.sin_port = htons( (bUseProxy ? wProxyPort : wPort) );
dest.sin_addr.s_addr = server.s_addr;
if(connect(sock, (SOCKADDR*)&dest, sizeof(SOCKADDR)) == SOCKET_ERROR)
{
return (long)WSAGetLastError();
}
if(bUseProxy)
{
// Build message for proxy server
dataLen = sprintf(data, "CONNECT %s:%u %s", serverName, wPort, "HTTP/1.0\r\nUser-Agent: CHttpClient\r\n\r\n");
if(send(sock, data, dataLen, 0) == SOCKET_ERROR)
{
return (long)WSAGetLastError();
}
do
{
if((dataLen = recv(sock, data, DATA_SIZE, 0)) == SOCKET_ERROR)
{
data[dataLen = 0] = '\0';
return (long)WSAGetLastError();
}
data[dataLen] = '\0';
} while(strstr(data, "\r\n\r\n") == NULL);
}
if(SSL)
{
long status = SSL->Connect(sock, serverName);
return status;
}
return 0;
}
long CHttpClient::Connect(const char *serverName)
{
if(!serverName) return WSAHOST_NOT_FOUND;
#ifdef _DEBUG
Report("Connect %s:%u\n", serverName, wPort);
#endif
IN_ADDR address;
// try to treat serverName as a dotted decimal
if(bUseProxy) address.s_addr = inet_addr(szProxyServerName);
else address.s_addr = inet_addr(serverName);
if(address.s_addr == INADDR_NONE)
{
// not dotted decimal, so try to get an ip for it
HOSTENT *hosts;
if(bUseProxy) hosts = gethostbyname(szProxyServerName);
else hosts = gethostbyname(serverName);
if(!hosts) return (long)WSAGetLastError();
// take the first address found
address.s_addr = **(LPDWORD*)&hosts->h_addr_list[0];
}
return Connect(address, serverName);
}
long CHttpClient::Disconnect(void)
{
#ifdef _DEBUG
Report("Disconnect\n");
#endif
if(sock == INVALID_SOCKET) return 0;
// SSL clean up
if(SSL)
{
SSL->Disconnect(sock);
}
int err;
shutdown(sock, SD_BOTH);
/* NOTE: Based on the "polite" way to close a connection, we
should call recv untill no more data is available
(timeout), but due to performance reasons, we will
not do this (or we leave it up to the application).
On the above line, set the SD_BOTH to SD_SEND, if
you wish to use the below code.
// clean out the receive buffer
char tempdata[DATA_SIZE+1];
for(int i=0; i<100; i++) // just quit after a while
{
if(!IsDataAvailable()) break;
err = recv(sock, tempdata, DATA_SIZE, 0);
if(err == 0 || err == SOCKET_ERROR) break;
}
*/
err = closesocket(sock);
sock = INVALID_SOCKET;
if(err) return (long)WSAGetLastError();
return 0;
}
long CHttpClient::HardDisconnect(void)
{
#ifdef _DEBUG
Report("HardDisconnect\n");
#endif
if(sock == INVALID_SOCKET) return 0;
// SSL clean up
if(SSL)
{
SSL->Disconnect(sock);
}
int err = closesocket(sock);
sock = INVALID_SOCKET;
if(err) return (long)WSAGetLastError();
return 0;
}
long CHttpClient::Send(const char *senddata, int len)
{
int err;
// Set our timers back to 0
sendTime = 0;
ttfbTime = 0;
ttlbTime = 0;
#ifdef _DEBUG
Report("Send\n");
#ifdef _DEBUG_DUMP
PrintHexDump(senddata, len);
#endif
#endif
if(len <= 0) return WSAEMSGSIZE;
if(!senddata) return WSAEFAULT;
if(SSL)
{
long status;
memcpy(data, senddata, len);
DWORD dLen = len;
status = SSL->Encrypt(data, dLen, DATA_SIZE);
dataLen = (int)dLen;
if(FAILED(status))
{
return status;
}
err = send(sock, data, dataLen, 0);
}
else
{
err = send(sock, senddata, len, 0);
}
if(err == SOCKET_ERROR)
{
return (long)WSAGetLastError();
}
sendTime = time(NULL);
return 0;
}
long CHttpClient::Send(void)
{
int err;
// Set our timers back to 0
sendTime = 0;
ttfbTime = 0;
ttlbTime = 0;
#ifdef _DEBUG
Report("Send\n");
#ifdef _DEBUG_DUMP
PrintHexDump(data, dataLen);
#endif
#endif
if(dataLen <= 0) return WSAEMSGSIZE;
if(SSL)
{
long status;
DWORD dLen = dataLen;
status = SSL->Encrypt(data, dLen, DATA_SIZE);
dataLen = (int)dLen;
if(FAILED(status))
{
return status;
}
err = send(sock, data, dataLen, 0);
}
else
{
err = send(sock, data, dataLen, 0);
}
if(err == SOCKET_ERROR)
{
return (long)WSAGetLastError();
}
sendTime = time(NULL);
return 0;
}
long CHttpClient::Receive(BOOL readAll/*=FALSE*/)
{
long err=0;
DWORD dLen;
dataLen = 0;
//DWORD contentLength = 0; // length of data according to the received header
//DWORD headerSize = 0;
#ifdef _DEBUG
Report("Receive:\n");
#endif
DWORD count = 0;
const DWORD maxCount = 500;
data[0] = '\0';
dataLen = 0;
receive:
do
{
if(++count >= maxCount)
{
err = WSAECONNABORTED;
break;
}
// check for available data
if(!IsDataAvailable())
{
data[dataLen] = '\0';
err = WSAETIMEDOUT;
break;
}
// retreive the data
if((dLen = recv(sock, data+dataLen, DATA_SIZE-dataLen, 0)) == SOCKET_ERROR)
{
data[dataLen] = '\0';
err = WSAGetLastError();
break;
}
if (!ttfbTime)
{
ttfbTime = time(NULL);
}
if(dLen == 0) break; // no more data
/* This code is commented out because we would want to do this
but because we un SSL after we get everything it wont work.
if(contentLength == 0)
{
char *t = strstr(data, "Content-Length:");
if(t)
{
contentLength = atol(t + strlen("Content-Length:"));
//FILE *f = fopen("c:\\test.txt", "a+");
//fprintf(f, "content length = %d\n", contentLength);
//fclose(f);
t = strstr(t, "\r\n\r\n");
headerSize = (t+4) - data;
}
}
*/
dataLen += dLen;
data[dataLen] = '\0';
/* See above note
// reached end of body
if(contentLength && dataLen-headerSize >= contentLength)
{
//FILE *f = fopen("c:\\test.txt", "a+");
//fprintf(f, "reached end of body\n", contentLength);
//fclose(f);
break;
}
*/
} while(readAll);
if(SSL)
{
dLen = (DWORD)dataLen;
// antonpav - add dLen check
// in case recv() returns zero length
// Decrypt() with zero len data results in
// SEC_E_INCOMPLETE_MESSAGE, and loops to receive label
if (dLen != 0)
{
long status = SSL->Decrypt(data, dLen, DATA_SIZE);
if(status == SEC_I_RENEGOTIATE)
{
status = SSL->ClientHandshakeLoop(sock, FALSE);
err = status;
}
else if(status == SEC_E_INCOMPLETE_MESSAGE)
{
// We need to read more from the server before we can decrypt
if(count < maxCount) goto receive;
}
if(FAILED(status))
{
err = status;
}
dataLen = (int)dLen;
}
}
data[dataLen] = '\0';
if (!ttfbTime)
{
sendTime = 0;
}
else
{
ttlbTime = time(NULL);
}
#ifdef _DEBUG_DUMP
PrintHexDump(data, dataLen);
#endif
return err;
}
BOOL CHttpClient::IsDataAvailable(void)
{
FD_SET bucket;
bucket.fd_count = 1;
bucket.fd_array[0] = sock;
// do some work for the next connection before waiting
if(nextsock == INVALID_SOCKET)
{
nextsock = socket(PF_INET, SOCK_STREAM, 0);
}
int err = select(0, &bucket, NULL, NULL, &timeout);
if(err == 0 || err == SOCKET_ERROR)
{
return FALSE;
}
return TRUE;
}
BOOL CHttpClient::IsSendAvailable(void)
{
TIMEVAL timeout;
timeout.tv_sec = 0;
timeout.tv_usec = 20;
FD_SET bucket;
bucket.fd_count = 1;
bucket.fd_array[0] = sock;
if(select(0, NULL, &bucket, NULL, &timeout) == 1)
{
return TRUE;
}
return FALSE;
}
long CHttpClient::SetLinger(BOOL linger, WORD timeout)
{
LINGER ling;
int size = sizeof(LINGER);
#ifdef _DEBUG
Report("Linger Enabled\n");
#endif
ling.l_onoff = (WORD)linger;
ling.l_linger = timeout;
int err;
if((err = setsockopt(sock, SOL_SOCKET, SO_LINGER, (char*)&ling, size)) == SOCKET_ERROR)
{
return (long)WSAGetLastError();
}
return 0;
}
long CHttpClient::SetKeepAlive(BOOL keepalive)
{
int err;
int val = keepalive;
#ifdef _DEBUG
Report("KeepAlive Enabled\n");
#endif
if((err = setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, (char*)&val, sizeof(int))) == SOCKET_ERROR)
{
return (long)WSAGetLastError();
}
return 0;
}
long CHttpClient::SetSSL(LPSTR pszUserName /* =NULL */, DWORD dwProtocol /* =SP_PROT_SSL2 */, ALG_ID aiKeyExch /* =CALG_RSA_KEYX */)
{
#ifdef _DEBUG
Report("SSL Enabled\n");
#endif
wPort = DEFAULT_SSL_PORT;
// available encryption type values
// dwProtocol = SP_PROT_PCT1;
// dwProtocol = SP_PROT_SSL2;
// dwProtocol = SP_PROT_SSL3;
// dwProtocol = SP_PROT_TLS1;
// aiKeyExch = CALG_RSA_KEYX;
// aiKeyExch = CALG_DH_EPHEM;
if(!SSL) SSL = new CSecureSocketLayer(pszUserName, dwProtocol, aiKeyExch);
if(!SSL) return SEC_E_INSUFFICIENT_MEMORY;
return 0;
}
long CHttpClient::SetProxy(const char *serverName, WORD port)
{
#ifdef _DEBUG
Report("Proxy Enabled\n");
#endif
bUseProxy = TRUE;
strcpy(szProxyServerName, serverName);
wProxyPort = port;
return 0;
}
void CHttpClient::SetRecvTimeout(UINT sec, UINT usec)
{
timeout.tv_sec = sec;
timeout.tv_usec = usec;
}
void CHttpClient::SetDefaultPort(WORD newPort)
{
wPort = newPort;
}
int CHttpClient::ParseURL(const char *url, char *server, char *site, BOOL* ssl)
{
// TODO try to recover on malformed urls
if(!url || !server || !site || !ssl) return 0;
// Check for SSL
url += 4;
if(*url == 's' || *url == 'S')
{
*ssl = 1;
url += 4;
}
else if(*url == ':')
{
*ssl = 0;
url += 3;
}
else return 0;
// copy the server portion
while(*url != '/')
{
if(!(*url))
{
// no site, so we tack on an ending /
*server = '\0';
site[0] = '/';
site[1] = '\0';
return 0;
}
*server++ = *url++;
}
// copy the path/page portion
*server = '\0';
strcpy(site, url);
return 1;
}
int CHttpClient::GrabCookies(Cookie *jar, char *source, char *domain /*=NULL*/)
{
if(!jar || !source) return 0;
int numFound = 0;
char *cookiestart;
cookiestart = (char*)source;
// antonpav
// should search through the entire response as
// we may have multiple replies in one buffer
// char *body = strstr(data, "\r\n\r\n");
// if(body) body[0] = '\0'; // just so we dont search through the entire response
while((cookiestart = strstr(cookiestart, "Set-Cookie:")) != NULL)
{
cookiestart += sizeof("Set-Cookie:");
jar->Add(cookiestart, domain);
++numFound;
}
// if(body) body[0] = '\r';
return numFound;
}
int CHttpClient::GetCookieRules(void)
{
return followDomainRules;
}
void CHttpClient::SetCookieRules(int i)
{
followDomainRules = i;
}
int CHttpClient::POSTEncode(char *dest, const char *source)
{
if(dest == source) return 0;
// NOTE: the restricted characters are defined in the URI RFC
// (current ver: 2396) in section 2.
char *restricted = ";/?:@&=+$,\"#%%<>\\~";
char buff[10];
int i;
for(i=0; *source; source++, i++)
{
if(strchr(restricted, *source) != NULL)
{
sprintf(buff, "%02X", (unsigned)(*source));
dest[i] = (char)'%%'; ++i;
dest[i] = buff[0]; ++i;
dest[i] = buff[1];
}
else if(*source == ' ')
{
dest[i] = '+';
}
else
{
dest[i] = *source;
}
}
dest[i] = '\0';
return i;
}
int ctox(char c)
{
if(c >= '0' && c <= '9') return c - '0';
else if(c >= 'A' && c <= 'F') return c - 'A' + 10;
else if(c >= 'a' && c <= 'f') return c - 'a' + 10;
else return 0;
}
int CHttpClient::URLDecode(char *dest, const char *source)
{
if(dest == source) return 0;
// NOTE: the restricted characters are defined in the URI RFC
// (current ver: 2396) in section 2.
int i;
for(i=0; *source; source++, i++)
{
if(*source == '%')
{
++source;
dest[i] = (char)ctox(*source)*16;
++source;
dest[i] += (char)ctox(*source);
}
else
{
dest[i] = *source;
}
}
dest[i] = '\0';
return i;
}
int CHttpClient::URLEncode(char *dest, const char *source)
{
if(dest == source) return 0;
// NOTE: the restricted characters are defined in the URI RFC
// (current ver: 2396) in section 2.
char *restricted = ";/?:@&=+$,\"#%%<>\\~ ";
char buff[10];
int i;
for(i=0; *source; source++, i++)
{
if(strchr(restricted, *source) != NULL)
{
sprintf(buff, "%02X", (unsigned)(*source));
dest[i] = (char)'%%'; ++i;
dest[i] = buff[0]; ++i;
dest[i] = buff[1];
}
else
{
dest[i] = *source;
}
}
dest[i] = '\0';
return i;
}
BOOL CHttpClient::DNSLookup(char *address, char *output, size_t bufferlen)
{
if(!address || !output || bufferlen==0) return FALSE;
HOSTENT *hosts;
hosts = gethostbyname(address);
if(!hosts) return FALSE;
size_t length = 0;
// get the entries
for(unsigned i=0; hosts->h_addr_list[i]; i++)
{
if(bufferlen <= length+16) break;
length =+ sprintf(output+length, "%u.%u.%u.%u", (unsigned char)hosts->h_addr_list[i][0], (unsigned char)hosts->h_addr_list[i][1], (unsigned char)hosts->h_addr_list[i][2], (unsigned char)hosts->h_addr_list[i][3]);
if(hosts->h_addr_list[i+1]) length += sprintf(output+length, ", ");
}
return TRUE;
}
// 0 = TTFB
// 1 = TTLB
time_t CHttpClient::GetTime(unsigned char timeToReturn)
{
switch (timeToReturn)
{
case 0:
return ttfbTime - sendTime;
case 1:
return ttlbTime - sendTime;
}
return 0;
}
#ifdef _DEBUG // enabled only in debug mode
static void Report(LPCTSTR lpszFormat, ...)
{
va_list args;
va_start(args, lpszFormat);
char szBuffer[512];
char szFormat[512];
char dbuffer[9];
char tbuffer[9];
_strdate(dbuffer);
_strtime(tbuffer);
sprintf(szFormat, "%s, %s, %s", tbuffer, dbuffer, lpszFormat);
vsprintf(szBuffer, szFormat, args);
FILE *f = fopen(DEBUGLOG, "a+");
if(f)
{
fprintf(f, "%s", szBuffer);
fclose(f);
}
else
printf("%s", szBuffer);
va_end(args);
}
static void PrintHexDump(const char * buffer, DWORD length)
{
FILE *f = fopen(DEBUGLOG, "a+");
#ifdef _DEBUG_RAW_DUMP
if(f)
{
fprintf(f, "%s", buffer);
fprintf(f, "\n");
fclose(f);
}
else
{
printf("%s", buffer);
printf("\n");
}
return;
#endif
DWORD i,count,index;
CHAR rgbDigits[]="0123456789ABCDEF";
CHAR rgbLine[100];
char cbLine;
for(index = 0; length; length -= count, buffer += count, index += count)
{
count = (length > 16) ? 16:length;
sprintf(rgbLine, "%4.4x ",index);
cbLine = 6;
for(i=0;i<count;i++)
{
rgbLine[cbLine++] = rgbDigits[buffer[i] >> 4];
rgbLine[cbLine++] = rgbDigits[buffer[i] & 0x0f];
if(i == 7)
{
rgbLine[cbLine++] = ' ';
}
else
{
rgbLine[cbLine++] = ' ';
}
}
for(; i < 16; i++)
{
rgbLine[cbLine++] = ' ';
rgbLine[cbLine++] = ' ';
rgbLine[cbLine++] = ' ';
}
rgbLine[cbLine++] = ' ';
for(i = 0; i < count; i++)
{
if(buffer[i] < 32 || buffer[i] > 126)
{
rgbLine[cbLine++] = '.';
}
else
{
rgbLine[cbLine++] = buffer[i];
}
}
rgbLine[cbLine++] = 0;
if(f) fprintf(f, "%s\n", rgbLine);
else printf("%s\n", rgbLine);
}
if(f) fclose(f);
}
#endif
|
bd8684fb99b5aa4ad0295f3ec13fd10c917b6548 | 71219ed2748798595af6890258d2f48e1fe63056 | /04-Trees-And-Graphs/0408-First-Common-Ancestor/solution_test.cpp | 1712784acb33d3d8f1056f15bb64737b5375c0b8 | [] | no_license | KoaLaYT/Cracking-The-Code-Interview-Question | ae95a483515eefb18827ecb9eac63e59632a780c | b2fb271ada1b32ffabf985259639671999844137 | refs/heads/master | 2023-04-05T22:45:26.118542 | 2021-04-07T06:25:58 | 2021-04-07T06:25:58 | 334,376,322 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,904 | cpp | solution_test.cpp | #include "solution.hpp"
#include <gtest/gtest.h>
#include <vector>
class FirstCommonAncestorTest : public ::testing::Test {
protected:
void SetUp() override
{
Node* n9 = new Node{9};
Node* n13 = new Node{13};
n9->p = n13;
n13->left = n9;
Node* n2 = new Node{2};
Node* n4 = new Node{4};
Node* n3 = new Node{3};
n2->p = n3;
n4->p = n3;
n3->left = n2;
n3->right = n4;
Node* n7 = new Node{7};
n13->p = n7;
n7->right = n13;
Node* n6 = new Node{6};
n3->p = n6;
n7->p = n6;
n6->left = n3;
n6->right = n7;
Node* n17 = new Node{17};
Node* n20 = new Node{20};
Node* n18 = new Node{18};
n17->p = n18;
n20->p = n18;
n18->left = n17;
n18->right = n20;
Node* root = new Node{15};
n6->p = root;
n18->p = root;
root->left = n6;
root->right = n18;
tree.set_root(root);
}
Tree tree;
};
struct Case {
int a;
int b;
int expect;
};
TEST_F(FirstCommonAncestorTest, find)
{
{
Node* a = tree.find(6);
ASSERT_TRUE(a);
EXPECT_EQ(a->key, 6);
}
{
Node* a = tree.find(9);
ASSERT_TRUE(a);
EXPECT_EQ(a->key, 9);
}
{
Node* a = tree.find(1);
ASSERT_FALSE(a);
}
}
TEST_F(FirstCommonAncestorTest, basic)
{
std::vector<Case> cases{
{4, 13, 6},
{2, 4, 3},
{2, 17, 15},
{1, 20, -1},
};
for (auto& c : cases) {
Node* a = tree.find(c.a);
Node* b = tree.find(c.b);
Node* result = tree.first_common_ancestor(a, b);
if (c.expect > 0) {
ASSERT_TRUE(result);
EXPECT_EQ(result->key, c.expect);
} else {
ASSERT_FALSE(result);
}
}
} |
86331076e09ed46bdc1fbb087c40582cabb77f79 | cbf41d6093b2c3615ec085d49ca65a451fffd78a | /dsastudents/tree/graph.cpp | e470389a1c7ebeef6f2b9c3add1e47fea2185a4b | [] | no_license | nhophucrious/Data-Structure-and-Algorithms-CO2003- | 867ae19f032e839e538127f6bf906a2e31be9785 | 3ca14c13fbb56e2d6464eb0f90e51ae7a06a966a | refs/heads/main | 2023-07-27T16:04:03.185521 | 2021-08-24T12:59:06 | 2021-08-24T12:59:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,920 | cpp | graph.cpp | #include <iostream>
#include <iomanip>
#include <string>
#include "geom/Vector3D.h"
#include "graph/IGraph.h"
#include "graph/UGraphModel.h"
#include "graph/DGraphModel.h"
#include "list/DLinkedList.h"
#include "stacknqueue/Stack.h"
#include "stacknqueue/Queue.h"
#include "stacknqueue/PriorityQueue.h"
#include "hash/XHashMap.h"
#include "sorting/DLinkedListSE.h"
using namespace std;
////////////////
char A = 'A', B = 'B', C = 'C', D = 'D', E = 'E',
F = 'F', G = 'G', H = 'H', I = 'I', J = 'J',
K = 'K', L = 'L', M = 'M', N = 'N', O = 'O',
P = 'P', Q = 'Q', R = 'R', S = 'S', T = 'T',
U = 'U', V = 'V', X = 'X', Y = 'Y', Z = 'Z';
bool vertexEQ(char &a, char &b)
{
return a == b;
}
string vertex2str(char &v)
{
return std::to_string(v);
}
void demo_1()
{
UGraphModel<char> model(&vertexEQ, &vertex2str);
char vertices[] = {A, B, C, D, F};
Edge<char> edges[] = {
Edge<char>(A, B, 100),
Edge<char>(B, D, 200),
Edge<char>(C, D, 400),
Edge<char>(F, D, 500)};
for (char v : vertices)
model.add(v);
for (Edge<char> e : edges)
model.connect(e.from, e.to, e.weight);
for (char v : vertices)
{
cout << v
<< ":" << model.inDegree(v)
<< "\t" << model.outDegree(v) << endl;
}
for (char v : vertices)
{
DLinkedList<char> inward = model.getInwardEdges(v);
DLinkedList<char> outward = model.getOutwardEdges(v);
cout << v << "\t" << inward.toString() << "\t" << outward.toString() << endl;
}
cout << model.weight(C, D) << endl;
cout << ((model.connected(A, B)) ? "has a connection" : "no connection") << endl;
model.remove(D);
model.println();
}
IGraph<char> *create_graph_0()
{
IGraph<char> *model = new DGraphModel<char>(&vertexEQ, &vertex2str);
char vertices[] = {A, B, C, D, E, F, G, H};
Edge<char> edges[] = {
Edge<char>(A, B),
Edge<char>(A, D),
Edge<char>(B, D),
Edge<char>(B, F),
Edge<char>(C, D),
Edge<char>(C, E),
Edge<char>(D, F),
Edge<char>(E, F),
Edge<char>(F, H),
Edge<char>(G, F),
Edge<char>(G, H),
};
for (char v : vertices)
model->add(v);
for (Edge<char> e : edges)
model->connect(e.from, e.to, e.weight);
return model;
}
IGraph<char> *create_graph_1()
{
char vertices[] = {'A', 'X', 'G', 'H', 'P', 'E', 'Y', 'M', 'J'};
Edge<char> edges[] = {
Edge<char>('A', 'X'),
Edge<char>('X', 'G'),
Edge<char>('X', 'H'),
Edge<char>('G', 'H'),
Edge<char>('G', 'P'),
Edge<char>('H', 'P'),
Edge<char>('H', 'E'),
Edge<char>('E', 'M'),
Edge<char>('E', 'Y'),
Edge<char>('Y', 'M'),
Edge<char>('M', 'J')};
IGraph<char> *graph = new DGraphModel<char>(&vertexEQ, &vertex2str);
for (char v : vertices)
graph->add(v);
for (Edge<char> edge : edges)
graph->connect(edge.from, edge.to);
return graph;
}
IGraph<char> *create_graph_2()
{
char vertices[] = {S, A, B, C, D, E, F, T};
Edge<char> edges[] = {
Edge<char>(S, A, 2),
Edge<char>(S, C, 4),
Edge<char>(S, E, 1),
Edge<char>(A, B, 5),
Edge<char>(C, A, 2),
Edge<char>(C, F, 3),
Edge<char>(E, D, 2),
Edge<char>(E, F, 3),
Edge<char>(B, T, 3),
Edge<char>(D, B, 5),
Edge<char>(D, T, 2),
Edge<char>(F, T, 1)};
IGraph<char> *graph = new DGraphModel<char>(&vertexEQ, &vertex2str);
for (char v : vertices)
graph->add(v);
for (Edge<char> edge : edges)
graph->connect(edge.from, edge.to);
return graph;
}
IGraph<char> *create_graph_3()
{
char vertices[] = {A, B, C, D, E, F, G, H};
Edge<char> edges[] = {
Edge<char>(A, B),
Edge<char>(A, D),
Edge<char>(B, D),
Edge<char>(B, F),
Edge<char>(C, D),
Edge<char>(C, E),
Edge<char>(D, F),
Edge<char>(E, F),
Edge<char>(G, F),
Edge<char>(G, H),
Edge<char>(F, H)};
IGraph<char> *graph = new DGraphModel<char>(&vertexEQ, &vertex2str);
for (char v : vertices)
graph->add(v);
for (Edge<char> edge : edges)
graph->connect(edge.from, edge.to);
return graph;
}
IGraph<char> *create_graph_4()
{
char vertices[] = {A, B, C, D, E, F, G, H, I, J, K};
Edge<char> edges[] = {
Edge<char>(B, A),
Edge<char>(C, A),
Edge<char>(D, A),
Edge<char>(E, D),
Edge<char>(F, D),
Edge<char>(E, G),
Edge<char>(F, G),
Edge<char>(H, D),
Edge<char>(I, D),
Edge<char>(J, H),
Edge<char>(J, I),
Edge<char>(K, J)};
IGraph<char> *graph = new DGraphModel<char>(&vertexEQ, &vertex2str);
for (char v : vertices)
graph->add(v);
for (Edge<char> edge : edges)
graph->connect(edge.from, edge.to);
return graph;
}
//Why runtime error?
void demo_2()
{
IGraph<char> *model = create_graph_0();
cout << model->toString() << endl;
DLinkedList<char> vertices = model->vertices();
DLinkedList<char>::Iterator it;
for (it = vertices.begin(); it != vertices.end(); it++)
{
char v = *it;
DLinkedList<char> inward = model->getInwardEdges(v);
DLinkedList<char> outward = model->getOutwardEdges(v);
cout << v << "\t" << inward.toString() << "\t" << outward.toString() << endl;
}
delete model;
}
//Why runtime error?
void demo_3()
{
IGraph<char> *model = create_graph_1();
cout << model->toString() << endl;
DGraphModel<char> *dmodel = dynamic_cast<DGraphModel<char> *>(model);
DGraphModel<char>::Iterator it;
for (it = dmodel->begin(); it != dmodel->end(); it++)
{
char v = *it;
DLinkedList<char> inward = dmodel->getInwardEdges(v);
DLinkedList<char> outward = dmodel->getOutwardEdges(v);
cout << v << "\t" << inward.toString() << "\t" << outward.toString() << endl;
}
delete model;
}
void demo_4()
{
DGraphModel<char> model(&vertexEQ, &vertex2str);
char vertices[] = {A, B, C, D, E, F, G, H};
Edge<char> edges[] = {
Edge<char>(A, B),
Edge<char>(A, D),
Edge<char>(B, D),
Edge<char>(B, F),
Edge<char>(C, D),
Edge<char>(C, E),
Edge<char>(D, F),
Edge<char>(E, F),
Edge<char>(F, H),
Edge<char>(G, F),
Edge<char>(G, H),
};
for (char v : vertices)
model.add(v);
for (Edge<char> e : edges)
model.connect(e.from, e.to, e.weight);
//
DLinkedList<char> list = model.vertices();
list.println();
DGraphModel<char>::Iterator it;
for (it = model.begin(); it != model.end(); it++)
{
cout << *it << endl;
}
}
int hash_code(char &key, int size)
{
return (int)key % size;
}
void dft(IGraph<char> *model, char start)
{
DLinkedList<char> results;
Stack<char> open; //contain nodes TO BE processed in future
XHashMap<char, char> inopen(&hash_code);
XHashMap<char, char> inclose(&hash_code); //contains vertices that have been processed
open.push(start);
inopen.put(start, start);
while (!open.empty())
{
char vertex = open.pop();
inopen.remove(vertex);
//process
results.add(vertex); //save it to results and then process later
inclose.put(vertex, vertex);
//generate children + push to open
DLinkedListSE<char> children;
children.copyFrom(model->getOutwardEdges(vertex));
children.sort();
DLinkedListSE<char>::Iterator it;
for (it = children.begin(); it != children.end(); it++)
{
char child = *it;
if (inclose.containsKey(child))
continue;
if (inopen.containsKey(child))
{
open.remove(child);
open.push(child);
continue;
}
open.push(child);
inopen.put(child, child);
}
}
//
results.println();
}
void bft(IGraph<char> *model, char start)
{
DLinkedList<char> results;
Queue<char> open; //contain nodes TO BE processed in future
XHashMap<char, char> inopen(&hash_code);
XHashMap<char, char> inclose(&hash_code); //contains vertices that have been processed
open.push(start);
inopen.put(start, start);
while (!open.empty())
{
char vertex = open.pop();
inopen.remove(vertex);
//process
results.add(vertex); //save it to results and then process later
inclose.put(vertex, vertex);
//generate children + push to open
DLinkedListSE<char> children;
children.copyFrom(model->getOutwardEdges(vertex));
children.sort();
DLinkedListSE<char>::Iterator it;
for (it = children.begin(); it != children.end(); it++)
{
char child = *it;
if (inopen.containsKey(child))
continue;
if (inclose.containsKey(child))
continue;
open.push(child);
inopen.put(child, child);
}
}
//
results.println();
}
void demo_dft()
{
IGraph<char> *model = create_graph_1();
dft(model, A);
delete model;
}
void demo_bft()
{
IGraph<char> *model = create_graph_4();
bft(model, A);
delete model;
}
int main(int arc, char **argv)
{
demo_2();
// demo_3();
return 0;
} |
df64cb056905131a2bbf00f75a93c01657e46fd7 | 485faf9d4ec7def9a505149c6a491d6133e68750 | /include/inv/bundles/SoTextureCoordinateBundle.H | fc93ff1321fb6d7bc8d38c24645c84c84330f567 | [
"LicenseRef-scancode-warranty-disclaimer",
"ECL-2.0"
] | permissive | ohlincha/ECCE | af02101d161bae7e9b05dc7fe6b10ca07f479c6b | 7461559888d829338f29ce5fcdaf9e1816042bfe | refs/heads/master | 2020-06-25T20:59:27.882036 | 2017-06-16T10:45:21 | 2017-06-16T10:45:21 | 94,240,259 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 6,830 | h | SoTextureCoordinateBundle.H | /*
*
* Copyright (C) 2000 Silicon Graphics, Inc. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* Further, this software is distributed without any warranty that it is
* free of the rightful claim of any third person regarding infringement
* or the like. Any license provided herein, whether implied or
* otherwise, applies only to this software file. Patent licenses, if
* any, provided herein do not apply to combinations of this program with
* other software, or any other product whatsoever.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pkwy,
* Mountain View, CA 94043, or:
*
* http://www.sgi.com
*
* For further information regarding this notice, see:
*
* http://oss.sgi.com/projects/GenInfo/NoticeExplan/
*
*/
// -*- C++ -*-
/*
* Copyright (C) 1990,91 Silicon Graphics, Inc.
*
_______________________________________________________________________
______________ S I L I C O N G R A P H I C S I N C . ____________
|
| $Revision: 22148 $
|
| Description:
| This file defines the SoTextureCoordinateBundle class.
|
| Author(s) : Paul S. Strauss
|
______________ S I L I C O N G R A P H I C S I N C . ____________
_______________________________________________________________________
*/
#ifndef _SO_TEXTURE_COORDINATE_BUNDLE
#define _SO_TEXTURE_COORDINATE_BUNDLE
#include "inv/bundles/SoBundle.H"
#include "inv/elements/SoGLTextureCoordinateElement.H"
#include "inv/misc/SoState.H"
//////////////////////////////////////////////////////////////////////////////
//
// Class: SoTextureCoordinateBundle
//
// Bundle that allows shapes to deal with texture coordinates more
// easily. This class provides a fairly simple interface to texture
// coordinate handling, including default texture coordinate
// generation. This can be used during either rendering or primitive
// generation.
//
// This class can be used during either rendering or primitive
// generation. For primitive generation, there are two cases,
// distinguished by the flag returned by isFunction(). If this
// flag is TRUE, the texture coordinates are to be generated using
// the get(point, normal) method, which uses a software texture
// coordinate function. (This process is also used for texture
// coordinates that are generated by default when necessary - in this
// case, the function does a linear map across two sides of the
// bounding box of the shape.) If the isFunction() flag is FALSE, the
// coordinates are accessed directly from the element using the
// get(index) method.
//
// For GL rendering, there is an additional case. If
// needCoordinates() returns FALSE, no texture coordinates need to be
// sent at all, and the bundle does not have to be used for anything
// else. Otherwise, send(index) should be used.
//
//////////////////////////////////////////////////////////////////////////////
SoEXTENDER class SoTextureCoordinateBundle : public SoBundle {
public:
// Constructor - takes the action the bundle is used for and a
// flag to indicate whether the bundle is being used for
// rendering. If this is TRUE, the bundle can be used to send
// texture coordinates to GL. If it is FALSE, the setUpDefault
// flag (default TRUE) indicates whether to set up a texture
// coordinate function if the binding is DEFAULT. Shapes can pass
// FALSE here if they are picking and want to delay computation of
// the texture coordinates until an intersection is found.
SoTextureCoordinateBundle(SoAction *action, SbBool forRendering,
SbBool setUpDefault = TRUE);
// Destructor
~SoTextureCoordinateBundle();
// Returns TRUE if texture coordinates are needed at all
SbBool needCoordinates() const { return needCoords; }
// return value to determine which get() to use.
SbBool isFunction() const { return isFunc; }
// Returns texture coordinate computed by function during
// primitive generation or rendering
SbVec4f get(const SbVec3f &point, const SbVec3f &normal) const
{ return texCoordElt->get(point, normal); }
// Returns indexed texture coordinate during primitive generation
// or rendering
SbVec4f get(int index) const
{ if (tCoords) return(SbVec4f(tCoords[index][0],tCoords[index][1],
0.0, 1.0));
else return texCoordElt->get4(index); }
// Sends indexed texture coordinate to GL during rendering
void send(int index) const { GLTexCoordElt->send(index); }
private:
// TextureCoordinate elements:
const SoTextureCoordinateElement *texCoordElt;
const SoGLTextureCoordinateElement *GLTexCoordElt;
SbBool needCoords; // Texture coordinates are needed
SbBool isFunc; // Coordinates generated by function
SbBool isRendering; // Bundle being used for rendering
SbBool setFunction; // We set default coord func in state
// These indicate the dimensions used for S and T for default
// texture coordinate generation
int coordS, coordT;
// These hold the vectors used for default texture coordinate generation
SbVec4f sVector, tVector;
// This holds the texture coords from a vertexProperty node:
const SbVec2f * tCoords;
// Sets up bundle for primitive generation or rendering
void setUpForPrimGen(SoAction *action,
SbBool setUpDefault);
void setUpForGLRender(SoAction *action);
// Sets up for default texture coordinate generation
void setUpDefaultCoordSpace(SoAction *action);
// Callback registered with SoTextureCoordinateElement for
// computing texture coordinate from point and normal - used for
// default coordinate generation. The userData arg will be "this".
static const SbVec4f &generateCoord(void *userData,
const SbVec3f &point,
const SbVec3f &normal);
// Callback registered with SoGLTextureCoordinateElement for
// setting up GL texture generation for default coordinates. The
// userData arg will be "this".
static void setUpTexGen(void *userData);
};
#endif /* _SO_TEXTURE_COORDINATE_BUNDLE */
|
5f9ec1922e023efee70c1ffddffc1eec7811bc8c | edb4f249883679792e689eea9fcf969f331c28ba | /leetcode/637_averageoflevelsinbinarytree.cpp | 575a161b49a91d4352d696dee6f7a210ed568b48 | [] | no_license | pavelsimo/ProgrammingContest | 2845bddc2a61444bf2c667aa5f77e34f7a324ebc | a2c52be868bcd480a682b872fed85b344731497b | refs/heads/master | 2021-01-25T03:48:05.415007 | 2017-11-11T14:39:51 | 2017-11-11T14:39:51 | 25,308,102 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,161 | cpp | 637_averageoflevelsinbinarytree.cpp | /* ========================================================================
$File:
$Date:
$Creator: Pavel Simo
======================================================================== */
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
typedef long long llong;
class Solution {
public:
vector<double> averageOfLevels(TreeNode* root) {
vector<double> res;
if (root == NULL)
return res;
queue<TreeNode*> q;
q.push(root);
while(!q.empty()) {
int n = q.size();
llong sum = 0;
for(int i = 0; i < n; ++i) {
TreeNode *cur = q.front();
q.pop();
sum += cur->val;
if (cur->left != NULL)
q.push(cur->left);
if (cur->right != NULL)
q.push(cur->right);
}
if (n > 0)
res.push_back(1.0*sum / n);
}
return res;
}
};
|
81d2402d70b89045b6d85b17867350811422bdd1 | 7ee38191fdfcc5c59ab08c0f1748f2fc52fa959e | /Integer.h | 177c1910e5b54c3f4cbe9a9a86db596f6abcdb58 | [] | no_license | gnom6584/Fft_course_work | 2c6bfe610ae8f4840863fb009af0ea4be15b4fb4 | a1e240d5fc627732bd2be1c04ca29ab4bf740646 | refs/heads/master | 2023-05-23T15:18:58.436381 | 2021-06-17T18:48:19 | 2021-06-17T18:48:19 | 375,441,555 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,571 | h | Integer.h | //
// Created by Gnome on 17.06.2021.
//
#include <iostream>
#include "dft.h"
#ifndef FFT__INTEGER_H_
#define FFT__INTEGER_H_
inline std::vector<int> normalize(const std::vector<int>& input_number) {
auto N = std::size(input_number);
std::vector<int> number(N);
for (auto i = 0u; i < N; ++i)
number[i] = input_number[N - 1 - i];
for (int i = 0; i < N; ++i) {
while (number[i] >= 10) {
number[i] -= 10;
if (N <= i + 1) {
number.push_back(0);
N++;
}
number[i + 1] += 1;
}
}
for (auto i = 0u; i < N / 2; ++i) {
const auto temp = number[i];
number[i] = number[N - 1 - i];
number[N - 1 - i] = temp;
}
return number;
}
class Integer {
public:
[[maybe_unused]] const static Integer zero;
explicit Integer(const std::string& str_number) {
const auto size = std::size(str_number);
using namespace std;
if(size == 0)
throw length_error("");
if(size != 1) {
if (str_number.starts_with("0"))
throw invalid_argument(str_number);
}
is_negative = str_number.starts_with("-");
bool skip_first = is_negative || str_number.starts_with("+");
if(is_negative && size == 1)
throw invalid_argument(str_number);
for (const auto& num : str_number) {
if(skip_first) {
skip_first = false;
continue;
}
if(!isdigit(num))
throw invalid_argument(str_number);
digits.emplace_back(num - 48);
}
}
[[nodiscard]] bool is_zero() const {
return digits[0] == 0;
}
Integer operator*(const Integer& other) const {
if(other.is_zero() || is_zero())
return Integer("0");
const auto this_digits_size = std::size(digits);
const auto other_digits_size = std::size(other.digits);
const auto diff = std::abs((int)other_digits_size - (int)this_digits_size);
const auto size = std::max(other_digits_size, this_digits_size);
const auto size_2 = size * 2;
using namespace std;
vector<Complex> a(size_2);
vector<Complex> b(size_2);
for (int i = 0; i < this_digits_size; ++i)
a[i] = digits[i];
for (int i = 0; i < other_digits_size; ++i)
b[i] = other.digits[i];
const auto ft_a = fft(a);
const auto ft_b = fft(b);
vector<Complex> mul_product(size_2);
for (int i = 0; i < size_2; ++i)
mul_product[i] = ft_a[i] * ft_b[i];
const auto ift_product = i_fft(mul_product);
vector<int> result_digits(size_2 - 1 - diff);
for (int i = 0; i < size_2 - 1; ++i)
result_digits[i] = round(ift_product[i].real());
return Integer(normalize(result_digits), is_negative ^ other.is_negative);
}
bool operator==(const Integer& other) const {
return digits == other.digits;
}
private:
explicit Integer(std::vector<int> number, bool negative) noexcept : digits(std::move(number)), is_negative(negative) {
}
std::vector<int> digits;
bool is_negative;
friend std::ostream& operator << (std::ostream& os, const Integer& integer);
};
std::ostream& operator << (std::ostream& os, const Integer& integer) {
if(integer.is_negative)
os << "-";
for(auto digit : integer.digits)
os << digit;
return os;
}
#endif //FFT__INTEGER_H_
|
cf8d51d3ba9400c97ca752a7e2ee24effb4f23a1 | 0cd47cd4554fb36c28becdf36dfbac02443e8b03 | /Lab 3b - aula20170510/ptr5.cpp | 45a37e6cd817cd7333f406dc415b4ed1ca74f9aa | [] | no_license | amadojoao/MTP | 77dfb069acdc4a8aed4cdc6f027c25340f61b33e | bf11b7b76cb8f39d8fd88745a7b1a007f3982c40 | refs/heads/master | 2021-01-19T14:24:59.163083 | 2017-09-20T16:31:00 | 2017-09-20T16:31:00 | 88,161,407 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 573 | cpp | ptr5.cpp | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define N 1000
int main ()
{
srand(time(NULL));
int i, numero, contagem = 0;
int vetor[N];
unsigned char *p;
for(i=0; i < N; i++)
vetor[i] = rand();
p = (unsigned char *) vetor;
printf("Escolha um numero entre 0 e 255: ");
scanf("%d", &numero);
for (i=0; i < sizeof(vetor); i++)
if(p[i] == numero){
contagem++;
printf("Em %p, temos %d\n", p+i, p[i]);
}
printf("%d bytes com %d entre %p e %p\n", contagem, numero, p, p+sizeof(vetor));
return 0;
}
|
8d8a8554b5abdf6032337847ecbf97c22775da7f | b86d4fe35f7e06a1981748894823b1d051c6b2e5 | /UVa/11878 Homework Checker.cpp | d9a99f1a27371c06b870fd0d245dd728a4bc5486 | [] | no_license | sifat-mbstu/Competitive-Programming | f138fa4f7a9470d979106f1c8106183beb695fd2 | c6c28979edb533db53e9601073b734b6b28fc31e | refs/heads/master | 2021-06-26T20:18:56.607322 | 2021-04-03T04:52:20 | 2021-04-03T04:52:20 | 225,800,602 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 95 | cpp | 11878 Homework Checker.cpp | #include <bits/stdc++.h>
using namespace std;
int main()
{
int a,b,c;
char sign ,c;
}
|
5ed1ea169be3b9e286bfa283794f84f0a2de99c8 | 7e8386702eed715447098c554d599c718b17345e | /Lab 2-Heap/Not working heap_ptr/heapptr.cpp | fbeb2d3fb6c33f36c0228f0e9325c72737826be1 | [] | no_license | nithinjs88/ADSA_LAB_2014 | 589b3b350e063f8b099daecb3d7335a13dc71830 | a735971f2b5904eabbc110d2c540d4f05812819e | refs/heads/master | 2021-01-20T09:41:14.176114 | 2015-06-11T09:48:14 | 2015-06-11T09:48:14 | 35,878,639 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,870 | cpp | heapptr.cpp | #include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>
#include "common_functions.cpp"
using namespace std;
#define DEBUG 1
#define dout if (DEBUG) cout
#define dout15 if (DEBUG && newKey==15) cout
#define ifdebug if (DEBUG)
#define GET_MAX "getmax"
#define EXTRACT_MAX "extractmax"
#define INCREASE_KEY "increasekey"
#define INSERT "insert"
class HeapNode {
public:
HeapNode(int id, string &name) {
this->id = id;
this->name = name;
this->left = NULL;
this->right= NULL;
}
std::string getName() {
return name;
}
int getID() {
return id;
}
bool isNameEqual(string &secondname) {
return name == secondname;
}
bool isIDEqual(int secondid) {
return id == secondid;
}
void pointToLeft(HeapNode *leftnode) {
this->left = leftnode;
}
HeapNode *getLeft() {
return left;
}
void pointToRight(HeapNode *rightnode) {
this->right = rightnode;
}
HeapNode *getRight() {
return right;
}
void pointToParent(HeapNode *parentnode) {
this->parent = parentnode;
}
HeapNode *getParent() {
return parent;
}
private:
string name;
int id;
HeapNode *left;
HeapNode *right;
HeapNode *parent;
};
class MaxHeap {
public:
void insertHeapNode(HeapNode* ptr);
private:
HeapNode* root = NULL;
HeapNode* tail = NULL;
HeapNode* getNewEleParent();
void maxHeapify(HeapNode* ptr);
int size = 0;
};
void maxHeapify(HeapNode* ptr){
if(ptr != null) {
int eleAtIdx = ptr->getId();
if(ptr->getLeft() && ptr->getRight()) {
int leftEle = ptr->getLeft()->getId();
int rightEle = ptr->getRight()->getId();
if(leftEle >eleAtIdx && leftEle>=rightEle) {
} else if(rightEle >eleAtIdx && rightEle>=leftEle) {
}
}
int leftIdx = getLeftChildIdx(index);
int rightIdx = getRightChildIdx(index);
if(isValidIdx(leftIdx)) {
if(isValidIdx(rightIdx)) {
int maxIdx = index;
if(heapPtr[leftIdx] > eleAtIdx) {
maxIdx = leftIdx;
}
if(heapPtr[rightIdx] > heapPtr[maxIdx]) {
maxIdx = rightIdx;
}
if(maxIdx != index) {
swap(maxIdx,index);
heapify(maxIdx);
}
} else {
if(heapPtr[leftIdx] > eleAtIdx) {
swap(index,leftIdx);
}
}
}
}
}
HeapNode* MaxHeap:: getNewEleParent() {
if(tail != null) {
HeapNode* ptr = root;
int num = getBinary(size);
string str = convertIntToString(num);
if(str.size() > 1) {
for(int i=1;i<str.size()-1;i++) {
char ch = str.at(i);
if(ch == 48) {
ptr = ptr->left;
} else if(ch == 49){
ptr = ptr->right;
}
return ptr;
}
} else {
return root;
}
}
}
void MaxHeap::insertHeapNode(HeapNode* ptr){
if(root == NULL) {
root = tail = ptr;
} else {
HeapNode* parent = getNewEleParent();
if(size %2 == 0) {
parent.setRight(ptr);
} else {
parent.setLeft(ptr);
}
ptr.setParent(parent);
}
size++;
}
}
int main(int argc,char*argv[]) {
}
|
1ca8be80676b00397cff719045f17b35b20b10bf | 2eeab40a405a7b27a52386f52f6f9753672cde78 | /Old_items/Toph/Clock_Math.cpp | d01a9fb604a323575fefacd2ffd9bfffd9944c80 | [] | no_license | rifatr/Competitive-Programming | c562c56f5090b9b76510d8c57e74a2c90d723643 | e802d9e73624607904223fddf7f29950fa429341 | refs/heads/master | 2023-05-24T02:02:56.062656 | 2023-05-22T08:08:02 | 2023-05-22T08:08:02 | 611,465,080 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 282 | cpp | Clock_Math.cpp | #include <bits/stdc++.h>
using namespace std;
int main()
{
double h, m, ha, ma;
cin >> h >> m;
ha = h * 30;
ha += (m / 60) * 30;
ma = m * 6;
double ans = ha - ma;
if(ans > 180.0)
ans = 360 - ans;
cout << fixed << setprecision(4) << abs(ans) << endl;
return 0;
} |
f5a8117982eebc0e7099c67537988748a001b44d | 55822e9e9222134dfb7e3b042536e7df87fff2bc | /Source/LostInSpace/AI/StateMachine/SSMNode.cpp | ddd30b8f1f165fbae4aa87ae93f4eb49c11ce7a6 | [] | no_license | bpeake13/LostInSpace | 378b3f07b8a5a3bee17b531b39866f33cb3f3c70 | a8518171bb4f2966eaf72d85bb5f7d1e88003a8f | refs/heads/master | 2016-09-05T10:59:08.721607 | 2015-05-05T01:08:34 | 2015-05-05T01:08:34 | 33,699,861 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 331 | cpp | SSMNode.cpp | // Fill out your copyright notice in the Description page of Project Settings.
#include "LostInSpace.h"
#include "SSMNode.h"
void USSMNode::Tick(UHSMSimpleStateMachineNode* machine){
}
USSMNode* USSMNode::GetNext(int transitionId)
{
if (transitionId >= NextStates.Num())
return NULL;
return NextStates[transitionId];
}
|
cf7bc482423c1cfdf0883286b48d4341895c2941 | 8ae9bdbb56622e7eb2fe7cf700b8fe4b7bd6e7ae | /llvm-3.8.0-r267675/lib/Target/MMPULite/MCTargetDesc/MMPULiteMCAsmInfo.h | 87607d441806cd4f228a5cf8551b6814f900dcea | [
"NCSA"
] | permissive | mapu/toolchains | f61aa8b64d1dce5e618f0ff919d91dd5b664e901 | 3a6fea03c6a7738091e980b9cdee0447eb08bb1d | refs/heads/master | 2021-09-16T00:07:16.731713 | 2017-12-29T04:09:01 | 2017-12-29T04:09:01 | 104,563,481 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 783 | h | MMPULiteMCAsmInfo.h | //===-- MMPULiteMCAsmInfo.h - MMPULite asm properties ----------------*- C++ -*--===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains the declaration of the MMPULiteMCAsmInfo class.
//
//===----------------------------------------------------------------------===//
#ifndef MMPULITETARGETASMINFO_H
#define MMPULITETARGETASMINFO_H
#include "llvm/MC/MCAsmInfoELF.h"
namespace llvm {
class Triple;
class MMPULiteELFMCAsmInfo : public MCAsmInfoELF {
public:
explicit MMPULiteELFMCAsmInfo(const Triple &TT);
};
} // namespace llvm
#endif
|
8270f7bb9e3f754b996caff9a2880e3d491c0f24 | 0841c948188711d194835bb19cf0b4dae04a5695 | /mds/sources/thelib/src/mds/cmdmanager.cpp | bb5343c0fe201f6d00784bdaa4b930dc767e9cba | [] | no_license | gjhbus/sh_project | 0cfd311b7c0e167e098bc4ec010822f1af2d0289 | 1d4d7df4e92cff93aba9d28226d3dbce71639ed6 | refs/heads/master | 2020-06-15T16:11:33.335499 | 2016-06-15T03:41:22 | 2016-06-15T03:41:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,739 | cpp | cmdmanager.cpp | #include "mds/cmdmanager.h"
#include "mds/mdsprocess.h"
#include "mds/cmdworker.h"
CmdManager::CmdManager(uint32_t count) {
count_ = count;
mddb_ = NULL;
}
CmdManager::~CmdManager() {
for (int i = 0; i < count_; i++) {
delete worker_[i];
}
if ( NULL != mddb_ ) {
delete mddb_;
mddb_ = NULL;
}
}
void CmdManager::Start() {
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED);
pthread_attr_setschedpolicy(&attr, SCHED_RR);
struct sched_param param;
param.sched_priority = 99;
pthread_attr_setschedparam(&attr, ¶m);
vector<int> cpu_ids;
for (int i = 0; i < (int)worker_.size(); i++) {
pthread_t thread;
int rs = pthread_create(&thread, &attr, CmdWorker::Start, worker_[i]);
if ( rs ) {
FATAL("pthread_create failed, errno is %d", rs);
exit(0);
}
cpu_ids.clear();
cpu_ids.push_back(((CmdWorker*)worker_[i])->cpu_id_);
if ( !setaffinityNp(cpu_ids, thread) ) {
FATAL("ThreadID:%d cpuID:%d setaffinityNp failed.", i, ((CmdWorker*)worker_[i])->cpu_id_);
exit(0);
}
usleep(100);
}
pthread_attr_destroy(&attr);
}
void CmdManager::Close() {
for (int i = 0; i < count_; i++)
worker_[i]->Close();
if ( NULL != mddb_ )
mddb_->Close();
}
void CmdManager::Clear() {
for (int i = 0; i < count_; i++)
worker_[i]->Clear();
if ( NULL != mddb_ )
mddb_->Clear();
}
bool CmdManager::AddWorker(CmdWorker *worker) {
worker_.push_back(worker);
return true;
}
void CmdManager::DBCompact() {
mddb_->DBCompact();
}
void CmdManager::FinishMigrate() {
mddb_->FinishMigrate();
}
|
7a8c0311710bef13b02a39ae24e4fa7391cafdd3 | 3da596a2ea8617d0f150662e3b0fdc763ea936e1 | /iree/compiler/Utils/TracingUtils.h | c81cbb2dca1a429d33ec983ae6564985ed4ef13b | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | 1121589/iree | e0f1a40c02f195a1b58c305e38b37952f53c8993 | 22a905c485e3ae2ff9743dc9d195de3b90b08ed5 | refs/heads/main | 2023-05-04T23:17:19.839076 | 2021-05-13T06:17:21 | 2021-05-13T06:17:21 | 367,058,873 | 0 | 0 | Apache-2.0 | 2021-05-13T13:33:42 | 2021-05-13T13:33:41 | null | UTF-8 | C++ | false | false | 2,048 | h | TracingUtils.h | // Copyright 2021 Google LLC
//
// 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef IREE_COMPILER_UTILS_TRACINGUTILS_H_
#define IREE_COMPILER_UTILS_TRACINGUTILS_H_
#include "iree/base/tracing.h"
#include "mlir/Pass/Pass.h"
#include "mlir/Pass/PassInstrumentation.h"
namespace mlir {
namespace iree_compiler {
// Instruments passes using IREE's runtime tracing support.
//
// Usage:
// passManager.addInstrumentation(std::make_unique<PassTracing>());
struct PassTracing : public PassInstrumentation {
PassTracing() {}
~PassTracing() override = default;
#if IREE_TRACING_FEATURES & IREE_TRACING_FEATURE_INSTRUMENTATION
// Note: we could also trace pipelines and analyses.
void runBeforePass(Pass *pass, Operation *op) override {
IREE_TRACE_ZONE_BEGIN_EXTERNAL(z0, __FILE__, strlen(__FILE__), __LINE__,
pass->getName().data(),
pass->getName().size(), NULL, 0);
passTraceZonesStack.push_back(z0);
}
void runAfterPass(Pass *pass, Operation *op) override {
IREE_TRACE_ZONE_END(passTraceZonesStack.back());
passTraceZonesStack.pop_back();
}
void runAfterPassFailed(Pass *pass, Operation *op) override {
IREE_TRACE_ZONE_END(passTraceZonesStack.back());
passTraceZonesStack.pop_back();
}
#endif // IREE_TRACING_FEATURES & IREE_TRACING_FEATURE_INSTRUMENTATION
llvm::SmallVector<iree_zone_id_t, 8> passTraceZonesStack;
};
} // namespace iree_compiler
} // namespace mlir
#endif // IREE_COMPILER_UTILS_TRACINGUTILS_H_
|
b42123461fe2f4a88f3fb1ff6974c8c3cb4bec6b | f8f2bd26df4d3bae5a59c05501997a5e2f414f02 | /Vector/Vectoroperation.cpp | e1d3c502ac5a5d0cc20a587a3f284a728804042e | [] | no_license | abhi-1993/geeksstldsa | 05c45f6d8542c3f45e87fca4cf8fb1bf87b34eb7 | 57ce2a9b7bc5ac6c2182707f740ae3cdb354820c | refs/heads/main | 2023-02-08T15:35:44.161212 | 2021-01-02T16:08:17 | 2021-01-02T16:08:17 | 326,166,602 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,809 | cpp | Vectoroperation.cpp | #include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
bool sortcol(const vector<int>& v1, const vector<int>& v2)
{
cout<<"\nV1[1] "<<v1[1] <<" "<<"V2[1]"<<v2[1];
return v1[1] < v2 [1];
}
int main()
{
vector<vector<int> > vect { {3,4,5},
{6,9,5},
{8,1,7}};
//loops to print 2d array
for(int i = 0; i < vect.size(); i++)
{
for(int j = 0; j < vect[i].size(); j++ )
cout<<"Vect"<<"["<<i<<"]"<<"["<<j<<"]"<< vect[i][j] << "\n";
cout<<endl;
}
//sort function to sort the 2d vector
// for(int i = 0; i < 3 ; i++)
// sort(vect[i].rbegin(),vect[i].rend());
// cout<<"\n 2D Vector after sort function \n";
// for(int i = 0; i < vect.size(); i++)
// {
// for(int j = 0; j < vect[i].size(); j++ )
// cout<<"Vect"<<"["<<i<<"]"<<"["<<j<<"]"<< vect[i][j] << "\n";
// cout<<endl;
// }
//sort function by implementing own comparator function to sort on particular column
sort(vect.begin(), vect.end(), sortcol);
cout<<"\n 2D Vector after comparator sort on 2nd column function \n";
for(int i = 0; i < vect.size(); i++)
{
for(int j = 0; j < vect[0].size(); j++ )
cout<<"Vect"<<"["<<i<<"]"<<"["<<j<<"]"<< vect[i][j] << "\n";
cout<<endl;
}
bool vector_empty_check = vect.empty();
cout<<"Result of vector empty or not\n"<<vector_empty_check;
cout<<"Checking the capacity of the vector\n"<<vect.capacity()<<" ";
vect.clear();
vector_empty_check = vect.empty();
cout<<"Checking whether vector is empty or not after clear operation\n"<<vector_empty_check;
return 0;
} |
ff90bb7b762d8c7b73dd442b804f5539d3537f5c | 01bcef56ade123623725ca78d233ac8653a91ece | /common/xbox/xbox_launch.h | b602f6e8cde0f41588b9acc925c3d153de444a9d | [
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | SwagSoftware/Kisak-Strike | 1085ba3c6003e622dac5ebc0c9424cb16ef58467 | 4c2fdc31432b4f5b911546c8c0d499a9cff68a85 | refs/heads/master | 2023-09-01T02:06:59.187775 | 2022-09-05T00:51:46 | 2022-09-05T00:51:46 | 266,676,410 | 921 | 123 | null | 2022-10-01T16:26:41 | 2020-05-25T03:41:35 | C++ | WINDOWS-1252 | C++ | false | false | 11,700 | h | xbox_launch.h | //========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose: Xbox Launch Routines.
//
//=====================================================================================//
#ifndef _XBOX_LAUNCH_H_
#define _XBOX_LAUNCH_H_
#pragma once
#ifndef _CERT
#pragma comment( lib, "xbdm.lib" )
#endif
// id and version are used to tag the data blob, currently only need a singe hardcoded id
// when the version and id don't match, the data blob is not ours
#define VALVE_LAUNCH_ID (('V'<<24)|('A'<<16)|('L'<<8)|('V'<<0))
#define VALVE_LAUNCH_VERSION 1
// launch flags
#define LF_ISDEBUGGING 0x80000000 // set if session was active prior to launch
#define LF_INTERNALLAUNCH 0x00000001 // set if launch was internal (as opposed to dashboard)
#define LF_EXITFROMINSTALLER 0x00000002 // set if exit was from an installer
#define LF_EXITFROMGAME 0x00000004 // set if exit was from a game
#define LF_EXITFROMCHOOSER 0x00000008 // set if exit was from the chooser
#define LF_WARMRESTART 0x00000010 // set if game wants to restart self (skips intro movies)
#define LF_INSTALLEDTOCACHE 0x00000040 // set if installer populated or validated cache partition
#define LF_UNKNOWNDATA 0x00000080
#pragma pack(1)
struct launchHeader_t
{
unsigned int id;
unsigned int version;
unsigned int flags;
int nUserID;
int nCtrlr2Storage[4];
char nSlot2Ctrlr[4];
char nSlot2Guest[4];
int numGameUsers;
int bForceEnglish;
// increments at each engine re-launch
DWORD nAttractID;
// for caller defined data, occurs after this header
// limited to slightly less than MAX_LAUNCH_DATA_SIZE
unsigned int nDataSize;
};
#pragma pack()
// per docs, no larger than MAX_LAUNCH_DATA_SIZE
union xboxLaunchData_t
{
launchHeader_t header;
char data[MAX_LAUNCH_DATA_SIZE];
};
//--------------------------------------------------------------------------------------
// Simple class to wrap the peristsent launch payload.
//
// Can be used by an application that does not use tier0 (i.e. the launcher).
// Primarily designed to be anchored in tier0, so multiple systems can easily query and
// set the persistent payload.
//--------------------------------------------------------------------------------------
class CXboxLaunch
{
public:
CXboxLaunch()
{
ResetLaunchData();
}
void ResetLaunchData()
{
// invalid until established
// nonzero identifies a valid payload
m_LaunchDataSize = 0;
m_Launch.header.id = 0;
m_Launch.header.version = 0;
m_Launch.header.flags = 0;
m_Launch.header.nUserID = XBX_INVALID_USER_ID;
m_Launch.header.bForceEnglish = false;
m_Launch.header.nCtrlr2Storage[0] = XBX_INVALID_STORAGE_ID;
m_Launch.header.nCtrlr2Storage[1] = XBX_INVALID_STORAGE_ID;
m_Launch.header.nCtrlr2Storage[2] = XBX_INVALID_STORAGE_ID;
m_Launch.header.nCtrlr2Storage[3] = XBX_INVALID_STORAGE_ID;
m_Launch.header.nSlot2Ctrlr[0] = 0;
m_Launch.header.nSlot2Ctrlr[1] = 1;
m_Launch.header.nSlot2Ctrlr[2] = 2;
m_Launch.header.nSlot2Ctrlr[3] = 3;
m_Launch.header.nSlot2Guest[0] = 0;
m_Launch.header.nSlot2Guest[1] = 0;
m_Launch.header.nSlot2Guest[2] = 0;
m_Launch.header.nSlot2Guest[3] = 0;
m_Launch.header.numGameUsers = 0;
m_Launch.header.nAttractID = 0;
m_Launch.header.nDataSize = 0;
}
// Returns how much space can be used by caller
int MaxPayloadSize()
{
return sizeof( xboxLaunchData_t ) - sizeof( launchHeader_t );
}
bool SetLaunchData( void *pData, int dataSize, int flags = 0 )
{
#if defined( _DEMO )
if ( pData && ( flags & LF_UNKNOWNDATA ) )
{
// not ours, put the demo structure back as-is
XSetLaunchData( pData, dataSize );
m_LaunchDataSize = dataSize;
return true;
}
#endif
if ( pData && dataSize && dataSize > MaxPayloadSize() )
{
// not enough room
return false;
}
if ( pData && dataSize && dataSize <= MaxPayloadSize() )
{
memcpy( m_Launch.data + sizeof( launchHeader_t ), pData, dataSize );
m_Launch.header.nDataSize = dataSize;
}
else
{
m_Launch.header.nDataSize = 0;
}
flags |= LF_INTERNALLAUNCH;
#if !defined( _CERT )
if ( DmIsDebuggerPresent() )
{
flags |= LF_ISDEBUGGING;
}
#endif
m_Launch.header.id = VALVE_LAUNCH_ID;
m_Launch.header.version = VALVE_LAUNCH_VERSION;
m_Launch.header.flags = flags;
XSetLaunchData( &m_Launch, MAX_LAUNCH_DATA_SIZE );
// assume successful, mark as valid
m_LaunchDataSize = MAX_LAUNCH_DATA_SIZE;
return true;
}
//--------------------------------------------------------------------------------------
// Returns TRUE if the launch data blob is available. FALSE otherwise.
// Caller is expected to validate and interpret contents based on ID.
//--------------------------------------------------------------------------------------
bool GetLaunchData( unsigned int *pID, void **pData, int *pDataSize )
{
if ( !m_LaunchDataSize )
{
// purposely not doing this in the constructor (unstable as used by tier0), but on first fetch
bool bValid = false;
DWORD dwLaunchDataSize;
DWORD dwStatus = XGetLaunchDataSize( &dwLaunchDataSize );
if ( dwStatus == ERROR_SUCCESS && dwLaunchDataSize <= MAX_LAUNCH_DATA_SIZE )
{
dwStatus = XGetLaunchData( (void*)&m_Launch, dwLaunchDataSize );
if ( dwStatus == ERROR_SUCCESS )
{
bValid = true;
m_LaunchDataSize = dwLaunchDataSize;
}
}
if ( !bValid )
{
ResetLaunchData();
}
}
// a valid launch payload could be ours (re-launch) or from an alternate booter (demo launcher)
if ( m_LaunchDataSize == MAX_LAUNCH_DATA_SIZE && m_Launch.header.id == VALVE_LAUNCH_ID && m_Launch.header.version == VALVE_LAUNCH_VERSION )
{
// internal recognized format
if ( pID )
{
*pID = m_Launch.header.id;
}
if ( pData )
{
*pData = m_Launch.data + sizeof( launchHeader_t );
}
if ( pDataSize )
{
*pDataSize = m_Launch.header.nDataSize;
}
}
else if ( m_LaunchDataSize )
{
// not ours, unknown format, caller interprets
if ( pID )
{
// assume payload was packaged with an initial ID
*pID = *(unsigned int *)m_Launch.data;
}
if ( pData )
{
*pData = m_Launch.data;
}
if ( pDataSize )
{
*pDataSize = m_LaunchDataSize;
}
}
else if ( !m_LaunchDataSize )
{
// mark for caller as all invalid
if ( pID )
{
*pID = 0;
}
if ( pData )
{
*pData = NULL;
}
if ( pDataSize )
{
*pDataSize = 0;
}
}
// valid when any data is available (not necessarily valve's tag)
return ( m_LaunchDataSize != 0 );
}
//--------------------------------------------------------------------------------------
// Returns TRUE if the launch data blob is available. FALSE otherwise.
// Data blob could be ours or not.
//--------------------------------------------------------------------------------------
bool RestoreLaunchData()
{
return GetLaunchData( NULL, NULL, NULL );
}
//--------------------------------------------------------------------------------------
// Restores the data blob. If the data blob is not ours, resets it.
//--------------------------------------------------------------------------------------
void RestoreOrResetLaunchData()
{
RestoreLaunchData();
#if !defined( _DEMO )
if ( m_Launch.header.id != VALVE_LAUNCH_ID || m_Launch.header.version != VALVE_LAUNCH_VERSION )
{
// not interested in somebody else's data
ResetLaunchData();
}
#endif
}
//--------------------------------------------------------------------------------------
// Returns OUR internal launch flags.
//--------------------------------------------------------------------------------------
int GetLaunchFlags()
{
// establish the data
RestoreOrResetLaunchData();
#if defined( _DEMO )
if ( m_Launch.header.id && m_Launch.header.id != VALVE_LAUNCH_ID )
{
return 0;
}
#endif
return m_Launch.header.flags;
}
void SetLaunchFlags( unsigned int ufNewFlags )
{
#if defined( _DEMO )
if ( m_Launch.header.id && m_Launch.header.id != VALVE_LAUNCH_ID )
{
return;
}
#endif
m_Launch.header.flags = ufNewFlags;
}
void GetStorageID( int storageID[4] )
{
RestoreOrResetLaunchData();
#if defined( _DEMO )
if ( m_Launch.header.id && m_Launch.header.id != VALVE_LAUNCH_ID )
{
storageID[0] = XBX_INVALID_STORAGE_ID;
storageID[1] = XBX_INVALID_STORAGE_ID;
storageID[2] = XBX_INVALID_STORAGE_ID;
storageID[3] = XBX_INVALID_STORAGE_ID;
return;
}
#endif
memcpy( storageID, m_Launch.header.nCtrlr2Storage, sizeof( m_Launch.header.nCtrlr2Storage ) );
}
void SetStorageID( int const storageID[4] )
{
#if defined( _DEMO )
if ( m_Launch.header.id && m_Launch.header.id != VALVE_LAUNCH_ID )
{
return;
}
#endif
memcpy( m_Launch.header.nCtrlr2Storage, storageID, sizeof( m_Launch.header.nCtrlr2Storage ) );
}
void GetSlotUsers( int &numGameUsers, char nSlot2Ctrlr[4], char nSlot2Guest[4] )
{
RestoreOrResetLaunchData();
#if defined( _DEMO )
if ( m_Launch.header.id && m_Launch.header.id != VALVE_LAUNCH_ID )
{
numGameUsers = 0;
nSlot2Ctrlr[0] = 0;
nSlot2Ctrlr[1] = 1;
nSlot2Ctrlr[2] = 2;
nSlot2Ctrlr[3] = 3;
nSlot2Guest[0] = 0;
nSlot2Guest[1] = 0;
nSlot2Guest[2] = 0;
nSlot2Guest[3] = 0;
return;
}
#endif
numGameUsers = m_Launch.header.numGameUsers;
memcpy( nSlot2Ctrlr, m_Launch.header.nSlot2Ctrlr, sizeof( m_Launch.header.nSlot2Ctrlr ) );
memcpy( nSlot2Guest, m_Launch.header.nSlot2Guest, sizeof( m_Launch.header.nSlot2Guest ) );
}
void SetSlotUsers( int numGameUsers, char const nSlot2Ctrlr[4], char const nSlot2Guest[4] )
{
#if defined( _DEMO )
if ( m_Launch.header.id && m_Launch.header.id != VALVE_LAUNCH_ID )
{
return;
}
#endif
m_Launch.header.numGameUsers = numGameUsers;
memcpy( m_Launch.header.nSlot2Ctrlr, nSlot2Ctrlr, sizeof( m_Launch.header.nSlot2Ctrlr ) );
memcpy( m_Launch.header.nSlot2Guest, nSlot2Guest, sizeof( m_Launch.header.nSlot2Guest ) );
}
int GetUserID( void )
{
RestoreOrResetLaunchData();
#if defined( _DEMO )
if ( m_Launch.header.id && m_Launch.header.id != VALVE_LAUNCH_ID )
{
return XBX_INVALID_USER_ID;
}
#endif
return m_Launch.header.nUserID;
}
void SetUserID( int userID )
{
#if defined( _DEMO )
if ( m_Launch.header.id && m_Launch.header.id != VALVE_LAUNCH_ID )
{
return;
}
#endif
m_Launch.header.nUserID = userID;
}
bool GetForceEnglish( void )
{
RestoreOrResetLaunchData();
#if defined( _DEMO )
if ( m_Launch.header.id && m_Launch.header.id != VALVE_LAUNCH_ID )
{
return false;
}
#endif
return m_Launch.header.bForceEnglish ? true : false;
}
void SetForceEnglish( bool bForceEnglish )
{
#if defined( _DEMO )
if ( m_Launch.header.id && m_Launch.header.id != VALVE_LAUNCH_ID )
{
return;
}
#endif
m_Launch.header.bForceEnglish = bForceEnglish;
}
DWORD GetAttractID( void )
{
RestoreOrResetLaunchData();
#if defined( _DEMO )
if ( m_Launch.header.id && m_Launch.header.id != VALVE_LAUNCH_ID )
{
return 0;
}
#endif
return m_Launch.header.nAttractID;
}
void SetAttractID( DWORD nAttractID )
{
#if defined( _DEMO )
if ( m_Launch.header.id && m_Launch.header.id != VALVE_LAUNCH_ID )
{
return;
}
#endif
m_Launch.header.nAttractID = nAttractID;
}
void Launch( const char *pNewImageName = NULL )
{
if ( !pNewImageName )
{
#if defined( _DEMO )
pNewImageName = XLAUNCH_KEYWORD_DEFAULT_APP;
#else
pNewImageName = "default.xex";
#endif
}
XLaunchNewImage( pNewImageName, 0 );
}
private:
xboxLaunchData_t m_Launch;
DWORD m_LaunchDataSize;
};
#if defined( PLATFORM_H )
// For applications that use tier0.dll
PLATFORM_INTERFACE CXboxLaunch *XboxLaunch();
#endif
#endif
|
4320e268930fbea5ed00866905406ad6be2bf649 | 689af7ab127a24d527301cd5dc0e3ec0ec8c3940 | /inc/dg/topology/fem_weights.h | fe1b03d097e78d11757106249f86a653d17bef61 | [
"LicenseRef-scancode-other-permissive",
"MIT",
"Apache-2.0"
] | permissive | feltor-dev/feltor | 98df35a2d905e7033b90a13e4ad1b5fa3df4cb7d | cafe7d194f149e28b8e9c644a187132af95ecc0c | refs/heads/master | 2023-08-17T04:11:34.363108 | 2023-08-09T09:09:13 | 2023-08-09T09:09:13 | 14,143,578 | 30 | 13 | MIT | 2023-08-09T09:09:15 | 2013-11-05T14:29:41 | C++ | UTF-8 | C++ | false | false | 3,567 | h | fem_weights.h | #pragma once
#include "weights.h"
/*! @file
* @brief Creation functions for finite element utilities
*/
namespace dg {
namespace create{
///@cond
namespace detail
{
template<class real_type>
std::vector<real_type> fem_weights( const DLT<real_type>& dlt)
{
std::vector<real_type> x = dlt.abscissas();
std::vector<real_type> w = x;
unsigned n = x.size();
if( n== 1)
w[0] = 2;
else
{
w[0] = 0.5*(x[1] - (x[n-1]-2));
w[n-1] = 0.5*((x[0]+2) - x[n-2]);
for( unsigned i=1; i<n-1; i++)
w[i] = 0.5*(x[i+1]-x[i-1]);
}
return w;
}
}//namespace detail
///@endcond
///@addtogroup fem
///@{
/*!@class hide_fem_weights_doc
* @brief finite element weight coefficients
*
* These will emulate the trapezoidal rule for integration
* @param g The grid
* @return Host Vector
* @sa <a href="https://www.overleaf.com/read/rpbjsqmmfzyj" target="_blank">Introduction to dg methods</a>
*/
/*!@class hide_fem_inv_weights_doc
* @brief inverse finite element weight coefficients
* @param g The grid
* @return Host Vector
* @sa <a href="https://www.overleaf.com/read/rpbjsqmmfzyj" target="_blank">Introduction to dg methods</a>
*/
///@copydoc hide_fem_weights_doc
template<class real_type>
thrust::host_vector<real_type> fem_weights( const RealGrid1d<real_type>& g)
{
thrust::host_vector<real_type> v( g.size());
std::vector<real_type> w = detail::fem_weights(g.dlt());
for( unsigned i=0; i<g.N(); i++)
for( unsigned j=0; j<g.n(); j++)
v[i*g.n() + j] = g.h()/2.*w[j];
return v;
}
///@copydoc hide_fem_inv_weights_doc
template<class real_type>
thrust::host_vector<real_type> fem_inv_weights( const RealGrid1d<real_type>& g)
{
thrust::host_vector<real_type> v = fem_weights( g);
for( unsigned i=0; i<g.size(); i++)
v[i] = 1./v[i];
return v;
}
///@copydoc hide_fem_weights_doc
template<class real_type>
thrust::host_vector<real_type> fem_weights( const aRealTopology2d<real_type>& g)
{
thrust::host_vector<real_type> v( g.size());
std::vector<real_type> wx = detail::fem_weights(g.dltx());
std::vector<real_type> wy = detail::fem_weights(g.dlty());
for( unsigned i=0; i<g.size(); i++)
v[i] = g.hx()*g.hy()/4.*
wx[i%g.nx()]*
wy[(i/(g.nx()*g.Nx()))%g.ny()];
return v;
}
///@copydoc hide_fem_inv_weights_doc
template<class real_type>
thrust::host_vector<real_type> fem_inv_weights( const aRealTopology2d<real_type>& g)
{
thrust::host_vector<real_type> v = fem_weights( g);
for( unsigned i=0; i<g.size(); i++)
v[i] = 1./v[i];
return v;
}
///@copydoc hide_fem_weights_doc
template<class real_type>
thrust::host_vector<real_type> fem_weights( const aRealTopology3d<real_type>& g)
{
thrust::host_vector<real_type> v( g.size());
std::vector<real_type> wx = detail::fem_weights(g.dltx());
std::vector<real_type> wy = detail::fem_weights(g.dlty());
std::vector<real_type> wz = detail::fem_weights(g.dltz());
for( unsigned i=0; i<g.size(); i++)
v[i] = g.hx()*g.hy()*g.hz()/8.*
wx[i%g.nx()]*
wy[(i/(g.nx()*g.Nx()))%g.ny()]*
wz[(i/(g.nx()*g.ny()*g.Nx()*g.Ny()))%g.nz()];
return v;
}
///@copydoc hide_fem_inv_weights_doc
template<class real_type>
thrust::host_vector<real_type> fem_inv_weights( const aRealTopology3d<real_type>& g)
{
thrust::host_vector<real_type> v = fem_weights( g);
for( unsigned i=0; i<g.size(); i++)
v[i] = 1./v[i];
return v;
}
///@}
}//namespace create
}//namespace dg
|
cea62eabbbe0414449113fd63dbef8d59e583a89 | 96f638860c0e73e39e5c41808692ed9b06942fee | /bark/world/tests/observed_world_test.cc | 26f8ed1d7adcfb008cdeafc6aa369b0906e13b33 | [
"MIT"
] | permissive | xmyqsh/bark | 5432a7ecb40f45dbb1722202fe7a4eb8a34edd7f | 8a2aef12a37e0cc7d26b51f8b65c3832af062771 | refs/heads/master | 2022-06-15T02:49:36.484886 | 2022-06-13T15:44:33 | 2022-06-13T15:44:33 | 207,952,703 | 0 | 0 | MIT | 2022-06-13T23:59:24 | 2019-09-12T03:00:54 | C++ | UTF-8 | C++ | false | false | 15,154 | cc | observed_world_test.cc | // Copyright (c) 2020 fortiss GmbH
//
// Authors: Julian Bernhard, Klemens Esterle, Patrick Hart and
// Tobias Kessler
//
// This work is licensed under the terms of the MIT license.
// For a copy, see <https://opensource.org/licenses/MIT>.
#include "bark/world/observed_world.hpp"
#include "bark/commons/params/setter_params.hpp"
#include "bark/geometry/polygon.hpp"
#include "bark/geometry/standard_shapes.hpp"
#include "bark/models/behavior/constant_acceleration/constant_acceleration.hpp"
#include "bark/models/behavior/motion_primitives/continuous_actions.hpp"
#include "bark/models/dynamic/single_track.hpp"
#include "bark/models/execution/interpolation/interpolate.hpp"
#include "bark/world/evaluation/evaluator_collision_agents.hpp"
#include "bark/world/goal_definition/goal_definition.hpp"
#include "bark/world/goal_definition/goal_definition_polygon.hpp"
#include "bark/world/map/map_interface.hpp"
#include "bark/world/map/roadgraph.hpp"
#include "bark/world/objects/agent.hpp"
#include "bark/world/opendrive/opendrive.hpp"
#include "bark/world/tests/dummy_road_corridor.hpp"
#include "bark/world/tests/make_test_world.hpp"
#include "bark/world/tests/make_test_xodr_map.hpp"
#include "gtest/gtest.h"
using namespace bark::models::dynamic;
using namespace bark::models::behavior;
using namespace bark::models::execution;
using namespace bark::world::map;
using bark::commons::SetterParams;
using bark::commons::transformation::FrenetPosition;
using bark::commons::transformation::FrenetStateDifference;
using bark::geometry::Model3D;
using bark::geometry::Point2d;
using bark::geometry::Polygon;
using bark::geometry::Pose;
using bark::geometry::standard_shapes::CarRectangle;
using bark::geometry::standard_shapes::GenerateGoalRectangle;
using bark::world::FrontRearAgents;
using bark::world::ObservedWorld;
using bark::world::ObservedWorldPtr;
using bark::world::World;
using bark::world::WorldPtr;
using bark::world::goal_definition::GoalDefinitionPolygon;
using bark::world::objects::Agent;
using bark::world::objects::AgentPtr;
using bark::world::opendrive::OpenDriveMapPtr;
using bark::world::tests::MakeXodrMapOneRoadTwoLanes;
using StateDefinition::MIN_STATE_SIZE;
TEST(observed_world, agent_in_front_same_lane) {
auto params = std::make_shared<SetterParams>();
// Setting Up Map
OpenDriveMapPtr open_drive_map = MakeXodrMapOneRoadTwoLanes();
MapInterfacePtr map_interface = std::make_shared<MapInterface>();
map_interface->interface_from_opendrive(open_drive_map);
// Goal Definition
Polygon polygon = GenerateGoalRectangle(6,3);
std::shared_ptr<Polygon> goal_polygon(
std::dynamic_pointer_cast<Polygon>(polygon.Translate(Point2d(50, -2))));
auto goal_ptr = std::make_shared<GoalDefinitionPolygon>(*goal_polygon);
// Setting Up Agents (one in front of another)
ExecutionModelPtr exec_model(new ExecutionModelInterpolate(params));
DynamicModelPtr dyn_model(new SingleTrackModel(params));
BehaviorModelPtr beh_model(new BehaviorConstantAcceleration(params));
Polygon car_polygon = CarRectangle();
State init_state1(static_cast<int>(MIN_STATE_SIZE));
init_state1 << 0.0, 3.0, -1.75, 0.0, 5.0;
AgentPtr agent1(new Agent(init_state1, beh_model, dyn_model, exec_model,
car_polygon, params, goal_ptr, map_interface,
Model3D())); // NOLINT
State init_state2(static_cast<int>(MIN_STATE_SIZE));
init_state2 << 0.0, 10.0, -1.75, 0.0, 5.0;
AgentPtr agent2(new Agent(init_state2, beh_model, dyn_model, exec_model,
car_polygon, params, goal_ptr, map_interface,
Model3D())); // NOLINT
// Construct World
WorldPtr world(new World(params));
world->AddAgent(agent1);
world->AddAgent(agent2);
world->UpdateAgentRTree();
WorldPtr current_world_state1(world->Clone());
ObservedWorld obs_world1(current_world_state1, agent2->GetAgentId());
// Leading agent should not have an agent in front
std::pair<AgentPtr, FrenetStateDifference> leading_vehicle =
obs_world1.GetAgentInFront();
EXPECT_FALSE(static_cast<bool>(leading_vehicle.first));
// Leading agent should not have an agent in front
std::pair<AgentPtr, FrenetStateDifference> following_vehicle =
obs_world1.GetAgentBehind();
BARK_EXPECT_TRUE(static_cast<bool>(following_vehicle.first));
EXPECT_EQ(following_vehicle.first->GetAgentId(), agent1->GetAgentId());
WorldPtr current_world_state2(world->Clone());
ObservedWorld obs_world2(current_world_state2, agent1->GetAgentId());
// Agent behind should have leading agent in front
std::pair<AgentPtr, FrenetStateDifference> leading_vehicle2 =
obs_world2.GetAgentInFront();
EXPECT_TRUE(static_cast<bool>(leading_vehicle2.first));
EXPECT_EQ(leading_vehicle2.first->GetAgentId(), agent2->GetAgentId());
State init_state3(static_cast<int>(MIN_STATE_SIZE));
init_state3 << 0.0, 20.0, -1.75, 0.0, 5.0;
AgentPtr agent3(new Agent(init_state3, beh_model, dyn_model, exec_model,
polygon, params, goal_ptr, map_interface,
Model3D())); // NOLINT
world->AddAgent(agent3);
world->UpdateAgentRTree();
WorldPtr current_world_state3(world->Clone());
ObservedWorld obs_world3(current_world_state3, agent1->GetAgentId());
// Adding a third agent in front of leading agent, still leading agent
// should be in front
std::pair<AgentPtr, FrenetStateDifference> leading_vehicle3 =
obs_world3.GetAgentInFront();
EXPECT_TRUE(static_cast<bool>(leading_vehicle3.first));
EXPECT_EQ(leading_vehicle2.first->GetAgentId(), agent2->GetAgentId());
}
TEST(observed_world, agent_in_front_other_lane) {
auto params = std::make_shared<SetterParams>();
// Setting Up Map
OpenDriveMapPtr open_drive_map = MakeXodrMapOneRoadTwoLanes();
MapInterfacePtr map_interface = std::make_shared<MapInterface>();
map_interface->interface_from_opendrive(open_drive_map);
// Goal Definition
Polygon polygon = GenerateGoalRectangle(6,3);
std::shared_ptr<Polygon> goal_polygon(
std::dynamic_pointer_cast<Polygon>(polygon.Translate(Point2d(50, -2))));
auto goal_ptr = std::make_shared<GoalDefinitionPolygon>(*goal_polygon);
// Setting Up Agents (one in front of another)
ExecutionModelPtr exec_model(new ExecutionModelInterpolate(params));
DynamicModelPtr dyn_model(new SingleTrackModel(params));
BehaviorModelPtr beh_model(new BehaviorConstantAcceleration(params));
Polygon car_polygon = CarRectangle();
State init_state1(static_cast<int>(MIN_STATE_SIZE));
init_state1 << 0.0, 3.0, -1.75, 0.0, 5.0;
AgentPtr agent1(new Agent(init_state1, beh_model, dyn_model, exec_model,
car_polygon, params, goal_ptr, map_interface,
Model3D())); // NOLINT
State init_state2(static_cast<int>(MIN_STATE_SIZE));
init_state2 << 0.0, 10.0, -1.75, 0.0, 5.0;
AgentPtr agent2(new Agent(init_state2, beh_model, dyn_model, exec_model,
car_polygon, params, goal_ptr, map_interface,
Model3D())); // NOLINT
// Construct World
WorldPtr world(new World(params));
world->AddAgent(agent1);
world->AddAgent(agent2);
world->UpdateAgentRTree();
// Adding a fourth agent in right lane
State init_state4(static_cast<int>(MIN_STATE_SIZE));
init_state4 << 0.0, 5.0, -5.25, 0.0, 5.0;
AgentPtr agent4(new Agent(init_state4, beh_model, dyn_model, exec_model,
car_polygon, params, goal_ptr, map_interface,
Model3D())); // NOLINT
world->AddAgent(agent4);
world->UpdateAgentRTree();
WorldPtr current_world_state4(world->Clone());
ObservedWorld obs_world4(current_world_state4, agent4->GetAgentId());
// there is no agent directly in front of agent4
obs_world4.SetLateralDifferenceThreshold(0.2);
std::pair<AgentPtr, FrenetStateDifference> leading_vehicle4 =
obs_world4.GetAgentInFront();
EXPECT_FALSE(static_cast<bool>(leading_vehicle4.first));
// adjust difference threshold to find agent on left lane
obs_world4.SetLateralDifferenceThreshold(4.0);
std::pair<AgentPtr, FrenetStateDifference> leading_vehicle5 =
obs_world4.GetAgentInFront();
EXPECT_TRUE(static_cast<bool>(leading_vehicle5.first));
const auto& road_corridor4 = agent4->GetRoadCorridor();
BARK_EXPECT_TRUE(road_corridor4 != nullptr);
Point2d ego_pos4 = agent4->GetCurrentPosition();
const auto& left_right_lane_corridor =
road_corridor4->GetLeftRightLaneCorridor(ego_pos4);
const LaneCorridorPtr& lane_corridor4 = left_right_lane_corridor.first;
BARK_EXPECT_TRUE(lane_corridor4 != nullptr);
EXPECT_EQ(3.5, lane_corridor4->GetLaneWidth(ego_pos4));
// in the lane corridor left of agent4, there is agent2 in front
FrontRearAgents fr_vehicle4b =
obs_world4.GetAgentFrontRearForId(agent4->GetAgentId(), lane_corridor4, obs_world4.GetLateralDifferenceThreshold());
EXPECT_TRUE(static_cast<bool>(fr_vehicle4b.front.first));
EXPECT_EQ(fr_vehicle4b.front.first->GetAgentId(), agent2->GetAgentId());
// in the lane corridor left of agent4, there is agent1 behind
EXPECT_TRUE(static_cast<bool>(fr_vehicle4b.rear.first));
EXPECT_EQ(fr_vehicle4b.rear.first->GetAgentId(), agent1->GetAgentId());
}
TEST(observed_world, clone) {
using bark::world::evaluation::EvaluatorCollisionAgents;
using bark::world::evaluation::EvaluatorPtr;
auto params = std::make_shared<SetterParams>();
ExecutionModelPtr exec_model(new ExecutionModelInterpolate(params));
DynamicModelPtr dyn_model(new SingleTrackModel(params));
BehaviorModelPtr beh_model(new BehaviorConstantAcceleration(params));
EvaluatorPtr col_checker(new EvaluatorCollisionAgents());
Polygon polygon(
Pose(1.25, 1, 0),
std::vector<Point2d>{Point2d(0, 0), Point2d(0, 2), Point2d(4, 2),
Point2d(4, 0), Point2d(0, 0)});
State init_state1(static_cast<int>(MIN_STATE_SIZE));
init_state1 << 0.0, 0.0, 0.0, 0.0, 5.0;
AgentPtr agent1(new Agent(init_state1, beh_model, dyn_model, exec_model,
polygon, params)); // NOLINT
State init_state2(static_cast<int>(MIN_STATE_SIZE));
init_state2 << 0.0, 8.0, 0.0, 0.0, 5.0;
AgentPtr agent2(new Agent(init_state2, beh_model, dyn_model, exec_model,
polygon, params)); // NOLINT
WorldPtr world = std::make_shared<World>(params);
world->AddAgent(agent1);
world->AddAgent(agent2);
world->UpdateAgentRTree();
WorldPtr current_world_state(world->Clone());
ObservedWorldPtr observed_world(
new ObservedWorld(current_world_state, agent1->GetAgentId()));
WorldPtr cloned(observed_world->Clone());
ObservedWorldPtr cloned_observed_world =
std::dynamic_pointer_cast<ObservedWorld>(cloned);
EXPECT_EQ(observed_world->GetEgoAgent()->GetAgentId(),
cloned_observed_world->GetEgoAgent()->GetAgentId());
EXPECT_EQ(typeid(observed_world->GetEgoBehaviorModel()),
typeid(cloned_observed_world->GetEgoBehaviorModel()));
observed_world.reset();
auto behavior_ego = cloned_observed_world->GetEgoBehaviorModel();
EXPECT_TRUE(behavior_ego != nullptr);
}
TEST(observed_world, predict) {
using bark::models::behavior::BehaviorMotionPrimitives;
using bark::models::behavior::BehaviorMPContinuousActions;
using bark::models::behavior::DiscreteAction;
using bark::models::dynamic::Input;
using bark::world::prediction::PredictionSettings;
using bark::world::tests::make_test_observed_world;
using StateDefinition::VEL_POSITION;
namespace mg = bark::geometry;
auto params = std::make_shared<SetterParams>();
params->SetReal("integration_time_delta", 0.01);
DynamicModelPtr dyn_model(new SingleTrackModel(params));
double ego_velocity = 5.0, rel_distance = 7.0, velocity_difference = 0.0;
auto observed_world = make_test_observed_world(1, rel_distance, ego_velocity,
velocity_difference);
for (const auto& agent : observed_world.GetAgents()) {
agent.second->SetDynamicModel(dyn_model);
}
// predict all agents with constant velocity
BehaviorModelPtr prediction_model(new BehaviorConstantAcceleration(params));
PredictionSettings prediction_settings(prediction_model, prediction_model);
observed_world.SetupPrediction(prediction_settings);
WorldPtr predicted_world = observed_world.Predict(1.0);
ObservedWorldPtr observed_predicted_world =
std::dynamic_pointer_cast<ObservedWorld>(predicted_world);
double distance_ego =
mg::Distance(observed_predicted_world->CurrentEgoPosition(),
observed_world.CurrentEgoPosition());
double distance_other = mg::Distance(
observed_predicted_world->GetOtherAgents()
.begin()
->second->GetCurrentPosition(),
observed_world.GetOtherAgents().begin()->second->GetCurrentPosition());
// distance current and predicted state should be
// velocity x prediction time span
EXPECT_NEAR(distance_ego, ego_velocity * 1.0, 0.06);
EXPECT_NEAR(distance_other,
observed_world.GetOtherAgents()
.begin()
->second->GetCurrentState()[VEL_POSITION] *
1.0, // NOLINT
0.06);
// predict ego agent with motion primitive model
BehaviorModelPtr ego_prediction_model(
new BehaviorMPContinuousActions(params));
Input u1(2);
u1 << 2, 0;
Input u2(2);
u2 << 0, 1;
BehaviorMotionPrimitives::MotionIdx idx1 =
std::dynamic_pointer_cast<BehaviorMPContinuousActions>(
ego_prediction_model)
->AddMotionPrimitive(u1); // NOLINT
BehaviorMotionPrimitives::MotionIdx idx2 =
std::dynamic_pointer_cast<BehaviorMPContinuousActions>(
ego_prediction_model)
->AddMotionPrimitive(u2); // NOLINT
BehaviorModelPtr others_prediction_model(
new BehaviorConstantAcceleration(params));
PredictionSettings prediction_settings2(ego_prediction_model,
others_prediction_model);
observed_world.SetupPrediction(prediction_settings2);
WorldPtr predicted_world2 =
observed_world.Predict(1.0, DiscreteAction(idx1));
auto ego_pred_velocity =
std::dynamic_pointer_cast<ObservedWorld>(predicted_world2)
->CurrentEgoState()[StateDefinition::VEL_POSITION]; // NOLINT
// distance current and predicted state should be velocity
// + prediction time span
EXPECT_NEAR(ego_pred_velocity, ego_velocity + 2 * 1.0, 0.05);
// We should get the same results with Predict of Agent Map
std::unordered_map<AgentId, DiscreteAction> agent_action_map;
agent_action_map.insert(
{observed_world.GetEgoAgentId(), DiscreteAction(idx1)});
predicted_world2 = observed_world.Predict(1.0, agent_action_map);
ego_pred_velocity =
std::dynamic_pointer_cast<ObservedWorld>(predicted_world2)
->CurrentEgoState()[StateDefinition::VEL_POSITION]; // NOLINT
// distance current and predicted state should be velocity
// + prediction time span
EXPECT_NEAR(ego_pred_velocity, ego_velocity + 2 * 1.0, 0.05);
}
|
7b0685d3574a4065d6120272a23ecc49b87f3c84 | 6b2a8dd202fdce77c971c412717e305e1caaac51 | /solutions_6404600001200128_1/C++/golmansax/A.cc | 3ff6bfca0dd0e4df832b9128b890ddb3676f5b0a | [] | no_license | alexandraback/datacollection | 0bc67a9ace00abbc843f4912562f3a064992e0e9 | 076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf | refs/heads/master | 2021-01-24T18:27:24.417992 | 2017-05-23T09:23:38 | 2017-05-23T09:23:38 | 84,313,442 | 2 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 725 | cc | A.cc | #include <iostream>
#include <cstdio>
#include <cmath>
#include <string>
using namespace std;
int main() {
int n_cases;
cin >> n_cases;
for (int i_case = 0; i_case < n_cases; i_case++) {
int n;
cin >> n;
int m[n];
long long ans_1 = 0;
int prev_m = 0;
int worst_diff = 0;
for (int i = 0; i < n; i++) {
cin >> m[i];
int prev_diff = prev_m - m[i];
if (prev_diff > 0) {
ans_1 += prev_diff;
}
prev_m = m[i];
worst_diff = max(worst_diff, prev_diff);
}
long long ans_2 = 0;
for (int i = 0; i < n - 1; i++) {
ans_2 += min(m[i], worst_diff);
}
printf("Case #%d: %lld %lld\n", i_case + 1, ans_1, ans_2);
}
return 0;
}
|
53461151fc4f49bcffa80d4ed0a4019afeb21b82 | 3dba2b348b3a29235ddfeac8f91797f04f306cd9 | /src/bench/ccoins_caching.cpp | 9280670fa1146510edf24891dd657878eaf5b8a0 | [
"MIT"
] | permissive | VadiqueMe/dogecoin | f331c35a504258fc7d30073121d6ec32d22836cb | b9693e5854157bdff733416083a956d8499e30ed | refs/heads/master | 2022-06-05T08:10:55.669611 | 2021-01-03T19:08:58 | 2022-05-22T18:37:58 | 209,979,651 | 1 | 1 | MIT | 2019-09-21T12:16:04 | 2019-09-21T12:16:03 | null | UTF-8 | C++ | false | false | 3,657 | cpp | ccoins_caching.cpp | // Copyright (c) 2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php
#include "bench.h"
#include "coins.h"
#include "policy/policy.h"
#include "wallet/crypter.h"
#include <vector>
// FIXME: Dedup with SetupDummyInputs in test/transaction_tests.cpp
//
// Helper: create two dummy transactions, each with
// two outputs. The first has 11 000000 and 50 000000 outputs
// paid to a TX_PUBKEY, the second 21 000000 and 22 000000 outputs
// paid to a TX_PUBKEYHASH
//
static std::vector< CMutableTransaction >
SetupDummyInputs( CBasicKeyStore & keystoreRet, CCoinsViewCache & coinsRet )
{
std::vector< CMutableTransaction > dummyTransactions ;
dummyTransactions.resize( 2 ) ;
// Add four keys to the keystore
CKey key[ 4 ] ;
for ( int i = 0 ; i < 4 ; i ++ )
{
key[ i ].MakeNewKey( i % 2 ) ;
keystoreRet.AddKey( key[ i ] ) ;
}
// Create some dummy input transactions
dummyTransactions[ 0 ].vout.resize( 2 ) ;
dummyTransactions[ 0 ].vout[ 0 ].nValue = 11 * E6COIN ;
dummyTransactions[ 0 ].vout[ 0 ].scriptPubKey << ToByteVector( key[ 0 ].GetPubKey() ) << OP_CHECKSIG ;
dummyTransactions[ 0 ].vout[ 1 ].nValue = 50 * E6COIN ;
dummyTransactions[ 0 ].vout[ 1 ].scriptPubKey << ToByteVector( key[ 1 ].GetPubKey() ) << OP_CHECKSIG ;
coinsRet.ModifyCoins( dummyTransactions[ 0 ].GetTxHash() )->FromTx( dummyTransactions[ 0 ], 0 ) ;
dummyTransactions[ 1 ].vout.resize( 2 ) ;
dummyTransactions[ 1 ].vout[ 0 ].nValue = 21 * E6COIN ;
dummyTransactions[ 1 ].vout[ 0 ].scriptPubKey = GetScriptForDestination( key[ 2 ].GetPubKey().GetID() ) ;
dummyTransactions[ 1 ].vout[ 1 ].nValue = 22 * E6COIN ;
dummyTransactions[ 1 ].vout[ 1 ].scriptPubKey = GetScriptForDestination( key[ 3 ].GetPubKey().GetID() ) ;
coinsRet.ModifyCoins( dummyTransactions[ 1 ].GetTxHash() )->FromTx( dummyTransactions[ 1 ], 0 ) ;
return dummyTransactions ;
}
// Microbenchmark for simple accesses to a CCoinsViewCache database. Note from
// laanwj, "replicating the actual usage patterns of the client is hard though,
// many times micro-benchmarks of the database showed completely different
// characteristics than e.g. reindex timings. But that's not a requirement of
// every benchmark"
// (https://github.com/bitcoin/bitcoin/issues/7883#issuecomment-224807484)
static void CCoinsCaching(benchmark::State& state)
{
CBasicKeyStore keystore ;
TrivialCoinsView coinsDummy ;
CCoinsViewCache coins( &coinsDummy ) ;
std::vector< CMutableTransaction > dummyTransactions = SetupDummyInputs( keystore, coins ) ;
CMutableTransaction t1;
t1.vin.resize(3);
t1.vin[0].prevout.hash = dummyTransactions[0].GetTxHash() ;
t1.vin[0].prevout.n = 1;
t1.vin[0].scriptSig << std::vector<unsigned char>(65, 0);
t1.vin[1].prevout.hash = dummyTransactions[1].GetTxHash() ;
t1.vin[1].prevout.n = 0;
t1.vin[1].scriptSig << std::vector<unsigned char>(65, 0) << std::vector<unsigned char>(33, 4);
t1.vin[2].prevout.hash = dummyTransactions[1].GetTxHash() ;
t1.vin[2].prevout.n = 1;
t1.vin[2].scriptSig << std::vector<unsigned char>(65, 0) << std::vector<unsigned char>(33, 4);
t1.vout.resize(2);
t1.vout[0].nValue = 90 * E6COIN ;
t1.vout[0].scriptPubKey << OP_1 ;
// Benchmark
while (state.KeepRunning()) {
bool success = AreInputsStandard(t1, coins);
assert(success);
CAmount value = coins.GetValueIn(t1);
assert( value == ( 50 + 21 + 22 ) * E6COIN ) ;
}
}
BENCHMARK(CCoinsCaching);
|
8c8df04b252c69f1be8740525d82934372665557 | 95e5da8d91a213c69856db4f50ba95e12f4d6d98 | /cc/library/sim_world/sim_world.cc | 315d8de0a38462095c7be058b3b7be517ab0e666 | [] | no_license | aushani/summer | 4f2ba146a9cafc8e0ed239e8d2ddecb30518bf11 | 01ef8e9fa05d13bd853f37d5d9f3aba2fe74d2fb | refs/heads/master | 2020-03-22T04:18:04.547751 | 2018-01-15T17:13:20 | 2018-01-15T17:13:20 | 137,923,798 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,183 | cc | sim_world.cc | #include "library/sim_world/sim_world.h"
#include <random>
#include <chrono>
namespace ge = library::geometry;
namespace library {
namespace sim_world {
unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
std::default_random_engine rand_engine(seed);
SimWorld::SimWorld(size_t n_shapes) :
bounding_box_(Shape::CreateBox(0, 0, 1000, 1000)),
origin_(0.0, 0.0) {
std::uniform_real_distribution<double> x_pos(-20.0, 20.0);
std::uniform_real_distribution<double> y_pos(-20.0, 20.0);
std::uniform_real_distribution<double> width(3.0, 6.0);
std::uniform_real_distribution<double> length(4.0, 8.0);
std::uniform_real_distribution<double> rand_size(2.0, 4.0);
std::uniform_real_distribution<double> rand_angle(-M_PI, M_PI);
std::uniform_real_distribution<double> rand_shape(0.0, 1.0);
// Make shapes in the world
int attempts = 0;
while (shapes_.size() < n_shapes) {
if (attempts++ > 1000)
break;
double x = x_pos(rand_engine);
double y = y_pos(rand_engine);
double angle = rand_angle(rand_engine);
bool make_box = rand_shape(rand_engine) < 0.5;
bool make_star = !make_box;
// Not too close to origin
if (std::abs(x) < 10 && std::abs(y) < 10) {
continue;
}
Shape obj = Shape::CreateBox(0, 0, 1, 1);
if (make_box) {
obj = Shape::CreateBox(x, y, width(rand_engine), length(rand_engine));
} else if (make_star) {
obj = Shape::CreateStar(x, y, rand_size(rand_engine));
}
obj.Rotate(angle);
// Check for origin inside shape
if (obj.IsInside(0, 0)) {
continue;
}
// Check for intersection
bool intersects = false;
for (const auto &s : shapes_) {
if (s.Intersects(obj)) {
intersects = true;
break;
}
}
if (intersects) {
continue;
}
shapes_.push_back(obj);
}
}
void SimWorld::AddShape(const Shape &obj) {
shapes_.push_back(obj);
}
double SimWorld::GetHit(const Eigen::Vector2d &ray, Eigen::Vector2d *hit) const {
Eigen::Vector2d ray_hat = ray.normalized();
double best_distance = bounding_box_.GetHit(origin_, ray_hat, hit);
Eigen::Vector2d b_hit;
for (const Shape &b : shapes_) {
double dist = b.GetHit(origin_, ray_hat, &b_hit);
if (dist > 0 && dist < best_distance) {
*hit = b_hit;
best_distance = dist;
}
}
return best_distance;
}
void SimWorld::GenerateSimData(std::vector<ge::Point> *hits, std::vector<ge::Point> *origins) const {
Eigen::Vector2d hit;
for (double angle = -M_PI; angle < M_PI; angle += 0.01) {
Eigen::Vector2d ray(cos(angle), sin(angle));
double distance = GetHit(ray, &hit);
if (distance > 0) {
hits->push_back(ge::Point(hit(0), hit(1)));
origins->push_back(ge::Point(origin_(0), origin_(1)));
}
}
}
void SimWorld::GenerateSimData(std::vector<ge::Point> *points, std::vector<float> *labels) const {
Eigen::Vector2d hit;
std::uniform_real_distribution<double> unif(0.0, 1.0);
unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
std::default_random_engine re(seed);
for (double angle = -M_PI; angle < M_PI; angle += 0.01) {
Eigen::Vector2d ray(cos(angle), sin(angle));
double distance = GetHit(ray, &hit);
if (distance > 0) {
points->push_back(ge::Point(hit(0), hit(1)));
labels->push_back(1.0);
for (int i=0; i<distance; i++) {
double random_range = unif(re)*distance;
Eigen::Vector2d free = origin_ + random_range * ray;
points->push_back(ge::Point(free(0), free(1)));
labels->push_back(-1.0);
}
}
}
}
void SimWorld::GenerateGrid(double size, std::vector<ge::Point> *points, std::vector<float> *labels, double res) const {
// Find extent of sim
//double x_min = GetMinX();
//double x_max = GetMaxX();
//double y_min = GetMinY();
//double y_max = GetMaxY();
//// Expand by a bit
//double x_range = x_max - x_min;
//x_min -= x_range*0.10;
//x_max += x_range*0.10;
//double y_range = y_max - y_min;
//y_min -= y_range*0.10;
//y_max += y_range*0.10;
for (double x = -size; x<size; x+=res) {
for (double y = -size; y<size; y+=res) {
points->emplace_back(x, y);
labels->push_back(IsOccupied(x, y) ? 1.0:-1.0);
}
}
}
void SimWorld::GenerateSamples(size_t trials, std::vector<ge::Point> *points, std::vector<float> *labels, bool visible, bool occluded) const {
// Find extent of sim
double x_min = GetMinX();
double x_max = GetMaxX();
double y_min = GetMinY();
double y_max = GetMaxY();
std::uniform_real_distribution<double> random_x(x_min, x_max);
std::uniform_real_distribution<double> random_y(y_min, y_max);
unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
std::default_random_engine re(seed);
std::vector<ge::Point> occu_points;
std::vector<ge::Point> free_points;
for (size_t i=0; i<trials; i++) {
double x = random_x(re);
double y = random_y(re);
// Check if it matches the flags we have
// If we don't have visible points and it is visible, or we don't want occluded points and it is occluded
if ( (!visible && IsVisible(x, y)) || (!occluded && IsOccluded(x, y)) ) {
continue;
}
if (IsOccupied(x, y)) {
occu_points.push_back(ge::Point(x, y));
} else {
free_points.push_back(ge::Point(x, y));
}
}
size_t min = occu_points.size();
if (free_points.size() < min)
min = free_points.size();
for (size_t i = 0; i<min; i++) {
points->push_back(occu_points[i]);
labels->push_back(1.0);
points->push_back(free_points[i]);
labels->push_back(-1.0);
}
}
void SimWorld::GenerateAllSamples(size_t trials, std::vector<ge::Point> *points, std::vector<float> *labels) const {
bool visible = true;
bool occluded = true;
GenerateSamples(trials, points, labels, visible, occluded);
}
void SimWorld::GenerateVisibleSamples(size_t trials, std::vector<ge::Point> *points, std::vector<float> *labels) const {
bool visible = true;
bool occluded = false;
GenerateSamples(trials, points, labels, visible, occluded);
}
void SimWorld::GenerateOccludedSamples(size_t trials, std::vector<ge::Point> *points, std::vector<float> *labels) const {
bool visible = false;
bool occluded = true;
GenerateSamples(trials, points, labels, visible, occluded);
}
bool SimWorld::IsOccupied(float x, float y) const {
for (const Shape &b : shapes_) {
if (b.IsInside(x, y))
return true;
}
return false;
}
double SimWorld::GetMinX() const {
return -10.0;
//double x_min = 0.0;
//bool first = false;
//for (const Shape &s: shapes_) {
// double s_x_min = s.GetMinX();
// if (s_x_min < x_min || first)
// x_min = s_x_min;
//}
//return x_min;
}
double SimWorld::GetMaxX() const {
return 10.0;
//double x_max = 0.0;
//bool first = false;
//for (const Shape &s: shapes_) {
// double s_x_max = s.GetMaxX();
// if (s_x_max > x_max || first)
// x_max = s_x_max;
//}
//return x_max;
}
double SimWorld::GetMinY() const {
return -10.0;
//double y_min = 0.0;
//bool first = false;
//for (const Shape &s: shapes_) {
// double s_y_min = s.GetMinY();
// if (s_y_min < y_min || first)
// y_min = s_y_min;
//}
//return y_min;
}
double SimWorld::GetMaxY() const {
return 10.0;
//double y_max = 0.0;
//bool first = false;
//for (const Shape &s: shapes_) {
// double s_y_max = s.GetMaxY();
// if (s_y_max > y_max || first)
// y_max = s_y_max;
//}
//return y_max;
}
const std::vector<Shape>& SimWorld::GetShapes() const {
return shapes_;
}
bool SimWorld::IsVisible(float x, float y) const {
Eigen::Vector2d point(x, y);
Eigen::Vector2d ray = (point - origin_);
Eigen::Vector2d hit;
double distance = GetHit(ray, &hit);
return distance >= ray.norm();
}
bool SimWorld::IsOccluded(float x, float y) const {
return !IsVisible(x, y);
}
std::vector<ge::Point> SimWorld::GetObjectLocations() const {
std::vector<ge::Point> locs;
for(auto shape : shapes_) {
auto center = shape.GetCenter();
locs.emplace_back(center(0), center(1));
}
return locs;
}
}
}
|
6b9569306ad58d902cf93dba1588003a1db19d7c | 98570eab097534253abf2d4e24e2297ef9e339ab | /bellman_ford.cpp | 120eadbca18119505a9ee0393bf260b38e5916ee | [] | no_license | jagadeeshnelaturu/standard_implementations | 26ae0bad052fb8ca033edeee570a683af3395bcb | 372dc1243e4b80422a1748a70d919a4b25f0843f | refs/heads/master | 2021-01-10T10:31:41.794732 | 2015-12-01T19:58:04 | 2015-12-01T19:58:04 | 44,399,954 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,832 | cpp | bellman_ford.cpp | #include <iostream>
#include <list>
#include <climits>
struct node {
std::list< std::pair<int, int> > _adjacency_list;
};
void addEdge(node** graph, int src, int dst, int weight) {
graph[src]->_adjacency_list.push_back(std::make_pair(dst, weight));
}
void bellman_ford(node **graph, int n, int source, int* distances) {
for(int i = 0; i < n; ++i) {
distances[i] = INT_MAX;
}
distances[source] = 0;
for(int i = 1; i < n; ++i) {
int current = 0;
while(current < n) {
for(std::list< std::pair<int, int> >::iterator it = graph[current]->_adjacency_list.begin();
it != graph[current]->_adjacency_list.end(); ++it) {
if((distances[current] != INT_MAX) &&
(distances[current] + it->second < distances[it->first])) {
distances[it->first] = distances[current] + it->second;
}
}
++current;
}
}
int current = 0;
while(current < n) {
for(std::list< std::pair<int, int> >::iterator it = graph[current]->_adjacency_list.begin();
it != graph[current]->_adjacency_list.end(); ++it) {
if((distances[current] != INT_MAX) &&
(distances[current] + it->second < distances[it->first])) {
std::cout << "Graph contains negative edge cycle\n";
return;
}
}
++current;
}
}
int main() {
int n;
std::cin >> n;
node **graph = new node*[n];
for(int i = 0; i < n; ++i) {
graph[i] = new node();
}
int m;
std::cin >> m;
int src, dst, weight;
while(m--) {
std::cin >> src >> dst >> weight;
addEdge(graph, src, dst, weight);
}
int *distances = new int[n];
bellman_ford(graph, n, 0, distances);
for(int i = 0; i < n; ++i) {
std::cout << distances[i] << ' ';
}
std::cout << '\n';
}
/*Example input
6
8
0 1 -1
0 2 4
1 2 3
1 3 2
1 4 2
3 1 1
3 2 5
4 3 -3
5 0 1
*/
|
7e2b96265c6a8c7f7b0b9bc00c7b6b383c42db6e | 6529a9e1f5fb1297dbbc6f93d64c7facaf6e67c1 | /rmw_ecal_dynamic_cpp/src/internal/serialization/protobuf/serializer_c.cpp | 5efb0f1d64e8e2f5dc4358e71bb1170a0c208810 | [
"Apache-2.0"
] | permissive | flynneva/rmw_ecal | cceb4abc9a7970568231c34ca48b7434f9cfb3fd | bad0d8885b3bfea158203c591c3bd61c38b448d7 | refs/heads/master | 2023-01-19T01:58:37.543464 | 2020-10-30T21:27:00 | 2020-10-30T21:27:00 | 308,684,831 | 1 | 0 | Apache-2.0 | 2020-11-09T03:39:47 | 2020-10-30T16:25:12 | C++ | UTF-8 | C++ | false | false | 12,043 | cpp | serializer_c.cpp | /* ========================= RMW eCAL LICENSE =================================
*
* Copyright (C) 2019 - 2020 Continental Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ========================= RMW eCAL LICENSE =================================
*/
#include "serializer_c.hpp"
#include <string>
#include <memory>
#include <stdexcept>
#include <rosidl_typesupport_introspection_c/field_types.h>
#include "internal/rosidl_generator_c_pkg_adapter.hpp"
#include "internal/common.hpp"
#include "internal/serialization/protobuf/helpers.hpp"
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4267 4244)
#endif
namespace eCAL
{
namespace rmw
{
namespace pb = google::protobuf;
using MessageMembers = rosidl_typesupport_introspection_c__MessageMembers;
#define DEFINE_SET_METHODS(PB_NAME, TYPE) \
template <> \
void CProtobufSerializer::SetSingle<TYPE>(const char *data, pb::Message *msg, \
const pb::FieldDescriptor *field) const \
{ \
auto ref = msg->GetReflection(); \
auto value = *reinterpret_cast<const TYPE *>(data); \
\
ref->Set##PB_NAME(msg, field, value); \
} \
\
template <> \
void CProtobufSerializer::SetArray<TYPE>(const char *data, int size, pb::Message *msg, \
const pb::FieldDescriptor *field) const \
{ \
auto ref = msg->GetReflection(); \
auto array = reinterpret_cast<const TYPE *>(data); \
for (int i = 0; i < size; i++) \
{ \
ref->Add##PB_NAME(msg, field, array[i]); \
} \
} \
\
template <> \
void CProtobufSerializer::SetDynamicArray<TYPE>(const char *data, pb::Message *msg, \
const pb::FieldDescriptor *field) const \
{ \
auto ref = msg->GetReflection(); \
auto sequence = reinterpret_cast<const rosidl_runtime_c__char__Sequence *>(data); \
\
ThrowIfInvalidProtobufArraySize(sequence->size); \
for (size_t i = 0; i < sequence->size; i++) \
{ \
auto value = reinterpret_cast<TYPE *>(sequence->data + sizeof(TYPE) * i); \
ref->Add##PB_NAME(msg, field, *value); \
} \
}
DEFINE_SET_METHODS(Bool, bool)
DEFINE_SET_METHODS(Int32, char)
DEFINE_SET_METHODS(Int32, int8_t)
DEFINE_SET_METHODS(Int32, int16_t)
DEFINE_SET_METHODS(Int32, int32_t)
DEFINE_SET_METHODS(Int64, int64_t)
DEFINE_SET_METHODS(UInt32, uint8_t)
DEFINE_SET_METHODS(UInt32, uint16_t)
DEFINE_SET_METHODS(UInt32, uint32_t)
DEFINE_SET_METHODS(UInt64, uint64_t)
DEFINE_SET_METHODS(Float, float)
DEFINE_SET_METHODS(Double, double)
template <>
void CProtobufSerializer::SetSingle<std::string>(const char *data, pb::Message *msg,
const pb::FieldDescriptor *field) const
{
auto ref = msg->GetReflection();
auto sequence = reinterpret_cast<const rosidl_runtime_c__char__Sequence *>(data);
auto str_data = reinterpret_cast<char *>(sequence->data);
ref->SetString(msg, field, str_data);
}
template <>
void CProtobufSerializer::SetArray<std::string>(const char *data, int size, pb::Message *msg,
const pb::FieldDescriptor *field) const
{
auto ref = msg->GetReflection();
auto array = reinterpret_cast<const rosidl_runtime_c__char__Sequence *>(data);
for (int i = 0; i < size; i++)
{
auto &string = array[i];
auto str_data = reinterpret_cast<char *>(string.data);
ref->AddString(msg, field, str_data);
}
}
template <>
void CProtobufSerializer::SetDynamicArray<std::string>(const char *data, pb::Message *msg,
const pb::FieldDescriptor *field) const
{
auto ref = msg->GetReflection();
auto sequence = reinterpret_cast<const rosidl_runtime_c__char__Sequence *>(data);
auto size = sequence->size;
auto strings = sequence->data;
ThrowIfInvalidProtobufArraySize(size);
for (size_t i = 0; i < size; i++, strings += sizeof(rosidl_runtime_c__char__Sequence))
{
auto string = reinterpret_cast<const rosidl_runtime_c__char__Sequence *>(strings);
auto str_data = reinterpret_cast<char *>(string->data);
ref->AddString(msg, field, str_data);
}
}
template <>
void CProtobufSerializer::SetSingle<ros_message_t>(const char *data, const MessageMembers *members,
pb::Message *msg, const pb::FieldDescriptor *field) const
{
auto sub_message = message_factory_.Create(members->message_name_);
auto sub_desc = sub_message->GetDescriptor();
FillMessage(data, members, sub_message, sub_desc);
auto ref = msg->GetReflection();
ref->SetAllocatedMessage(msg, sub_message, field);
}
template <>
void CProtobufSerializer::SetArray<ros_message_t>(const char *data, const MessageMembers *members,
int size, pb::Message *msg,
const pb::FieldDescriptor *field) const
{
auto ref = msg->GetReflection();
for (int i = 0; i < size; i++)
{
auto sub_message = message_factory_.Create(members->message_name_);
auto sub_desc = sub_message->GetDescriptor();
FillMessage(data, members, sub_message, sub_desc);
ref->AddAllocatedMessage(msg, field, sub_message);
data += members->size_of_;
}
}
template <>
void CProtobufSerializer::SetDynamicArray<ros_message_t>(const char *data, const MessageMembers *members,
pb::Message *msg, const pb::FieldDescriptor *field) const
{
auto sequence = reinterpret_cast<const rosidl_runtime_c__char__Sequence *>(data);
auto arr_data = reinterpret_cast<char *>(sequence->data);
auto arr_size = sequence->size;
ThrowIfInvalidProtobufArraySize(arr_size);
SetArray<ros_message_t>(arr_data, members, arr_size, msg, field);
}
template <typename T>
void CProtobufSerializer::Set(const char *data,
const rosidl_typesupport_introspection_c__MessageMember *member,
pb::Message *msg, const pb::Descriptor *desc) const
{
auto pb_field = desc->FindFieldByName(member->name_);
if (member->is_array_)
{
if (member->array_size_ > 0 && !member->is_upper_bound_)
{
ThrowIfInvalidProtobufArraySize(member->array_size_);
SetArray<T>(data, member->array_size_, msg, pb_field);
}
else
{
SetDynamicArray<T>(data, msg, pb_field);
}
}
else
{
SetSingle<T>(data, msg, pb_field);
}
}
template <>
void CProtobufSerializer::Set<ros_message_t>(const char *data,
const rosidl_typesupport_introspection_c__MessageMember *member,
pb::Message *msg, const pb::Descriptor *desc) const
{
auto pb_field = desc->FindFieldByName(member->name_);
auto sub_members = GetMembers(member);
if (member->is_array_)
{
if (member->array_size_ > 0 && !member->is_upper_bound_)
{
ThrowIfInvalidProtobufArraySize(member->array_size_);
SetArray<ros_message_t>(data, sub_members, member->array_size_, msg, pb_field);
}
else
{
SetDynamicArray<ros_message_t>(data, sub_members, msg, pb_field);
}
}
else
{
SetSingle<ros_message_t>(data, sub_members, msg, pb_field);
}
}
#undef DEFINE_SET_METHODS
void CProtobufSerializer::FillMessage(const char *data, const MessageMembers *members,
pb::Message *msg, const pb::Descriptor *desc) const
{
for (uint32_t i = 0; i < members->member_count_; i++)
{
auto member = members->members_ + i;
auto member_data = data + member->offset_;
switch (member->type_id_)
{
case ::rosidl_typesupport_introspection_c__ROS_TYPE_STRING:
Set<std::string>(member_data, member, msg, desc);
break;
case ::rosidl_typesupport_introspection_c__ROS_TYPE_BOOLEAN:
Set<bool>(member_data, member, msg, desc);
break;
case ::rosidl_typesupport_introspection_c__ROS_TYPE_BYTE:
Set<uint8_t>(member_data, member, msg, desc);
break;
case ::rosidl_typesupport_introspection_c__ROS_TYPE_CHAR:
Set<char>(member_data, member, msg, desc);
break;
case ::rosidl_typesupport_introspection_c__ROS_TYPE_FLOAT:
Set<float>(member_data, member, msg, desc);
break;
case ::rosidl_typesupport_introspection_c__ROS_TYPE_DOUBLE:
Set<double>(member_data, member, msg, desc);
break;
case ::rosidl_typesupport_introspection_c__ROS_TYPE_INT8:
Set<int8_t>(member_data, member, msg, desc);
break;
case ::rosidl_typesupport_introspection_c__ROS_TYPE_INT16:
Set<int16_t>(member_data, member, msg, desc);
break;
case ::rosidl_typesupport_introspection_c__ROS_TYPE_INT32:
Set<int32_t>(member_data, member, msg, desc);
break;
case ::rosidl_typesupport_introspection_c__ROS_TYPE_INT64:
Set<int64_t>(member_data, member, msg, desc);
break;
case ::rosidl_typesupport_introspection_c__ROS_TYPE_UINT8:
Set<uint8_t>(member_data, member, msg, desc);
break;
case ::rosidl_typesupport_introspection_c__ROS_TYPE_UINT16:
Set<uint16_t>(member_data, member, msg, desc);
break;
case ::rosidl_typesupport_introspection_c__ROS_TYPE_UINT32:
Set<uint32_t>(member_data, member, msg, desc);
break;
case ::rosidl_typesupport_introspection_c__ROS_TYPE_UINT64:
Set<uint64_t>(member_data, member, msg, desc);
break;
case ::rosidl_typesupport_introspection_c__ROS_TYPE_MESSAGE:
Set<ros_message_t>(member_data, member, msg, desc);
break;
case ::rosidl_typesupport_introspection_c__ROS_TYPE_LONG_DOUBLE:
case ::rosidl_typesupport_introspection_c__ROS_TYPE_WSTRING:
case ::rosidl_typesupport_introspection_c__ROS_TYPE_WCHAR:
throw std::logic_error("Wide character/string serialization is unsupported.");
}
}
}
const std::string CProtobufSerializer::Serialize(const void *data)
{
std::unique_ptr<pb::Message> msg(message_factory_.Create());
auto msg_desc = msg->GetDescriptor();
FillMessage(static_cast<const char *>(data), members_, msg.get(), msg_desc);
return msg->SerializeAsString();
}
const std::string CProtobufSerializer::GetMessageStringDescriptor() const
{
return message_factory_.GetMessageStringDescriptor();
}
} // namespace rmw
} // namespace eCAL
#ifdef _MSC_VER
#pragma warning(pop)
#endif |
05c52cb80c073dd5eeaacfd08953935dd987dc0d | 15fcf2266ef08c8c7a6720e27b431544e912f9b5 | /tools/ftdi/ftdi_list_devices.cpp | d86e1ae8c95d1d5d30d293b8d1046483c184c425 | [] | no_license | d-hawkins/avnet_minized_tutorial | 003b0e837d40e69bd4d46afef777b145af3fbb94 | b52f7340498fe3f058db75fa44693acf8a77e1c5 | refs/heads/main | 2023-04-09T14:55:36.025756 | 2021-04-14T07:01:39 | 2021-04-14T07:01:39 | 356,716,810 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,050 | cpp | ftdi_list_devices.cpp | // ----------------------------------------------------------------------------
// ftdi_list_devices.cpp
//
// 12/10/2018 D. W. Hawkins (David.W.Hawkins@jpl.nasa.gov)
//
// List the FTDI devices attached via USB.
//
// ----------------------------------------------------------------------------
// Windows types used by the FTDI D2XX direct access API
#ifdef __linux__
#include "WinTypes.h"
#else
#include <windows.h>
#endif
#include <unistd.h> // usleep()
// FTDI D2XX direct access API
#include "ftd2xx.h"
#include <iostream>
#include <iomanip>
#include <sstream>
#include <vector>
// ================================================================
// Main Application
// ================================================================
//
int main (int argc, char **argv)
{
try {
FT_STATUS status;
DWORD num_devices;
status = FT_CreateDeviceInfoList(&num_devices);
if (status != FT_OK) {
std::stringstream err;
err << "FT_CreateDeviceInfoList returned " << (int)status;
throw std::runtime_error(err.str());
}
if (num_devices < 1) {
std::cout << "No FTDI devices detected" << std::endl;
return 0;
}
std::cout << num_devices << " FTDI devices found" << std::endl;
std::vector<FT_DEVICE_LIST_INFO_NODE> dev_info(num_devices);
status = FT_GetDeviceInfoList(&dev_info[0], &num_devices);
if (status != FT_OK) {
std::stringstream err;
err << "FT_GetDeviceInfoList returned " << (int)status;
throw std::runtime_error(err.str());
}
for (uint32_t i = 0; i < num_devices; i++) {
std::cout << "Device " << i
<< "\n Flags " << dev_info[i].Flags
<< "\n Type " << dev_info[i].Type
<< "\n ID " << dev_info[i].ID
<< "\n LocID " << dev_info[i].LocId
<< "\n SerialNumber " << dev_info[i].SerialNumber
<< "\n Description " << dev_info[i].Description
<< std::endl;
}
} catch (const std::exception& e) {
std::cerr << "Error: " << e.what() << std::endl;
}
return 0;
}
|
604d0e602dde4de4fe01bb8550f01b9f4c669bba | a741637c734b5a73889b1508a1ee5442573681f4 | /external/pdlfs-common/src/status.cc | e80b80f00ec6c8457d6871aebe2817aa9f7b9745 | [
"BSD-3-Clause"
] | permissive | dlambrig/deltafs | 0c06565145c6777ab10783b198d80ebcc720dc6b | 4ce381ba9f4c5c256a82df95971149b6b85db600 | refs/heads/master | 2020-04-22T19:23:28.243009 | 2019-02-09T21:04:50 | 2019-02-09T21:04:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,279 | cc | status.cc | /*
* Copyright (c) 2011 The LevelDB Authors.
* Copyright (c) 2015-2017 Carnegie Mellon University.
*
* All rights reserved.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file. See the AUTHORS file for names of contributors.
*/
#include <stdint.h>
#include <string.h>
#include "pdlfs-common/status.h"
namespace pdlfs {
const char* Status::CopyState(const char* state) {
uint32_t size;
memcpy(&size, state, sizeof(size));
char* result = new char[size + 5];
memcpy(result, state, size + 5);
return result;
}
Status::Status(Code code, const Slice& msg, const Slice& msg2) {
assert(code != kOk);
const uint32_t len1 = msg.size();
const uint32_t len2 = msg2.size();
const uint32_t size = len1 + (len2 ? (2 + len2) : 0);
char* result = new char[size + 5];
memcpy(result, &size, sizeof(size));
result[4] = static_cast<char>(code);
memcpy(result + 5, msg.data(), len1);
if (len2) {
result[5 + len1] = ':';
result[6 + len1] = ' ';
memcpy(result + 7 + len1, msg2.data(), len2);
}
state_ = result;
}
namespace {
/* clang-format off */
static const char* kCodeString[] = {
/* kOk */ "OK", /* 0 */
/* kNotFound */ "Not found", /* 1 */
/* kAlreadyExists */ "Already exists", /* 2 */
/* kCorruption */ "Corruption", /* 3 */
/* kNotSupported */ "Not implemented", /* 4 */
/* kInvalidArgument */ "Invalid argument", /* 5 */
/* kIOError */ "IO error", /* 6 */
/* kBufferFull */ "Buffer full", /* 7 */
/* kReadOnly */ "Read only", /* 8 */
/* kWriteOnly */ "Write only", /* 9 */
/* kDeadLocked */ "Dead locked", /* 10 */
/* kOptimisticLockFailed */ "Optimistic lock failed", /* 11 */
/* kTryAgain */ "Try again", /* 12 */
/* kDisconnected */ "Disconnected", /* 13 */
/* kAssertionFailed */ "Assertion failed", /* 14 */
/* kAccessDenied */ "Permission denied", /* 15 */
/* kDirExpected */ "Dir expected", /* 16 */
/* kFileExpected */ "File expected", /* 17 */
/* kDirNotEmpty */ "Dir not empty", /* 18 */
/* kDirNotAllocated */ "Dir not allocated", /* 19 */
/* kDirDisabled */ "Dir disabled", /* 20 */
/* kDirMarkedDeleted */ "Dir marked deleted", /* 21 */
/* kInvalidFileDescriptor */ "Invalid file descriptor", /* 22 */
/* kTooManyOpens */ "Too many open files" /* 23 */
/* kRange */ "Out of range" /* 24 */
};
/* clang-format on */
}
std::string Status::ToString() const {
if (state_ == NULL) {
return "OK";
} else {
const char* type = kCodeString[err_code()];
uint32_t length;
memcpy(&length, state_, sizeof(length));
if (length == 0) {
return type;
} else {
std::string result(type);
result.append(": ");
result.append(state_ + 5, length);
return result;
}
}
}
} // namespace pdlfs
|
49c5349f27472022d7914ad34a4b54fff645ff07 | 443edae9d0064be944dc0160d8ffb3b8ee8faf1f | /initxml.h | 8e038cbfd232810074c9921d8e05b53521773884 | [] | no_license | trigrass2/i700-m | 3e3ed24f00c9fa457cbc88045b8fab0a6dd80ad3 | 17d582b3b270ac3c1f1f27e4f07d2031da1dc289 | refs/heads/master | 2020-07-11T21:25:31.326485 | 2018-07-20T09:08:30 | 2018-07-20T09:08:30 | 204,646,892 | 1 | 0 | null | 2019-08-27T15:35:00 | 2019-08-27T07:34:59 | null | UTF-8 | C++ | false | false | 1,056 | h | initxml.h | #ifndef INITXML_H
#define INITXML_H
#include <QDialog>
#include <QString>
#include <QStandardItem>
namespace Ui {
class initxml;
}
class initxml : public QDialog
{
Q_OBJECT
public:
explicit initxml(QWidget *parent = 0);
~initxml();
int read_xmll(QString filename);
//void do_xml(const QString opt,QString filename);
typedef struct {
QString Trans;
QString Comment;
uint8_t Timeout;
uint8_t Ccs;
uint16_t Index;
uint8_t SubIndex;
union
{
uint32_t DataInt;
uint8_t DataStr[100];
};
bool IsChar;
uint8_t DataLenth;
}XmlDataStruct;
XmlDataStruct xmlData[300];//120
int16_t XmlDataNum;
QString filename;
QStandardItemModel* model;
QStandardItem* itemProject;
private slots:
void on_loadButton_clicked();
void on_modifyButton_clicked();
void on_downloadButton_clicked();
private:
Ui::initxml *ui;
};
#endif // INITXML_H
|
2dc0cd2bf6ad72467356bbbbe34bfb3c3c5a712d | f7a2aa9d933466c25177a1abe06cc25a0650d9dd | /client/libraries/game/CFileObjectInstance.h | 4b75c401b8c8ff6c5097c02ecdc7ace891810b1b | [
"MIT"
] | permissive | CyberMor/sampvoice | b6f055dc32c975faef95a1eca31e60e6ea0120b2 | 11988682bf46a6ebdff8eab2810385610f221a21 | refs/heads/master | 2023-07-26T15:16:11.941105 | 2023-07-18T11:17:21 | 2023-07-18T11:17:21 | 165,523,561 | 139 | 105 | MIT | 2023-07-16T06:59:55 | 2019-01-13T15:47:46 | C++ | UTF-8 | C++ | false | false | 557 | h | CFileObjectInstance.h | /*
Plugin-SDK (Grand Theft Auto San Andreas) header file
Authors: GTA Community. See more here
https://github.com/DK22Pac/plugin-sdk
Do not delete this comment block. Respect others' work!
*/
#pragma once
#include "PluginBase.h"
#include "CVector.h"
#include "CQuaternion.h"
class PLUGIN_API CFileObjectInstance {
public:
CVector m_vecPosition;
CQuaternion m_qRotation;
int m_nModelId;
int m_nInterior;
int m_nLodIndex; // -1 - without LOD model
};
VALIDATE_SIZE(CFileObjectInstance, 0x28); |
77557dddd306744fa100fb7aa9f6e1f815eae600 | e8432ea0bd17cc866214dad44068088b202fa2b7 | /InteractiveFusion/PlaneCutSegmenter.cpp | f15743251c716a1297a579eae07de52f64bed7ee | [] | no_license | sirkryl/EditingRealityCPP | a531f13b5f7f92281b512b1ea82838435b0c9bbb | 4d2aa6db2bb33c7cb4257ffc0d8be73bde3630e3 | refs/heads/master | 2020-05-17T16:24:33.302625 | 2015-11-17T12:35:06 | 2015-11-17T12:35:06 | 25,351,681 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,752 | cpp | PlaneCutSegmenter.cpp | #include "PlaneCutSegmenter.h"
#include "DebugUtility.h"
#include "ModelData.h"
namespace InteractiveFusion {
PlaneCutSegmenter::PlaneCutSegmenter() :
Segmenter()
{
}
PlaneCutSegmenter::~PlaneCutSegmenter()
{
}
void PlaneCutSegmenter::SetSegmentationParameters(PlaneCutSegmentationParams _segmentationParams)
{
DebugUtility::DbgOut(L"PlaneCutSegmenter::SetSegmentationParameters");
PlaneCutSegmentationParams* temporaryParams = dynamic_cast<PlaneCutSegmentationParams*>(&_segmentationParams);
if (temporaryParams != nullptr)
segmentationParameters = *temporaryParams;
else
segmentationParameters = PlaneCutSegmentationParams();
}
bool PlaneCutSegmenter::ConvertToPointCloud(MeshContainer &_mesh)
{
CleanUp();
Segmenter::ConvertToPointCloud(_mesh);
return true;
}
bool PlaneCutSegmenter::UpdateSegmentation(GraphicsController& _glControl, ModelData& _modelData)
{
if (!HasPointCloudData())
{
if (!InitializeSegmentation(_modelData))
return false;
}
bool segmentationResult = Segment();
EstimateIndices();
if (!segmentationResult)
{
return false;
}
return true;
}
bool PlaneCutSegmenter::InitializeSegmentation(ModelData& _modelData)
{
std::shared_ptr<MeshContainer> remainingMesh = _modelData.GetCurrentlySelectedMesh();
if (remainingMesh == nullptr)
{
DebugUtility::DbgOut(L"PlaneCutSegmenter::InitializeSegmentation::No Mesh selected");
return false;
}
if (!ConvertToPointCloud(*remainingMesh))
return false;
return true;
}
bool PlaneCutSegmenter::Segment()
{
DebugUtility::DbgOut(L"PlaneCutSegmenter::Segment()");
temporarySegmentationClusterIndices.clear();
pcl::PointIndices verticesAbove;
pcl::PointIndices verticesBelow;
Logger::WriteToLog(L"PlaneCutSegmentation with Parameters X = " + std::to_wstring(segmentationParameters.planeParameters.x)
+ L", Y = " + std::to_wstring(segmentationParameters.planeParameters.y)
+ L", Z = " + std::to_wstring(segmentationParameters.planeParameters.z)
+ L", D = " + std::to_wstring(segmentationParameters.planeParameters.d), Logger::info);
int index = 0;
for (auto& vertex : mainCloud->points)
{
float iO = vertex.x*segmentationParameters.planeParameters.x + vertex.y*segmentationParameters.planeParameters.y + vertex.z * segmentationParameters.planeParameters.z - segmentationParameters.planeParameters.d;
if (iO > 0)
verticesAbove.indices.push_back(index);
else
verticesBelow.indices.push_back(index);
index++;
}
temporarySegmentationClusterIndices.push_back(verticesAbove);
temporarySegmentationClusterIndices.push_back(verticesBelow);
Logger::WriteToLog(L"Plane cut segmentation produced " + std::to_wstring((int)verticesAbove.indices.size()) + L" above and "
+ std::to_wstring((int)verticesAbove.indices.size()) + L"below.", Logger::info);
return true;
}
void PlaneCutSegmenter::UpdateHighlights(ModelData& _modelData)
{
if (GetClusterCount() == 0)
return;
DebugUtility::DbgOut(L"UpdatePlaneCutSegmenterHighlights:: Cluster Count: ", GetClusterCount() - 1);
std::vector<int> trianglesToBeColored = GetClusterIndices(GetClusterCount() - 1);
_modelData.TemporarilyColorTriangles(0, trianglesToBeColored, ColorIF{ 0.5f, 0.0f, 0.0f }, true);
}
void PlaneCutSegmenter::FinishSegmentation(ModelData& _inputModelData, ModelData& _outputModelData)
{
DebugUtility::DbgOut(L"PlaneCutSegmenter::FinishSegmentation:: Cluster Count: ", GetClusterCount());
_outputModelData.SetMeshAsDeleted(_outputModelData.GetCurrentlySelectedMeshIndex());
for (int i = 0; i < GetClusterCount(); i++)
{
_outputModelData.AddObjectMeshToData(ConvertToMesh(i));
}
}
void PlaneCutSegmenter::CleanUp()
{
Segmenter::CleanUp();
}
} |
8609076b16e23ceda9e69ce8bae77002b36e452a | c6f5524dd21cf8050aa06c9758ff54ec1811a469 | /ET580/Day 1 Array_recursion_asymptotic/01_Review_Arrays_Examples/EX_2_Linear_Search.cpp | 55283cf9ef83103b1abfb26c2eb2873380afcda9 | [] | no_license | AChen24562/C-Plus-plus | 482dbb33bd6b6b9b1cf49e3b5c0360285816d049 | 27364b7f02e5172aec89f2132bc963313b99d16b | refs/heads/master | 2022-06-21T12:37:40.370312 | 2022-06-17T14:44:46 | 2022-06-17T14:44:46 | 236,824,208 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,111 | cpp | EX_2_Linear_Search.cpp | // S. Trowbridge 2020
#include <iostream>
using namespace std;
void print(int *a, int size) { // print array
for(int i=0; i<size; ++i) { // iterate from 0 to size-1
cout << a[i] << " "; // print value at index i
}
}
int getIndex(int *a, int size, int value) { // linear search
for(int i=0; i<size; i++) { // iterate from 0 to size-1
if(a[i] == value) { // if num[i] is same as value
return i; // return i (the location of the value)
}
}
return -1; // return -1 if value not found in the array
}
int main( ) {
cout << endl;
const int SIZE = 10;
int numbers[SIZE] = {1, 5, 14, 23, 45, 52, 58, 71, 82, 91};
print(numbers, SIZE);
cout << "\n\n";
cout << "Number 23 at index " << getIndex(numbers, SIZE, 23) << "\n";
cout << "Number 58 at index " << getIndex(numbers, SIZE, 58) << "\n";
cout << "Number 11 at index " << getIndex(numbers, SIZE, 11) << "\n";
cout << endl;
return 0;
}
|
691499a2002788ec239914ad5894cc01f6ca2605 | 3190a9606fdb6a32b68b4012869c1074a5933ca4 | /c++/20140721/pthread/Consume.h | e52efa20f52db9fe33665beaae85a7086ca7bc5d | [] | no_license | lvchao0428/ultrapp | caa5971eddc98226bb62d8269b7be2537c442ca3 | 614c85e88dce932663389a434297f516ea3c979b | refs/heads/master | 2021-01-23T17:31:10.722025 | 2015-09-22T03:30:57 | 2015-09-22T03:30:57 | 21,064,395 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 254 | h | Consume.h |
#ifndef CONSUME_H_
#define CONSUME_H_
#include <pthread.h>
#include "Thread.h"
class Buffer;
//inherit must use .h file
class Consume:public Thread
{
public:
Consume(Buffer &buffer);
void run();
};
#endif /*CONSUME_H_*/
|
824332f4375da63eba8cad24ce83415b91bf6af3 | 7bf40ccb547c9dbe267aea74517ab8df5e4626ac | /TinyObj/GrahpicTut1/GraphicTut/src/PlayerController.cpp | 67d677aef210a39e5770f598e15fcb0ca3b2b442 | [] | no_license | BenjaminMatthewMoore/Virtual | 04d1ee5ae25210c336d611c0001d798cb6c92f1e | 07335be631c894d8765c2c10355ed12da041b973 | refs/heads/master | 2021-01-01T05:42:29.708471 | 2016-06-08T02:33:25 | 2016-06-08T02:33:25 | 59,450,315 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,297 | cpp | PlayerController.cpp | #include "PlayerController.h"
#include "ControllerHitReport.h"
#include "PhysicsScene.h"
#include "Gizmos.h"
#include "Window.h"
#include "GLFW\glfw3.h"
using namespace physx;
PlayerController::PlayerController(PhysicsScene* physicScene)
{
startPosition = PxExtendedVec3(20, 20, 20);
m_hitReport = new ControllerHitReport();
m_characterManager = PxCreateControllerManager(*physicScene->m_physicsScene);
PxCapsuleControllerDesc desc;
desc.height = 2.0f;
desc.radius = 1.0f;
//desc.position.set(0, 0, 0);z
desc.material = physicScene->m_physicsMaterial;
desc.reportCallback = m_hitReport;
desc.density = 10;
m_playerController = m_characterManager->createController(desc);
m_playerController->setPosition(startPosition);
physicScene->m_physicsScene->addActor(*m_playerController->getActor());
m_velocity = 10;
m_rotation = 0;
m_gravity = -9.8f;
m_hitReport->clearPlayerContactNormal();
//capsule.radius = 5;
//capsule.halfHeight = 30;
//m_playerController = PxCreateDynamic(*physicScene->m_physics, PxTransform(60, 60, 60), capsule, *physicScene->m_physicsMaterial, (PxReal)desc.density);
//physicScene->m_physicsScene->addActor(*m_playerCapsule);
bool onGround = true;
movementSpeed = 20.0f;
roatationSpeed = 1.0f;
}
PlayerController::~PlayerController()
{
}
void PlayerController::Update(float deltaTime, Window* activeWindow)
{
if (m_hitReport->getPlayerContactNormal().y > 0.1f)
{
m_velocity = -0.01f;
onGround = true;
}
else
{
m_velocity += m_gravity*deltaTime;
onGround = false;
}
m_hitReport->clearPlayerContactNormal();
PxVec3 velocity(0, m_velocity, 0);
if (glfwGetKey(activeWindow->m_window, GLFW_KEY_J) == GLFW_PRESS)
{
velocity.x = -movementSpeed*deltaTime;
}
if (glfwGetKey(activeWindow->m_window, GLFW_KEY_L) == GLFW_PRESS)
{
velocity.x = +movementSpeed*deltaTime;
}
if (glfwGetKey(activeWindow->m_window, GLFW_KEY_I) == GLFW_PRESS)
{
velocity.z = -movementSpeed*deltaTime;
}
if (glfwGetKey(activeWindow->m_window, GLFW_KEY_K) == GLFW_PRESS)
{
velocity.z = +movementSpeed*deltaTime;
}
const PxVec3 up = PxVec3(0, 1, 0);
float minDistance = 0.001f;
PxControllerFilters filter;
PxQuat rotation(m_rotation, PxVec3(0, 1, 0));
m_playerController->move(rotation.rotate(velocity), minDistance, deltaTime, filter);
} |
5370787666f57d6fee26cff726a99de9c2f29448 | a736f20a3dd0282a20d64d717fba98ece9e456c5 | /util/testHistPlotter.cxx | 10de1a45dbecaac223d3901ccdf58b10fce13317 | [] | no_license | oviazlo/WprimeTestingPackage | 1cea181633a823ecf31beb48e2bca6b8705d862d | dd5f4d51e55e73034d925c71b3f5688aee267a33 | refs/heads/master | 2020-04-06T06:50:56.052016 | 2016-08-17T15:33:13 | 2016-08-17T15:33:13 | 32,322,616 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,245 | cxx | testHistPlotter.cxx | /* Copyright 2016 Oleksandr Viazlo */
///*****************************************************************************
///
/// Plotting script. Plot MCs as THStack. Data - TH1 histogram.
/// Still in developing and testing state
///
///*****************************************************************************
/// WARNING HOWTO run the script
///
/// testHistPlotter -l finalAll_v4.txt -s w,data
/// testHistPlotter -l finalAll_v4.txt
///
/// -l <fileName>
/// list of all directories where histrograms produced by runMainLoop script are
/// can contain two columns: directory and tag. But second column is optional.
/// example:
/// submitDirs/finalData_0027 finalData_0027
/// submitDirs/finalData_0028_m150 finalData_0028_m150
/// submitDirs/finalData_0028_m151 finalData_0028_m151
/// submitDirs/finalMC_diboson finalMC_diboson
/// submitDirs/finalMC_inclusiveZ finalMC_inclusiveZ
/// submitDirs/finalMC_inclusiveW finalMC_inclusiveW
/// submitDirs/finalMC_massBinnedDY finalMC_massBinnedDY
/// submitDirs/finalMC_top finalMC_top
/// submitDirs/finalMC_missingDiboson finalMC_missingDiboson
///
/// -s <sample1,sample2,sample3,...>
/// list of inclusive samples to draw separated by comma
/// allowed sample names to use are specified here in
/// WprimeMergedSample::WprimeMergedSample() function.
/// if this flag is not used script will use plot default samples:
/// "diboson","z","top","w","data"
/// TODO
/// 1) add possibility to make plots w/o data
/// 2) draw errors on plots and on ratio plots
/// 3) use tags from input list
/// EventLoop/xAOD
#include "xAODRootAccess/Init.h"
#include "SampleHandler/SampleHandler.h"
#include "SampleHandler/Sample.h"
#include "SampleHandler/ToolsDiscovery.h"
#include "SampleHandler/DiskListLocal.h"
#include <SampleHandler/ScanDir.h>
#include <SampleHandler/ToolsJoin.h>
#include "EventLoop/Job.h"
#include "EventLoop/ProofDriver.h"
#include "EventLoop/DirectDriver.h"
#include <EventLoop/OutputStream.h>
#include <EventLoopAlgs/NTupleSvc.h>
/// ROOT
#include <TSystem.h>
#include <TH1F.h>
#include <TCanvas.h>
#include <TColor.h>
#include <Rtypes.h>
#include <TLegend.h>
#include <THStack.h>
/// std C/C++
#include <fstream>
#include <sstream>
/// private
#include "MyAnalysis/RecoAnalysis.h"
#include "HelpFunctions.h"
#include "histPlotter/WprimeMergedSample.h"
map<string,string> sampleMap;
po::variables_map vm;
Color_t colorArr[] = {kOrange, kAzure-9, kRed+1, kWhite, kYellow, kBlue, kViolet,
kGreen, kRed, kGreen, kRed, kGreen, kRed, kGreen, kRed, kGreen, kRed,
kGreen, kRed, kGreen, kRed, kGreen, kRed, kGreen, kRed, kGreen, kRed,
kGreen, kRed, kGreen, kRed, kGreen, kRed, kGreen, kRed, kGreen, kRed,
kGreen, kRed, kGreen, kRed, kGreen, kRed, kGreen, kRed, kGreen, kRed,
};
void setHistStyle(TH1D* inHist, Color_t kColor);
/// parse name of file from name of input list
TFile* createOutFile(string listName);
vector<string> getSamplesToDraw(WprimeMergedSample *mergedSample);
int main( int argc, char* argv[] ) {
po::options_description desc("Options");
desc.add_options()
("help,h", "Print help messages")
("sampleList,l", po::value<string>(), "file with list of samples and tags")
("samplesToDraw,s",po::value<string>()," list of samples to draw, separated by coma")
("histFolder,f",po::value<string>()," specify hist folder to use")
;
/// get global input arguments:
const size_t returnedMessage = parseOptionsWithBoost(vm, desc,argc,argv);
if (returnedMessage!=SUCCESS) std::exit(returnedMessage);
/// Take the submit directory from the input if provided:
std::string sampleList = "sampleList.txt";
if (vm.count("sampleList"))
sampleList = vm["sampleList"].as<std::string>();
cout << "[INFO]\tread list of samples from file: " << sampleList << endl;
std::ifstream sampleListStream;
sampleListStream.open (sampleList.c_str(), std::ifstream::in);
vector<string> samples, tags;
while(sampleListStream.good()){
std::string sample = "";
std::string tag = "";
sampleListStream >> sample >> tag;
if (sample == "")
continue;
samples.push_back(sample);
tags.push_back(tag);
cout << "[INFO]\tread sample-tag pair: {" << sample << "," << tag << "}"
<< endl;
}
if (samples.size()!=tags.size() || samples.size()==0){
cout << "[ERROR]\tsamples.size() = " << samples.size() <<
", tags.size() = " << tags.size() << endl;
return -1;
}
TFile* outFile = createOutFile(sampleList);
WprimeMergedSample *mergedSample = new WprimeMergedSample();
vector<string> samplesToDraw = getSamplesToDraw(mergedSample);
if (samplesToDraw.size()==0)
return 0;
for (int i=0; i<samples.size(); i++){
SH::SampleHandler sh;
cout << "[INFO]\tRead samples from dir: " << samples[i] << endl;
sh.load (samples[i] + "/hist");
mergedSample->AddSampleHandler(sh,samples[i]);
}
//string prefix = "muon/stage_final_noWeight/hObjDump_";
string histFolderName = "final";
if (vm.count("histFolder"))
histFolderName = vm["histFolder"].as<std::string>();
string prefix = "muon/stage_" + histFolderName + "/hObjDump_";
vector<string> plotsToDrawWithPrefix = {"pt","met","mt","eta","phi"};
vector<string> plotsToDrawWoPrefix = {"cutflow_hist"};
map<string,string> prefixMap;
vector<string> plotsToDraw;
plotsToDraw.reserve(plotsToDrawWithPrefix.size()+plotsToDrawWoPrefix.size());
plotsToDraw.insert(plotsToDraw.end(),plotsToDrawWithPrefix.begin(),plotsToDrawWithPrefix.end());
plotsToDraw.insert(plotsToDraw.end(),plotsToDrawWoPrefix.begin(),plotsToDrawWoPrefix.end());
for (int i=0; i<plotsToDrawWithPrefix.size(); i++){
prefixMap[plotsToDrawWithPrefix[i]] = prefix;
}
for (int i=0; i<plotsToDrawWoPrefix.size(); i++){
prefixMap[plotsToDrawWoPrefix[i]] = "";
}
SetAtlasStyle();
// gStyle->SetHistTopMargin(0.);
TCanvas* tmpCan = new TCanvas("c","c",3508*150/300.,2480*150/300.);
for (int i=0; i<plotsToDraw.size(); i++){
THStack *hs = new THStack("hs","Stacked 1D histograms");
TH1D *h2 = NULL;
TH1D* testHist = NULL;
TH1D* dataHist = NULL;
TH1D* multijetHist = NULL;
for (int k=0; k<samplesToDraw.size(); k++){
if (samplesToDraw[k]=="data"){
dataHist = mergedSample->GetMergedDataHist(prefixMap[plotsToDraw[i]]+plotsToDraw[i]);
dataHist->SetName(("mc_"+samplesToDraw[k]+"_" + histFolderName).c_str());
if(!outFile->cd(plotsToDraw[i].c_str())){
TDirectory *rdir = outFile->mkdir(plotsToDraw[i].c_str());
rdir->cd();
}
dataHist->Write();
continue;
}
if (samplesToDraw[k]=="multijet"){
std::string myHistName = prefixMap[plotsToDraw[i]]+plotsToDraw[i];
std::size_t found = myHistName.find("/hObjDump_");
myHistName.insert(found,"_QCD");
testHist =
// mergedSample->GetMergedMultijetHist(prefixMap[plotsToDraw[i]]+plotsToDraw[i]);
mergedSample->GetMergedDataHist(myHistName);
}
else
testHist = mergedSample->GetMergedHist(samplesToDraw[k],prefixMap[plotsToDraw[i]]+plotsToDraw[i]);
testHist->SetName(("mc_"+samplesToDraw[k]+"_" + histFolderName).c_str());
/// WARNING debug
// cout << "Print out binflow for hist: " << testHist->GetName() << endl;
// for (unsigned int iBin=1; iBin<=testHist->GetNbinsX(); iBin++){
// cout << testHist->GetBinContent(iBin) << endl;
// }
if (testHist!=NULL){
setHistStyle(testHist,colorArr[k]);
hs->Add(testHist);
}
else{
cout << "Plot *" << plotsToDraw[i] << "* is empty for sample " << samplesToDraw[k]
<< endl;
}
if (h2==NULL){
h2 = (TH1D*)testHist->Clone("h2");
}
else{
h2->Add(testHist);
}
if(!outFile->cd(plotsToDraw[i].c_str())){
TDirectory *rdir = outFile->mkdir(plotsToDraw[i].c_str());
rdir->cd();
}
testHist->Write();
// cout << endl;
// cout << "[DEBUG]\t" << plotsToDraw[i] << " " << samplesToDraw[k] << endl;
// testHist->Print("all");
}
outFile->Write();
TPad *pad1 = new TPad("pad1", "pad1", 0, 0.3, 1, 1.0);
pad1->SetBottomMargin(0); /// Upper and lower plot are joined
// pad1->SetGridx(); /// Vertical grid
pad1->Draw(); /// Draw the upper pad: pad1
pad1->cd(); /// pad1 becomes the current pad
std::size_t found = histFolderName.find("noMET_mT_cuts");
hs->Draw("HIST");
if (dataHist!=NULL)
dataHist->Draw("Esame");
if (i<3){
hs->SetMinimum(10E-7);
hs->SetMaximum(10E5);
if (found==std::string::npos){
hs->GetXaxis()->SetRangeUser(50,2000);
dataHist->GetXaxis()->SetRangeUser(50,2000);
}
}
else{
hs->SetMinimum(10E-1);
hs->SetMaximum(8*10E2);
if (found!=std::string::npos)
hs->SetMaximum(5*10E3);
}
hs->GetXaxis()->SetTitle(testHist->GetXaxis()->GetTitle());
hs->GetYaxis()->SetTitle(testHist->GetYaxis()->GetTitle());
gPad->Update();
if (i>=3){
gPad->SetLogx(0);
gPad->SetLogy(0);
}
else{
gPad->SetLogy();
gPad->SetLogx();
}
/// lower plot will be in pad
tmpCan->cd(); /// Go back to the main canvas before defining pad2
TPad *pad2 = new TPad("pad2", "pad2", 0, 0.05, 1, 0.3);
pad2->SetTopMargin(0);
pad2->SetBottomMargin(0.2);
// pad2->SetGridx(); /// vertical grid
pad2->SetGridy(); /// vertical grid
pad2->Draw();
pad2->cd(); /// pad2 becomes the current pad
gPad->Update();
if (i>=3){
gPad->SetLogx(0);
}
else{
gPad->SetLogx();
}
/// Define the ratio plot
TH1D *h3 = (TH1D*)dataHist->Clone("h3");
h3->SetLineColor(kBlack);
h3->SetMinimum(0.8); /// Define Y ..
h3->SetMaximum(1.35); /// .. range
h3->Sumw2();
h3->SetStats(0); /// No statistics on lower plot
h3->Divide(h2);
h3->SetMarkerStyle(21);
h3->Draw("ep"); /// Draw the ratio plot
/// Ratio plot (h3) settings
h3->SetTitle(""); /// Remove the ratio title
/// Y axis ratio plot settings
h3->GetYaxis()->SetTitle("Data/Bkg");
h3->GetYaxis()->SetNdivisions(505);
h3->GetYaxis()->SetTitleSize(30);
h3->GetYaxis()->SetTitleFont(43);
h3->GetYaxis()->SetTitleOffset(1.55);
h3->GetYaxis()->SetLabelFont(43); /// Absolute font size in pixel (precision 3)
h3->GetYaxis()->SetLabelSize(25);
h3->GetYaxis()->SetRangeUser(0.61,1.49);
/// X axis ratio plot settings
h3->GetXaxis()->SetTitleSize(30);
h3->GetXaxis()->SetTitleFont(43);
h3->GetXaxis()->SetTitleOffset(4.);
h3->GetXaxis()->SetLabelFont(43); /// Absolute font size in pixel (precision 3)
h3->GetXaxis()->SetLabelSize(25);
tmpCan->cd(); /// Go back to the main canvas
string outFileName = "pictures/" + histFolderName + ".ps";
if (i==0&&plotsToDraw.size()>1)
outFileName += "(";
if (i==(plotsToDraw.size()-1)&&plotsToDraw.size()>1)
outFileName += ")";
tmpCan->SaveAs(outFileName.c_str());
outFileName = "pictures/" + histFolderName + "_" + plotsToDraw[i] + ".ps";
tmpCan->SaveAs(outFileName.c_str());
outFileName = "pictures/" + histFolderName + "_" + plotsToDraw[i] + ".png";
tmpCan->SaveAs(outFileName.c_str());
}
return 0;
}
void setHistStyle(TH1D* inHist, Color_t kColor){
if (inHist==NULL)
return;
inHist->SetFillColor(kColor);
inHist->SetMarkerStyle(21);
inHist->SetMarkerColor(kColor);
}
TFile* createOutFile(string listName){
vector<string> tmpStrVec = GetWords(listName,'/');
string tmpStr = tmpStrVec[tmpStrVec.size()-1];
tmpStrVec = GetWords(tmpStr,'.');
(tmpStrVec.size()>1) ? tmpStr = tmpStrVec[tmpStrVec.size()-2] : tmpStrVec[0];
return new TFile((tmpStr+".root").c_str(),"RECREATE");
}
vector<string> getSamplesToDraw(WprimeMergedSample *mergedSample){
vector<string> samplesToDraw;
if (vm.count("samplesToDraw")){
samplesToDraw = GetWords(vm["samplesToDraw"].as<std::string>(),',');
cout << "[INFO]\tRunning over saples: ";
vector<string> supportedSamples = mergedSample->GetAllSupportedGlobalSampleTags();
std::vector<string>::iterator it;
for (int i=0; i<samplesToDraw.size(); i++){
cout << samplesToDraw[i] << " ";
it = find (supportedSamples.begin(), supportedSamples.end(), samplesToDraw[i]);
if (it == supportedSamples.end()){
cout << "Sample *" << samplesToDraw[i] << "* is not supported by code!!!" << endl;
cout << "Available options:" << endl;
for (int k=0; k<supportedSamples.size(); k++)
cout << supportedSamples[k] << " ";
cout << endl;
cout << "Terminate execution!!!" << endl;
}
}
cout << endl;
}
else
samplesToDraw = {"diboson","z","top","w","data"};
return samplesToDraw;
}
// std::vector<std::string> split(const std::string &s, char delim) {
// std::vector<std::string> elems;
// split(s, delim, elems);
// return elems;
// }
|
3015befd2e7ef28f849c812058b6def06530af41 | 638d256d0417a5721bfd5592c0dc0b5ddb8163ef | /lab10/Mebel.h | c57a8176548edaf8684c4912fdeff6954e9e0ec1 | [] | no_license | Es1337/OOP1 | 19238767f4da511f80a05147989ed52af092d27a | 019fa7f659d072b65cdb7d0cef1d93248a6037aa | refs/heads/master | 2022-09-21T20:47:30.129030 | 2020-06-06T11:40:25 | 2020-06-06T11:40:25 | 269,939,776 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 750 | h | Mebel.h | #pragma once
#include <iostream>
class Mebel
{
friend std::ostream& operator<<(std::ostream& os, const Mebel& m);
public:
Mebel() = default;
Mebel(int setSz, int setWys, int setDl) : sz(setSz), wys(setWys), dl(setDl){}
virtual ~Mebel()
{
std::cout << "~Mebel" << std::endl;
}
virtual void print() const
{
std::cout << "Mebel: sz: "<< sz << " wys: " << wys << " dl: " << dl;
}
private:
int sz;
int wys;
int dl;
};
// Stream operator overload using a virtual method to allow for different outputs
std::ostream& operator<<(std::ostream& os, const Mebel& m)
{
m.print();
return os;
} |
9c09bd191855aa865c2ea968bc0768a0153a6a27 | b7d4fc29e02e1379b0d44a756b4697dc19f8a792 | /deps/boost/libs/compute/test/test_svm_ptr.cpp | 1546deb70426cc90361b774e5c4a2f7d2f04c975 | [
"GPL-1.0-or-later",
"MIT",
"BSL-1.0"
] | permissive | vslavik/poedit | 45140ca86a853db58ddcbe65ab588da3873c4431 | 1b0940b026b429a10f310d98eeeaadfab271d556 | refs/heads/master | 2023-08-29T06:24:16.088676 | 2023-08-14T15:48:18 | 2023-08-14T15:48:18 | 477,156 | 1,424 | 275 | MIT | 2023-09-01T16:57:47 | 2010-01-18T08:23:13 | C++ | UTF-8 | C++ | false | false | 4,595 | cpp | test_svm_ptr.cpp | //---------------------------------------------------------------------------//
// Copyright (c) 2013-2014 Kyle Lutz <kyle.r.lutz@gmail.com>
//
// Distributed under the Boost Software License, Version 1.0
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//
// See http://boostorg.github.com/compute for more information.
//---------------------------------------------------------------------------//
#define BOOST_TEST_MODULE TestSvmPtr
#include <boost/test/unit_test.hpp>
#include <iostream>
#include <boost/compute/core.hpp>
#include <boost/compute/svm.hpp>
#include <boost/compute/container/vector.hpp>
#include <boost/compute/utility/source.hpp>
#include "quirks.hpp"
#include "check_macros.hpp"
#include "context_setup.hpp"
namespace compute = boost::compute;
BOOST_AUTO_TEST_CASE(empty)
{
}
#ifdef BOOST_COMPUTE_CL_VERSION_2_0
BOOST_AUTO_TEST_CASE(alloc)
{
REQUIRES_OPENCL_VERSION(2, 0);
compute::svm_ptr<cl_int> ptr = compute::svm_alloc<cl_int>(context, 8);
compute::svm_free(context, ptr);
}
BOOST_AUTO_TEST_CASE(svmmemcpy)
{
REQUIRES_OPENCL_VERSION(2, 0);
if(bug_in_svmmemcpy(device)){
std::cerr << "skipping svmmemcpy test case" << std::endl;
return;
}
cl_int input[] = { 1, 2, 3, 4, 5, 6, 7, 8 };
cl_int output[] = { 0, 0, 0, 0, 0, 0, 0, 0 };
compute::svm_ptr<cl_int> ptr = compute::svm_alloc<cl_int>(context, 8);
compute::svm_ptr<cl_int> ptr2 = compute::svm_alloc<cl_int>(context, 8);
// copying from and to host mem
queue.enqueue_svm_memcpy(ptr.get(), input, 8 * sizeof(cl_int));
queue.enqueue_svm_memcpy(output, ptr.get(), 8 * sizeof(cl_int));
queue.finish();
CHECK_HOST_RANGE_EQUAL(cl_int, 8, output, (1, 2, 3, 4, 5, 6, 7, 8));
// copying between svm mem
queue.enqueue_svm_memcpy(ptr2.get(), ptr.get(), 8 * sizeof(cl_int));
queue.enqueue_svm_memcpy(output, ptr2.get(), 8 * sizeof(cl_int));
queue.finish();
CHECK_HOST_RANGE_EQUAL(cl_int, 8, output, (1, 2, 3, 4, 5, 6, 7, 8));
compute::svm_free(context, ptr);
compute::svm_free(context, ptr2);
}
BOOST_AUTO_TEST_CASE(sum_svm_kernel)
{
REQUIRES_OPENCL_VERSION(2, 0);
const char source[] = BOOST_COMPUTE_STRINGIZE_SOURCE(
__kernel void sum_svm_mem(__global const int *ptr, __global int *result)
{
int sum = 0;
for(uint i = 0; i < 8; i++){
sum += ptr[i];
}
*result = sum;
}
);
compute::program program =
compute::program::build_with_source(source, context, "-cl-std=CL2.0");
compute::kernel sum_svm_mem_kernel = program.create_kernel("sum_svm_mem");
cl_int data[] = { 1, 2, 3, 4, 5, 6, 7, 8 };
compute::svm_ptr<cl_int> ptr = compute::svm_alloc<cl_int>(context, 8);
queue.enqueue_svm_map(ptr.get(), 8 * sizeof(cl_int), CL_MAP_WRITE);
for(size_t i = 0; i < 8; i ++) {
static_cast<cl_int*>(ptr.get())[i] = data[i];
}
queue.enqueue_svm_unmap(ptr.get());
compute::vector<cl_int> result(1, context);
sum_svm_mem_kernel.set_arg(0, ptr);
sum_svm_mem_kernel.set_arg(1, result);
queue.enqueue_task(sum_svm_mem_kernel);
queue.finish();
BOOST_CHECK_EQUAL(result[0], (36));
compute::svm_free(context, ptr);
}
#endif // BOOST_COMPUTE_CL_VERSION_2_0
#ifdef BOOST_COMPUTE_CL_VERSION_2_1
BOOST_AUTO_TEST_CASE(migrate)
{
REQUIRES_OPENCL_VERSION(2, 1);
compute::svm_ptr<cl_int> ptr =
compute::svm_alloc<cl_int>(context, 8);
// Migrate to device
std::vector<const void*> ptrs(1, ptr.get());
std::vector<size_t> sizes(1, 8 * sizeof(cl_int));
queue.enqueue_svm_migrate_memory(ptrs, sizes).wait();
// Set on device
const char source[] = BOOST_COMPUTE_STRINGIZE_SOURCE(
__kernel void foo(__global int *ptr)
{
for(int i = 0; i < 8; i++){
ptr[i] = i;
}
}
);
compute::program program =
compute::program::build_with_source(source, context, "-cl-std=CL2.0");
compute::kernel foo_kernel = program.create_kernel("foo");
foo_kernel.set_arg(0, ptr);
queue.enqueue_task(foo_kernel).wait();
// Migrate to host
queue.enqueue_svm_migrate_memory(
ptr.get(), 0, boost::compute::command_queue::migrate_to_host
).wait();
// Check
CHECK_HOST_RANGE_EQUAL(
cl_int, 8,
static_cast<cl_int*>(ptr.get()),
(0, 1, 2, 3, 4, 5, 6, 7)
);
compute::svm_free(context, ptr);
}
#endif // BOOST_COMPUTE_CL_VERSION_2_1
BOOST_AUTO_TEST_SUITE_END()
|
d6e2974d599909424f8bcb5c922b127e75ce9028 | 660f8a1a5c389cf02e0cac03fcad44e15a12784f | /AudioEqualizer/main.cpp | 0fdbc8e30f4b736650f3137e6091600e4a090cfb | [] | no_license | johnneycat/AudioEQ | 25b42d5d301c89854d1e123390e89838a6a84622 | ed89a0268ef9f84c30d8a6556547f30c8500aafa | refs/heads/master | 2022-03-01T17:31:10.722549 | 2019-09-02T22:32:22 | 2019-09-02T22:32:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,660 | cpp | main.cpp | // main.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "AudioDevice.h"
#include "Window.h"
#include "InputManager.h"
#include "FrameRateLimiter.h"
#include "EQDraw.h"
#include "Equalizer.h"
#include "DFT.h"
#include "EqualizerDFT.h"
#include "EqualizerDCT.h"
#include "EqualizerFFT.h"
// -----------------------------------------------------------------
// TODO: If we want, we can parameterize execution with a parameter file.
// Some parameters to consider:
//
// eq type (dct, dft, fft)
// num eq samples
// frame rate
// whether to print fps or not
// the file to play
// enter test mode
// -----------------------------------------------------------------
// -----------------------------------------------------------------
//
static const int kWIN_WIDTH = 600;
static const int kWIN_HEIGHT = 400;
static const int kNUM_EQ_SAMPLES = 256;
// -----------------------------------------------------------------
//
std::vector<std::string> wav_files = { "../resources/sine_sweep.wav",
"../resources/white_noise.wav",
"../resources/sample_piano.wav",
"../resources/Q2_sample_2.wav" };
// -----------------------------------------------------------------
//
const char const* FILE_PATH = wav_files[1].c_str();
// -----------------------------------------------------------------
// Forward declare.
void test();
//========================================================================
//
int main( int argc, char** argv )
{
// =================================================================
// Test mode execution:
// test();
// =================================================================
// Init the main window. This will also initialize SDL.
std::unique_ptr<IWindow> window( new Window( kWIN_WIDTH, kWIN_HEIGHT ) );
window->init();
// Get the audio data from file.
WavFile wav_file( kNUM_EQ_SAMPLES );
wav_file.openWavFile( FILE_PATH );
wav_file.displayInformation( FILE_PATH );
EQDraw eq_curve( *window, kNUM_EQ_SAMPLES );
Equalizer equalizer( kNUM_EQ_SAMPLES );
InputManager input_manager;
FrameRateLimiter frame_rate_limiter( 60, 1.0, 60 );
EqualizerDFT dft( kNUM_EQ_SAMPLES );
EqualizerDCT dct( kNUM_EQ_SAMPLES );
EqualizerFFT fft( kNUM_EQ_SAMPLES );
AudioDevice audio_device( std::move(wav_file._vectorized_audio), kNUM_EQ_SAMPLES, fft, eq_curve.getEqCoeffsBuffer() );
audio_device.setPlayState( DEVICE_STATE::PLAY );
size_t chunk_index = 0;
bool running = true;
while( input_manager.pollForEvents() )
{
frame_rate_limiter.setStartFrame();
eq_curve.processUserInput( input_manager.getKeys() );
std::vector<double> audio_spectrum;
audio_device.getFrequencySpectrum( audio_spectrum );
eq_curve.drawSpectrumTowindow( audio_spectrum );
eq_curve.drawToWindow();
audio_device.switchAnyalyzer( input_manager.getKeys() );
frame_rate_limiter.LimitFPS();
frame_rate_limiter.printFPS();
window->RenderFrame();
}
audio_device.terminate();
window->close();
return 0;
}
//========================================================================
//
void test()
{
std::cout << "=== COMPLEX CLASS ===============================================\n" << std::endl;
Math::Complex z;
z.test();
std::cout << "\n=== DFT MATRIX ==================================================\n" << std::endl;
DFT dft( 4 );
dft.test();
std::getchar();
exit( 0 );
}
|
8ea639dab3ada3caa4bb01237876d113af77ffb8 | f4d4695405d981ce0a7a612a826c9d26735f25f3 | /MoonliteAccelstepperAFMotor.ino | 57717247fea8b5f6da186281571d5a10ae968f67 | [
"BSD-2-Clause"
] | permissive | orlyandico/arduino-focuser-moonlite | 42994fa943aae0d226bd65295ac7ec514e470c65 | 486d0684c2c09c6b9c64c007d266e216354cf9f9 | refs/heads/master | 2021-01-01T05:09:31.137244 | 2020-09-29T23:30:05 | 2020-09-29T23:30:05 | 58,908,120 | 4 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 5,978 | ino | MoonliteAccelstepperAFMotor.ino | // Moonlite-compatible stepper controller
//
// Uses AccelStepper (http://www.airspayce.com/mikem/arduino/AccelStepper/)
// Uses AFMotor and the Adafruit v1.2 Motor Shield https://learn.adafruit.com/adafruit-motor-shield
//
// Requires a 10uf - 100uf capacitor between RESET and GND on the motor shield; this prevents the
// Arduino from resetting on connect (via DTR going low). Without the capacitor, this sketch works
// with the stand-alone Moonlite control program (non-ASCOM) but the ASCOM driver does not detect it.
// Adding the capacitor allows the Arduino to respond quickly enough to the ASCOM driver probe
//
// orly.andico@gmail.com, 13 April 2014
#include <AccelStepper.h>
#include <AFMotor.h>
// maximum speed is 160pps which should be OK for most
// tin can steppers
#define MAXSPEED 100
#define SPEEDMULT 3
AF_Stepper motor1(300, 1);
void forwardstep() {
motor1.onestep(BACKWARD, DOUBLE);
}
void backwardstep() {
motor1.onestep(FORWARD, DOUBLE);
}
AccelStepper stepper(forwardstep, backwardstep);
#define MAXCOMMAND 8
char inChar;
char cmd[MAXCOMMAND];
char param[MAXCOMMAND];
char line[MAXCOMMAND];
long pos;
int isRunning = 0;
int speed = 32;
int eoc = 0;
int idx = 0;
long millisLastMove = 0;
void setup()
{
Serial.begin(9600);
// we ignore the Moonlite speed setting because Accelstepper implements
// ramping, making variable speeds un-necessary
stepper.setSpeed(MAXSPEED);
stepper.setMaxSpeed(MAXSPEED);
stepper.setAcceleration(10);
stepper.enableOutputs();
memset(line, 0, MAXCOMMAND);
millisLastMove = millis();
}
void loop(){
// run the stepper if there's no pending command and if there are pending movements
if (!Serial.available())
{
if (isRunning) {
stepper.run();
millisLastMove = millis();
}
else {
// reported on INDI forum that some steppers "stutter" if disableOutputs is done repeatedly
// over a short interval; hence we only disable the outputs and release the motor some seconds
// after movement has stopped
if ((millis() - millisLastMove) > 15000) {
stepper.disableOutputs();
motor1.release();
}
}
if (stepper.distanceToGo() == 0) {
stepper.run();
isRunning = 0;
}
}
else {
// read the command until the terminating # character
while (Serial.available() && !eoc) {
inChar = Serial.read();
if (inChar != '#' && inChar != ':') {
line[idx++] = inChar;
if (idx >= MAXCOMMAND) {
idx = MAXCOMMAND - 1;
}
}
else {
if (inChar == '#') {
eoc = 1;
}
}
}
} // end if (!Serial.available())
// process the command we got
if (eoc) {
memset(cmd, 0, MAXCOMMAND);
memset(param, 0, MAXCOMMAND);
int len = strlen(line);
if (len >= 2) {
strncpy(cmd, line, 2);
}
if (len > 2) {
strncpy(param, line + 2, len - 2);
}
memset(line, 0, MAXCOMMAND);
eoc = 0;
idx = 0;
// the stand-alone program sends :C# :GB# on startup
// :C# is a temperature conversion, doesn't require any response
// LED backlight value, always return "00"
if (!strcasecmp(cmd, "GB")) {
Serial.print("00#");
}
// home the motor, hard-coded, ignore parameters since we only have one motor
if (!strcasecmp(cmd, "PH")) {
stepper.setCurrentPosition(8000);
stepper.moveTo(0);
isRunning = 1;
}
// firmware value, always return "10"
if (!strcasecmp(cmd, "GV")) {
Serial.print("10#");
}
// get the current motor position
if (!strcasecmp(cmd, "GP")) {
pos = stepper.currentPosition();
char tempString[6];
sprintf(tempString, "%04X", pos);
Serial.print(tempString);
Serial.print("#");
}
// get the new motor position (target)
if (!strcasecmp(cmd, "GN")) {
pos = stepper.targetPosition();
char tempString[6];
sprintf(tempString, "%04X", pos);
Serial.print(tempString);
Serial.print("#");
}
// get the current temperature, hard-coded
if (!strcasecmp(cmd, "GT")) {
Serial.print("20#");
}
// get the temperature coefficient, hard-coded
if (!strcasecmp(cmd, "GC")) {
Serial.print("02#");
}
// get the current motor speed, only values of 02, 04, 08, 10, 20
if (!strcasecmp(cmd, "GD")) {
char tempString[6];
sprintf(tempString, "%02X", speed);
Serial.print(tempString);
Serial.print("#");
}
// set speed, only acceptable values are 02, 04, 08, 10, 20
if (!strcasecmp(cmd, "SD")) {
speed = hexstr2long(param);
// we ignore the Moonlite speed setting because Accelstepper implements
// ramping, making variable speeds un-necessary
// stepper.setSpeed(speed * SPEEDMULT);
// stepper.setMaxSpeed(speed * SPEEDMULT);
stepper.setSpeed(MAXSPEED);
stepper.setMaxSpeed(MAXSPEED);
}
// whether half-step is enabled or not, always return "00"
if (!strcasecmp(cmd, "GH")) {
Serial.print("00#");
}
// motor is moving - 01 if moving, 00 otherwise
if (!strcasecmp(cmd, "GI")) {
if (abs(stepper.distanceToGo()) > 0) {
Serial.print("01#");
}
else {
Serial.print("00#");
}
}
// set current motor position
if (!strcasecmp(cmd, "SP")) {
pos = hexstr2long(param);
stepper.setCurrentPosition(pos);
}
// set new motor position
if (!strcasecmp(cmd, "SN")) {
pos = hexstr2long(param);
stepper.moveTo(pos);
}
// initiate a move
if (!strcasecmp(cmd, "FG")) {
isRunning = 1;
stepper.enableOutputs();
}
// stop a move
if (!strcasecmp(cmd, "FQ")) {
isRunning = 0;
stepper.moveTo(stepper.currentPosition());
stepper.run();
}
}
} // end loop
long hexstr2long(char *line) {
long ret = 0;
ret = strtol(line, NULL, 16);
return (ret);
}
|
b90af8e0399bbcae1dc0522a4d2896ef53d37d75 | 2d4221efb0beb3d28118d065261791d431f4518a | /OIDE源代码/OLIDE/Controls/scintilla/SyntaxCtrl.h | f028857df44252a76e021581ed5ab40e61f6d17b | [] | no_license | ophyos/olanguage | 3ea9304da44f54110297a5abe31b051a13330db3 | 38d89352e48c2e687fd9410ffc59636f2431f006 | refs/heads/master | 2021-01-10T05:54:10.604301 | 2010-03-23T11:38:51 | 2010-03-23T11:38:51 | 48,682,489 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 779 | h | SyntaxCtrl.h | #pragma once
#include "ScintillaCtrl.h"
// CSyntaxCtrl
class SCINTILLACTRL_EXT_CLASS CSyntaxCtrl : public CScintillaCtrl
{
DECLARE_DYNAMIC(CSyntaxCtrl)
public:
CSyntaxCtrl();
virtual ~CSyntaxCtrl();
public:
int GetCurrentLine();
protected:
afx_msg void OnRButtonDown(UINT nFlags, CPoint point);
afx_msg void OnRButtonUp(UINT nFlags, CPoint point);
DECLARE_MESSAGE_MAP()
public:
afx_msg void OnChar(UINT nChar, UINT nRepCnt, UINT nFlags);
afx_msg void OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags);
afx_msg void OnKeyUp(UINT nChar, UINT nRepCnt, UINT nFlags);
afx_msg void OnLButtonDown(UINT nFlags, CPoint point);
afx_msg void OnLButtonUp(UINT nFlags, CPoint point);
afx_msg BOOL OnHelpInfo(HELPINFO* pHelpInfo);
};
|
83edbaba5dc3208cd1830d96a523285b51bc303c | 01ec5fae952211e0a0ab29dfb49a0261a8510742 | /backup/source/cpp/[430]扁平化多级双向链表.cpp | 4d6b3e9a9b901f6e943920a125204bf128803da7 | [] | no_license | algoboy101/LeetCodeCrowdsource | 5cbf3394087546f9051c493b1613b5587c52056b | 25e93171fa16d6af5ab0caec08be943d2fdd7c2e | refs/heads/master | 2021-02-20T00:18:51.225422 | 2020-06-21T09:04:24 | 2020-06-21T09:04:24 | 245,323,834 | 10 | 4 | null | 2020-03-09T02:23:39 | 2020-03-06T03:43:27 | C++ | UTF-8 | C++ | false | false | 1,117 | cpp | [430]扁平化多级双向链表.cpp | //您将获得一个双向链表,除了下一个和前一个指针之外,它还有一个子指针,可能指向单独的双向链表。这些子列表可能有一个或多个自己的子项,依此类推,生成多级数据结构
//,如下面的示例所示。
//
// 扁平化列表,使所有结点出现在单级双链表中。您将获得列表第一级的头部。
//
//
//
// 示例:
//
// 输入:
// 1---2---3---4---5---6--NULL
// |
// 7---8---9---10--NULL
// |
// 11--12--NULL
//
//输出:
//1-2-3-7-8-11-12-9-10-4-5-6-NULL
//
//
//
//
// 以上示例的说明:
//
// 给出以下多级双向链表:
//
//
//
//
//
// 我们应该返回如下所示的扁平双向链表:
//
//
// Related Topics 深度优先搜索 链表
//leetcode submit region begin(Prohibit modification and deletion)
/*
// Definition for a Node.
class Node {
public:
int val;
Node* prev;
Node* next;
Node* child;
};
*/
class Solution {
public:
Node* flatten(Node* head) {
}
};
//leetcode submit region end(Prohibit modification and deletion)
|
e5e9959e002c91d368cbf724c6a67fa6ec75ac84 | 278a387702eccb05752471d80e9ff21cc232f941 | /src/components/hitable.cpp | ff83e46751d265d6ebae5ebdb68411b3da46b179 | [
"MIT"
] | permissive | ChinYing-Li/ClusterEngine | 2707f92870360aaea8d179181cc0c4d697d0ce92 | 2625dfb194a65d6b277f6c3c57602319000bce16 | refs/heads/master | 2023-07-07T06:26:27.533531 | 2021-08-15T13:44:16 | 2021-08-15T13:44:16 | 263,721,285 | 3 | 0 | MIT | 2020-10-09T11:37:34 | 2020-05-13T19:13:01 | C | UTF-8 | C++ | false | false | 156 | cpp | hitable.cpp | #include "src/components/hitable.h"
Hitable::Hitable():
Drawable()
{}
Hitable::Hitable(const float x, const float y, const float z):
Drawable(x, y, z)
{}
|
12f10ee83841b2f2ac2180556c8b3e09b9bc4f13 | eacb94b1e073d390c7f24c3b3bb59d3e600f204a | /tests/cuda3.2/tests/sortingNetworks/main.cpp | 481a6776588240424b728a6459a180ff616ad474 | [
"BSD-3-Clause"
] | permissive | mprevot/gpuocelot | b04d20ee58958efd7146ab7b3e798df8127b1a9c | d9277ef05a110e941aef77031382d0260ff115ef | refs/heads/master | 2020-10-01T19:01:38.047090 | 2019-12-12T12:41:41 | 2019-12-12T12:41:41 | 227,603,673 | 1 | 0 | BSD-3-Clause | 2019-12-12T12:38:19 | 2019-12-12T12:38:19 | null | UTF-8 | C++ | false | false | 5,664 | cpp | main.cpp | /*
* Copyright 1993-2010 NVIDIA Corporation. All rights reserved.
*
* Please refer to the NVIDIA end user license agreement (EULA) associated
* with this source code for terms and conditions that govern your use of
* this software. Any use, reproduction, disclosure, or distribution of
* this software and related documentation outside the terms of the EULA
* is strictly prohibited.
*
*/
/*
* This sample implemenets bitonic sort and odd-even merge sort, algorithms
* belonging to the class of sorting networks.
* While generally subefficient on large sequences
* compared to algorithms with better asymptotic algorithmic complexity
* (i.e. merge sort or radix sort), may be the algorithms of choice for sorting
* batches of short- or mid-sized arrays.
* Refer to the excellent tutorial by H. W. Lang:
* http://www.iti.fh-flensburg.de/lang/algorithmen/sortieren/networks/indexen.htm
*
* Victor Podlozhnyuk, 07/09/2009
*/
// Utilities and system includes
#include <shrUtils.h>
#include <cutil_inline.h>
#include "sortingNetworks_common.h"
////////////////////////////////////////////////////////////////////////////////
// Test driver
////////////////////////////////////////////////////////////////////////////////
int main(int argc, char** argv)
{
// Start logs
shrSetLogFileName ("sortingNetworks.txt");
shrLog("%s Starting...\n\n", argv[0]);
shrLog("Starting up CUDA context...\n");
if( cutCheckCmdLineFlag(argc, (const char**)argv, "device") )
cutilDeviceInit(argc, argv);
else
cudaSetDevice( cutGetMaxGflopsDeviceId() );
uint *h_InputKey, *h_InputVal, *h_OutputKeyGPU, *h_OutputValGPU;
uint *d_InputKey, *d_InputVal, *d_OutputKey, *d_OutputVal;
uint hTimer;
const uint N = isDeviceEmulation() ? 8192 : 1048576;
const uint DIR = 0;
const uint numValues = 65536;
const uint numIterations = 1;
shrLog("Allocating and initializing host arrays...\n\n");
cutCreateTimer(&hTimer);
h_InputKey = (uint *)malloc(N * sizeof(uint));
h_InputVal = (uint *)malloc(N * sizeof(uint));
h_OutputKeyGPU = (uint *)malloc(N * sizeof(uint));
h_OutputValGPU = (uint *)malloc(N * sizeof(uint));
srand(2001);
for(uint i = 0; i < N; i++){
h_InputKey[i] = rand() % numValues;
h_InputVal[i] = i;
}
shrLog("Allocating and initializing CUDA arrays...\n\n");
cutilSafeCall( cudaMalloc((void **)&d_InputKey, N * sizeof(uint)) );
cutilSafeCall( cudaMalloc((void **)&d_InputVal, N * sizeof(uint)) );
cutilSafeCall( cudaMalloc((void **)&d_OutputKey, N * sizeof(uint)) );
cutilSafeCall( cudaMalloc((void **)&d_OutputVal, N * sizeof(uint)) );
cutilSafeCall( cudaMemcpy(d_InputKey, h_InputKey, N * sizeof(uint), cudaMemcpyHostToDevice) );
cutilSafeCall( cudaMemcpy(d_InputVal, h_InputVal, N * sizeof(uint), cudaMemcpyHostToDevice) );
int flag = 1;
shrLog("Running GPU bitonic sort (%u identical iterations)...\n\n", numIterations);
for(uint arrayLength = 64; arrayLength <= N; arrayLength *= 2){
shrLog("Testing array length %u (%u arrays per batch)...\n", arrayLength, N / arrayLength);
cutilSafeCall( cudaThreadSynchronize() );
cutResetTimer(hTimer);
cutStartTimer(hTimer);
uint threadCount = 0;
for(uint i = 0; i < numIterations; i++)
threadCount = bitonicSort(
d_OutputKey,
d_OutputVal,
d_InputKey,
d_InputVal,
N / arrayLength,
arrayLength,
DIR
);
cutilSafeCall( cudaThreadSynchronize() );
cutStopTimer(hTimer);
shrLog("Average time: %f ms\n\n", cutGetTimerValue(hTimer) / numIterations);
if (arrayLength == N)
{
double dTimeSecs = 1.0e-3 * cutGetTimerValue(hTimer) / numIterations;
shrLogEx(LOGBOTH | MASTER, 0, "sortingNetworks-bitonic, Throughput = %.4f MElements/s, Time = %.5f s, Size = %u elements, NumDevsUsed = %u, Workgroup = %u\n",
(1.0e-6 * (double)arrayLength/dTimeSecs), dTimeSecs, arrayLength, 1, threadCount);
}
shrLog("\nValidating the results...\n");
shrLog("...reading back GPU results\n");
cutilSafeCall( cudaMemcpy(h_OutputKeyGPU, d_OutputKey, N * sizeof(uint), cudaMemcpyDeviceToHost) );
cutilSafeCall( cudaMemcpy(h_OutputValGPU, d_OutputVal, N * sizeof(uint), cudaMemcpyDeviceToHost) );
int keysFlag = validateSortedKeys(h_OutputKeyGPU, h_InputKey, N / arrayLength, arrayLength, numValues, DIR);
int valuesFlag = validateValues(h_OutputKeyGPU, h_OutputValGPU, h_InputKey, N / arrayLength, arrayLength);
flag = flag && keysFlag && valuesFlag;
shrLog("\n");
}
shrLog( flag ? "PASSED\n\n" : "FAILED\n\n");
shrLog("Shutting down...\n");
cutilCheckError( cutDeleteTimer(hTimer) );
cutilSafeCall( cudaFree(d_OutputVal) );
cutilSafeCall( cudaFree(d_OutputKey) );
cutilSafeCall( cudaFree(d_InputVal) );
cutilSafeCall( cudaFree(d_InputKey) );
free(h_OutputValGPU);
free(h_OutputKeyGPU);
free(h_InputVal);
free(h_InputKey);
cudaThreadExit();
shrEXIT(argc, (const char**)argv);
}
|
9c1e076cdcb22742710275793db26639fc31d97d | ae4a20cbbff5e77cfe632c75be577577fd7b64da | /cp3/ad-hoc/UVa_489_HangmanJudge.cpp | d955f00a405fc9d5fe62d2fc2b80250ac8c53c2b | [] | no_license | geeooleea/ACM-ICPC | 43903d2c99d747305884f0ec387adde6f700b958 | 6ed19114f0aa535f932fdd3afc577f5b3176f9b7 | refs/heads/master | 2020-04-02T16:40:35.700428 | 2019-11-13T16:36:36 | 2019-11-13T16:36:36 | 154,623,588 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,411 | cpp | UVa_489_HangmanJudge.cpp | #include <iostream>
#include <unordered_set>
using namespace std;
unordered_set<char> tried; // avoid duplicate wrong guesses
int main() {
int round_n;
string word;
string guess;
int lives;
cin >> round_n;
while (round_n != -1) {
cout << "Round " << round_n << endl;
cin >> word >> guess;
lives = 7;
// cout << guess << endl;
for (int i=0; i<guess.length() && lives > 0 && !word.empty(); i++) {
if (!tried.count(guess[i])) {
if (lives > 0) {
tried.emplace(guess[i]);
int len_i = word.length();
for (int j=0; j<word.length(); j++) {
if (word[j] == guess[i]) {
word.erase(word.begin()+j);
j--;
}
}
if (word.length() == len_i) { // guess is not present in string
lives--;
}
}
}
}
if (lives > 0) {
// cout << word.empty() << endl;
if (word.empty()) {
cout << "You win.\n";
} else {
cout << "You chickened out.\n";
}
} else {
cout << "You lose.\n";
}
cin >> round_n;
tried.clear();
}
return 0;
} |
c4d5e2990fc82fac97f3f786b590c41ef81ba533 | 4fddbc04d6196e915a68968e9845bf2d77513cec | /lib/jpegli/common.cc | 5f34372f3e534647d3b39d1520496596d85a2c1d | [
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla"
] | permissive | libjxl/libjxl | 4159f66557f01b7f8e76df8710d7a46bcbfa7fa3 | 4b8aad231bc7857158be8e4bf554a805596b1916 | refs/heads/main | 2023-08-25T19:45:32.798803 | 2023-08-24T10:11:25 | 2023-08-24T14:02:13 | 340,219,494 | 1,254 | 237 | BSD-3-Clause | 2023-09-14T11:13:28 | 2021-02-19T00:56:12 | C++ | UTF-8 | C++ | false | false | 1,602 | cc | common.cc | // Copyright (c) the JPEG XL Project 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 "lib/jpegli/common.h"
#include "lib/jpegli/decode_internal.h"
#include "lib/jpegli/encode_internal.h"
#include "lib/jpegli/memory_manager.h"
void jpegli_abort(j_common_ptr cinfo) {
if (cinfo->mem == nullptr) return;
for (int pool_id = 0; pool_id < JPOOL_NUMPOOLS; ++pool_id) {
if (pool_id == JPOOL_PERMANENT) continue;
(*cinfo->mem->free_pool)(cinfo, pool_id);
}
if (cinfo->is_decompressor) {
cinfo->global_state = jpegli::kDecStart;
} else {
cinfo->global_state = jpegli::kEncStart;
}
}
void jpegli_destroy(j_common_ptr cinfo) {
if (cinfo->mem == nullptr) return;
(*cinfo->mem->self_destruct)(cinfo);
if (cinfo->is_decompressor) {
cinfo->global_state = jpegli::kDecNull;
delete reinterpret_cast<j_decompress_ptr>(cinfo)->master;
} else {
cinfo->global_state = jpegli::kEncNull;
}
}
JQUANT_TBL* jpegli_alloc_quant_table(j_common_ptr cinfo) {
JQUANT_TBL* table = jpegli::Allocate<JQUANT_TBL>(cinfo, 1);
table->sent_table = FALSE;
return table;
}
JHUFF_TBL* jpegli_alloc_huff_table(j_common_ptr cinfo) {
JHUFF_TBL* table = jpegli::Allocate<JHUFF_TBL>(cinfo, 1);
table->sent_table = FALSE;
return table;
}
int jpegli_bytes_per_sample(JpegliDataType data_type) {
switch (data_type) {
case JPEGLI_TYPE_UINT8:
return 1;
case JPEGLI_TYPE_UINT16:
return 2;
case JPEGLI_TYPE_FLOAT:
return 4;
default:
return 0;
}
}
|
c3bb386aaf104429bda6e60cc80537ebe052f5a0 | d50ab7fe87359deb5c97588994402e94e8c57432 | /base/communication.hpp | ca67b80cca8d6b2e70a43664b1155858cd96f1a0 | [
"Apache-2.0"
] | permissive | Aaronchangji/Grasper | ee4aeb5566a6b0e298ad26c7e541b1d6874f4f8c | 51b272bf7304f1b9758e68dbbcf68517803b1fa6 | refs/heads/master | 2021-06-25T13:28:37.697321 | 2021-04-03T09:33:12 | 2021-04-03T09:38:15 | 223,234,231 | 0 | 0 | Apache-2.0 | 2019-11-21T18:04:15 | 2019-11-21T18:04:14 | null | UTF-8 | C++ | false | false | 3,024 | hpp | communication.hpp | /* Copyright 2019 Husky Data Lab, CUHK
Authors: Hongzhi Chen (hzchen@cse.cuhk.edu.hk)
*/
#ifndef COMMUNICATION_HPP_
#define COMMUNICATION_HPP_
#include <mpi.h>
#include <vector>
#include "base/node.hpp"
#include "base/serialization.hpp"
#include "utils/global.hpp"
#include "utils/unit.hpp"
using namespace std;
// ============================================
int all_sum(int my_copy, MPI_Comm world = MPI_COMM_WORLD);
long long master_sum_LL(long long my_copy, MPI_Comm world = MPI_COMM_WORLD);
long long all_sum_LL(long long my_copy, MPI_Comm world = MPI_COMM_WORLD);
char all_bor(char my_copy, MPI_Comm world = MPI_COMM_WORLD);
bool all_lor(bool my_copy, MPI_Comm world = MPI_COMM_WORLD);
bool all_land(bool my_copy, MPI_Comm world = MPI_COMM_WORLD);
// ============================================
void send(void* buf, int size, int dst, MPI_Comm world, int tag = COMMUN_CHANNEL);
int recv(void* buf, int size, int src, MPI_Comm world, int tag = COMMUN_CHANNEL); // return the actual source, since "src" can be MPI_ANY_SOURCE
// ============================================
void send_ibinstream(ibinstream& m, int dst, MPI_Comm world, int tag = COMMUN_CHANNEL);
void recv_obinstream(obinstream& m, int src, MPI_Comm world, int tag = COMMUN_CHANNEL);
// ============================================
// obj-level send/recv
template <class T>
void send_data(Node & node, const T& data, int dst, bool is_global, int tag = COMMUN_CHANNEL);
template <class T>
T recv_data(Node & node, int src, bool is_global, int tag = COMMUN_CHANNEL);
// ============================================
// all-to-all
template <class T>
void all_to_all(Node & node, bool is_global, std::vector<T>& to_exchange);
template <class T>
void all_to_all(Node & node, bool is_global, vector<vector<T*>> & to_exchange);
template <class T, class T1>
void all_to_all(Node & node, bool is_global, vector<T>& to_send, vector<T1>& to_get);
template <class T, class T1>
void all_to_all_cat(Node & node, bool is_global, std::vector<T>& to_exchange1, std::vector<T1>& to_exchange2);
template <class T, class T1, class T2>
void all_to_all_cat(Node & node, bool is_global, std::vector<T>& to_exchange1, std::vector<T1>& to_exchange2, std::vector<T2>& to_exchange3);
// ============================================
// scatter
template <class T>
void master_scatter(Node & node, bool is_global, vector<T>& to_send);
template <class T>
void slave_scatter(Node & node, bool is_global, T& to_get);
// ================================================================
// gather
template <class T>
void master_gather(Node & node, bool is_global, vector<T>& to_get);
template <class T>
void slave_gather(Node & node, bool is_global, T& to_send);
// ================================================================
// bcast
template <class T>
void master_bcast(Node & node, bool is_global, T& to_send);
template <class T>
void slave_bcast(Node & node, bool is_global, T& to_get);
#include "communication.tpp"
#endif /* COMMUNICATION_HPP_ */
|
b1d64775d21cccee8809c26c5578c8102ab49ad4 | 738853f3f29836c9d3ea26a25df85913c876e2a9 | /include/clu/type_erasure.h | f461223e642bb01437d6dcfc3044cc80e53ff172 | [
"MIT"
] | permissive | gorilux/clu | c61f4823323078739a2f97e2d17c06cebe561c5a | 92e382a854cd9c5d678c4465c099cd3a84f190c0 | refs/heads/master | 2023-03-28T07:48:27.760676 | 2021-03-13T11:51:51 | 2021-03-13T11:51:51 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 17,469 | h | type_erasure.h | #pragma once
#include <tuple>
#include <typeinfo>
#include "new.h"
#include "take.h"
#include "concepts.h"
#include "function_traits.h"
#include "type_traits.h"
#include "meta/value_list.h"
namespace clu
{
namespace te
{
struct policy_base {};
template <typename T> concept policy = std::derived_from<T, policy_base>;
// @formatter:off
struct nullable : policy_base {};
struct copyable : policy_base {};
template <size_t Size> struct small_buffer : policy_base { static constexpr size_t size = Size; };
template <size_t Size> struct stack_only : policy_base { static constexpr size_t size = Size; };
// @formatter:on
}
namespace detail
{
template <typename Impl, typename Members>
concept implements_model = requires { typename Members::template members<Impl>; };
struct omnipotype
{
template <typename T>
explicit(false) operator T() const { return std::declval<T>(); }
};
template <typename Model>
using prototype = typename Model::template interface<meta::empty_type_list>;
using copy_ctor_t = void* (*)(void* buf, const void* from);
using move_ctor_t = void (*)(void* buf, void* from) noexcept;
using dtor_t = void (*)(void*) noexcept;
// @formatter:off
template <bool Copyable> struct copy_vfptr_provider {};
template <> struct copy_vfptr_provider<true> { copy_ctor_t copy_ctor = nullptr; };
template <typename T, size_t BufferSize>
concept stack_storable =
sizeof(T) <= BufferSize &&
alignof(T) <= alignof(std::max_align_t) &&
std::is_nothrow_move_constructible_v<T>;
// @formatter:on
template <typename Model, bool Copyable>
struct vtable : copy_vfptr_provider<Copyable>
{
private:
template <typename T, size_t BufferSize>
static void* copy_impl(void* buf, const void* from)
{
void* result;
if constexpr (stack_storable<T, BufferSize>)
result = buf;
else
result = aligned_alloc_for<T>();
new(result) T(*static_cast<const T*>(from));
return result;
}
template <typename T>
static void move_impl(void* buf, void* from) noexcept { new(buf) T(static_cast<T&&>(*static_cast<T*>(from))); }
template <typename T, size_t BufferSize>
static void dtor_impl(void* ptr) noexcept
{
static_cast<T*>(ptr)->~T();
if constexpr (!stack_storable<T, BufferSize>) aligned_free_for<T>(ptr);
}
template <auto Member>
static constexpr auto vfptr_type_impl()
{
using traits = function_traits<decltype(Member)>;
using ret = typename traits::return_type;
return []<typename... As>(meta::type_list<As...>)
{
return static_cast<ret(*)(void*, As ...)>(nullptr);
}(typename traits::argument_types{});
}
template <auto... Vs>
static constexpr auto vfptrs_type_impl(meta::value_list<Vs...>)
{
return std::tuple<
decltype(vfptr_type_impl<Vs>())...>{};
}
using vfptrs_type = decltype(vfptrs_type_impl(typename Model::template members<prototype<Model>>{}));
template <typename T, auto Member, typename R, typename... As>
static constexpr auto gen_vfptr(R (*)(void*, As ...))
{
using traits = function_traits<decltype(Member)>;
return +[](void* ptr, As ... args) -> R
{
using ref_type = typename traits::implicit_param_type;
auto&& ref = static_cast<ref_type>(*static_cast<typename traits::class_type*>(ptr));
return std::invoke(Member, std::forward<ref_type>(ref), std::forward<As>(args)...);
};
}
template <typename T>
static constexpr auto gen_vfptrs()
{
return []<auto... Member, typename... VfptrT>(meta::value_list<Member...>, meta::type_list<VfptrT...>)
{
return std::tuple{ gen_vfptr<T, Member>(static_cast<VfptrT>(nullptr))... };
}(typename Model::template members<T>{}, meta::extract_list_t<vfptrs_type>{});
}
public:
move_ctor_t move_ctor = nullptr;
dtor_t dtor = nullptr;
vfptrs_type vfptrs{};
template <typename T, size_t BufferSize>
static constexpr vtable generate_for()
{
vtable result;
if constexpr (Copyable) result.copy_ctor = copy_impl<T, BufferSize>;
if constexpr (stack_storable<T, BufferSize>) result.move_ctor = move_impl<T>;
result.dtor = dtor_impl<T, BufferSize>;
result.vfptrs = gen_vfptrs<T>();
return result;
}
};
template <typename Vtable, typename T, size_t BufferSize>
inline constexpr Vtable vtable_for = Vtable::template generate_for<T, BufferSize>();
class heap_storage
{
private:
void* ptr_ = nullptr;
public:
static constexpr size_t buffer_size = 0;
heap_storage() = default;
template <typename T, typename... Ts>
void emplace(Ts&&... args)
{
ptr_ = aligned_alloc_for<T>();
try { new(ptr_) T(std::forward<Ts>(args)...); }
catch (...)
{
aligned_free_for<T>(ptr_);
throw;
}
}
void copy(const heap_storage& other, const copy_ctor_t ctor) { ptr_ = ctor(nullptr, other.ptr_); }
void move(heap_storage&& other, move_ctor_t) noexcept { ptr_ = take(other.ptr_); }
void* ptr() const noexcept { return ptr_; }
};
template <size_t N>
class small_buffer_storage // NOLINT(cppcoreguidelines-pro-type-member-init)
{
private:
void* ptr_ = nullptr;
alignas(std::max_align_t) char buffer_[N];
public:
static constexpr size_t buffer_size = N;
small_buffer_storage() = default; // NOLINT(cppcoreguidelines-pro-type-member-init)
template <typename T, typename... Ts>
void emplace(Ts&&... args)
{
if constexpr (!stack_storable<T, N>)
{
ptr_ = aligned_alloc_for<T>();
try { new(ptr_) T(std::forward<Ts>(args)...); }
catch (...)
{
aligned_free_for<T>(ptr_);
throw;
}
}
else
{
new(buffer_) T(std::forward<Ts>(args)...);
ptr_ = buffer_;
}
}
void copy(const small_buffer_storage& other, const copy_ctor_t ctor) { ptr_ = ctor(buffer_, other.ptr_); }
void move(small_buffer_storage&& other, const move_ctor_t ctor) noexcept
{
if (ctor)
{
ctor(buffer_, other.ptr_);
ptr_ = buffer_;
}
else
ptr_ = take(other.ptr_);
}
void* ptr() const noexcept { return ptr_; }
};
template <size_t N>
class stack_only_storage // NOLINT(cppcoreguidelines-pro-type-member-init)
{
private:
alignas(std::max_align_t) char buffer_[N];
public:
static constexpr size_t buffer_size = N;
stack_only_storage() = default;
template <typename T, typename... Ts>
void emplace(Ts&&... args) { new(buffer_) T(std::forward<Ts>(args)...); }
void copy(const stack_only_storage& other, const copy_ctor_t ctor) { (void)ctor(buffer_, other.buffer_); }
void move(stack_only_storage&& other, const move_ctor_t ctor) noexcept { ctor(buffer_, other.buffer_); }
void* ptr() noexcept { return buffer_; }
const void* ptr() const noexcept { return buffer_; }
};
// @formatter:off
template <typename, template <size_t> typename>
struct sized_template : std::false_type { static constexpr size_t size = 0; };
template <size_t S, template <size_t> typename T>
struct sized_template<T<S>, T> : std::true_type { static constexpr size_t size = S; };
// @formatter:on
template <template <size_t> typename Templ, te::policy... Ps>
constexpr size_t get_policy_size() noexcept { return (sized_template<Ps, Templ>::size + ... + 0); }
template <te::policy... Ps>
constexpr auto get_storage_type() noexcept
{
constexpr size_t small_buffer_count =
(static_cast<size_t>(sized_template<Ps, te::small_buffer>::value) + ... + 0);
constexpr size_t stack_only_count =
(static_cast<size_t>(sized_template<Ps, te::stack_only>::value) + ... + 0);
if constexpr (small_buffer_count + stack_only_count == 0)
return meta::type_tag<heap_storage>{};
else
{
static_assert(small_buffer_count + stack_only_count == 1,
"At most one of small_buffer or stack_only policy can be specified");
if constexpr (small_buffer_count > 0)
return meta::type_tag<small_buffer_storage<get_policy_size<te::small_buffer, Ps...>()>>{};
else // small_buffer_count > 0
return meta::type_tag<stack_only_storage<get_policy_size<te::stack_only, Ps...>()>>{};
}
}
template <te::policy... Ps>
using storage_type = typename decltype(get_storage_type<Ps...>())::type;
template <typename Model, te::policy... Policies>
class dispatch_base
{
protected:
static constexpr bool copyable =
(std::is_same_v<Policies, te::copyable> || ...);
using storage_t = storage_type<Policies...>;
static constexpr size_t buffer_size = storage_t::buffer_size;
using vtable_t = vtable<Model, copyable>;
void reset() noexcept
{
if (vtable_) vtable_->dtor(storage_.ptr());
vtable_ = nullptr;
}
storage_t storage_;
const vtable_t* vtable_ = nullptr;
template <typename T, typename... Ts>
void emplace_no_reset(Ts&&... args)
{
storage_.template emplace<T>(std::forward<Ts>(args)...);
vtable_ = &vtable_for<vtable_t, T, buffer_size>;
}
public:
dispatch_base() noexcept = default; // NOLINT(cppcoreguidelines-pro-type-member-init)
dispatch_base(const dispatch_base&) = delete;
dispatch_base& operator=(const dispatch_base&) = delete;
dispatch_base(const dispatch_base& other) requires copyable
{
if (!other.vtable_) return;
storage_.copy(other.storage_, other.vtable_->copy_ctor);
vtable_ = other.vtable_;
}
dispatch_base& operator=(const dispatch_base& other) requires copyable
{
if (&other != this)
{
reset();
if (!other.vtable_) return *this;
storage_.copy(other.storage_, other.vtable_->copy_ctor);
vtable_ = other.vtable_;
}
return *this;
}
~dispatch_base() noexcept { reset(); }
dispatch_base(dispatch_base&& other) noexcept
{
if (!other.vtable_) return;
storage_.move(std::move(other.storage_), other.vtable_->move_ctor);
vtable_ = take(other.vtable_);
}
dispatch_base& operator=(dispatch_base&& other) noexcept
{
if (&other != this)
{
reset();
if (!other.vtable_) return *this;
storage_.move(std::move(other.storage_), other.vtable_->move_ctor);
vtable_ = take(other.vtable_);
}
return *this;
}
template <size_t I, typename This, typename... Ts>
friend decltype(auto) vdispatch_impl(This&& this_, Ts&&... args); // NOLINT
};
template <size_t I, typename This, typename... Ts>
decltype(auto) vdispatch_impl(This&& this_, Ts&&... args)
{
return get<I>(this_.vtable_->vfptrs)(
this_.storage_.ptr(), std::forward<Ts>(args)...);
}
}
template <size_t I, typename Interface, typename... Ts>
decltype(auto) vdispatch(Interface&& inter, Ts&&... args)
{
if constexpr (!std::is_base_of_v<meta::empty_type_list, std::remove_cvref_t<Interface>>)
return detail::vdispatch_impl<I>(
std::forward<Interface>(inter), std::forward<Ts>(args)...);
else
return detail::omnipotype{};
}
template <typename Model, te::policy... Policies>
class type_erased : public Model::template interface<detail::dispatch_base<Model, Policies...>>
{
static_assert(detail::implements_model<detail::prototype<Model>, Model>,
"Interface of the model type should implement the specified members");
private:
using indirect_base = detail::dispatch_base<Model, Policies...>;
using base = typename Model::template interface<indirect_base>;
using vtable_t = typename indirect_base::vtable_t;
static constexpr bool nullable =
(std::is_same_v<Policies, te::nullable> || ...);
static constexpr bool copyable = indirect_base::copyable;
static constexpr bool stack_only = detail::sized_template<
typename indirect_base::storage_t, detail::stack_only_storage>::value;
template <typename T>
static constexpr bool is_impl_type =
detail::implements_model<T, Model> &&
(!copyable || std::is_copy_constructible_v<T>) &&
!forwarding<T, type_erased> &&
(!stack_only || detail::stack_storable<T, indirect_base::buffer_size>);
template <typename T>
static constexpr const auto* vtptr_for() { return &detail::vtable_for<vtable_t, T, indirect_base::buffer_size>; }
template <typename T>
bool compare_vtable() const noexcept { return indirect_base::vtable_ == vtptr_for<T>(); }
public:
type_erased() = delete;
type_erased() noexcept requires nullable = default;
// @formatter:off
template <typename T, typename... Ts> requires (is_impl_type<T> && no_cvref_v<T>)
explicit type_erased(std::in_place_type_t<T>, Ts&&... args)
{
indirect_base::template emplace_no_reset<T>(
std::forward<Ts>(args)...);
}
// @formatter:on
template <typename T> requires is_impl_type<std::remove_cvref_t<T>>
explicit(false) type_erased(T&& value)
{
indirect_base::template
emplace_no_reset<std::remove_cvref_t<T>>(std::forward<T>(value));
}
void reset() noexcept requires nullable { indirect_base::reset(); }
template <typename T, typename... Ts> requires (is_impl_type<T> && no_cvref_v<T>)
void emplace(Ts&&... args)
{
indirect_base::reset();
indirect_base::template emplace_no_reset<T>(std::forward<Ts>(args)...);
}
template <typename T>
[[nodiscard]] T& as()
{
if (auto* ptr = as_ptr<T>()) return *ptr;
throw std::bad_cast();
}
template <typename T>
[[nodiscard]] const T& as() const
{
if (const auto* ptr = as_ptr<T>()) return *ptr;
throw std::bad_cast();
}
template <typename T> requires (is_impl_type<T> && no_cvref_v<T>)
[[nodiscard]] T* as_ptr() noexcept
{
return compare_vtable<T>()
? static_cast<T*>(indirect_base::storage_.ptr())
: nullptr;
}
template <typename T> requires (is_impl_type<T> && no_cvref_v<T>)
[[nodiscard]] const T* as_ptr() const noexcept
{
return compare_vtable<T>()
? static_cast<const T*>(indirect_base::storage_.ptr())
: nullptr;
}
[[nodiscard]] bool empty() const noexcept { return indirect_base::vtable_ != nullptr; }
[[nodiscard]] explicit operator bool() const noexcept { return indirect_base::vtable_ != nullptr; }
[[nodiscard]] bool operator==(std::nullptr_t) const noexcept { return indirect_base::vtable_ == nullptr; }
};
}
|
cef023adc3f588a42c13e9ba255ccd09c49c8cab | e99416680ccd308d39a3e679d609d46b1ad42514 | /cpp/string2/string.h | dc860c39a91b29e495d0eaad3c04de0209487d37 | [] | no_license | lim1992kr/ForStudy | 123295b80196d294dab615c598ce04870c567798 | 77d2810607ada140df733ddce42e4315faaa5dfb | refs/heads/master | 2022-12-12T19:49:36.979941 | 2020-09-08T04:47:25 | 2020-09-08T04:47:25 | 276,047,088 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,051 | h | string.h | #ifndef STRING_H
#define STRING_H
#include "stringRep.h"
#include <iostream>
class String {
friend std::ostream& operator << (std::ostream& out, const String& rhs);
//맴버함수 아니고 전역함수다.
private:
//char *str;
//int len;
StringRep *ptr_;
/*
StringRep *ptr_; 을 호출하면 아래 세개가 호출된다.
char *str_;
int len_;
int rc_; //참조 계수 reference counting
*/
//void set_str(const char *str); // helper func. tool func.
String(const char *str, bool); //bool은 의미없는 인자.
public:
//String();
String(const char *str = 0); //String s1이 맴버함수를 호출한다. 디폴트 값은 0
String(const String& rhs);
~String();
String& operator=(const String& rhs);
//오퍼레이트= 연산은 이렇게 생김 데이지 체인연산을하려면 필요하다.,결과값이 s1
String& operator=(const char *str);
bool operator==(const String& rhs) const;
const String operator+(const String& rhs) const;
const char *c_str() const;
int length() const;
//
};
#endif
|
fe1f94bd0e7a3305542ddbe0b8baa306ebf1d574 | 59e51f6466c7232f9d235e32b15a421b37bfb772 | /Graph store/Traits/Traits.h | 9e961ebca8e345677950a3540e01d354a5451561 | [] | no_license | IDragnev/Graph-store | 125fe050d5081b4a85430cad88f1b79ce419a6f3 | e435064a63e84c12b16d37b66a13b7799644f5ba | refs/heads/master | 2021-03-27T20:41:13.824270 | 2019-07-28T16:22:07 | 2019-07-28T16:22:07 | 122,102,047 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,276 | h | Traits.h | #ifndef __TRAITS_H_INCLUDED__
#define __TRAITS_H_INCLUDED__
#include <type_traits>
#include <iterator>
namespace IDragnev::Traits
{
namespace Detail
{
template <typename Iterator>
using IteratorCategory = typename std::iterator_traits<Iterator>::iterator_category;
template <typename Iterator>
using IteratorReference = typename std::iterator_traits<Iterator>::reference;
}
template <typename T, typename = std::void_t<>>
struct IsIterator : std::false_type { };
template <typename T>
struct IsIterator<T, std::void_t<Detail::IteratorCategory<T>>> : std::true_type { };
template <typename T>
inline constexpr bool isIterator = IsIterator<T>::value;
template <typename T>
struct IsConstReference : std::is_const<std::remove_reference_t<T>> { };
template <typename T>
inline constexpr bool isConstReference = IsConstReference<T>::value;
template <typename Iterator, bool = isIterator<Iterator>>
struct IsConstIterator : IsConstReference<Detail::IteratorReference<Iterator>> { };
template <typename Iterator>
struct IsConstIterator<Iterator, false> : std::false_type { };
template <typename Iterator>
inline constexpr bool isConstIterator = IsConstIterator<Iterator>::value;
template <typename Iterator, bool = isIterator<Iterator>>
struct IsForwardIterator : std::is_convertible<Detail::IteratorCategory<Iterator>, std::forward_iterator_tag> { };
template <typename Iterator>
struct IsForwardIterator<Iterator, false> : std::false_type { };
template <typename Iterator>
inline constexpr bool isForwardIterator = IsForwardIterator<Iterator>::value;
template <typename Iterator, bool = isIterator<Iterator>>
struct IsInputIterator : std::is_convertible<Detail::IteratorCategory<Iterator>, std::input_iterator_tag> { };
template <typename Iterator>
struct IsInputIterator<Iterator, false> : std::false_type { };
template <typename Iterator>
inline constexpr bool isInputIterator = IsInputIterator<Iterator>::value;
template <template <typename...> typename Predicate, typename... Ts>
struct AllOf : std::bool_constant<(Predicate<Ts>::value && ...)> { };
template <template <typename...> typename Predicate, typename... Ts>
inline constexpr bool allOf = AllOf<Predicate, Ts...>::value;
}
#endif //__TRAITS_H_INCLUDED__ |
657d8f552901aff4e0c8c54651bee97a008f5a13 | 7eca32bc2f32d8deee9a07e027cba753c3bc440a | /Arduino/PinenerdDerby/PinenerdDerby.ino | c751ab8e3390897216d6924012c4a51fa39354bc | [] | no_license | joshing/pinenerd-derby | e11bde289fac2df4f1a7e2d8990b8349af5845ce | bbdd394aa9b76ae884e4cc104d1c154554e04dfc | refs/heads/master | 2020-06-07T12:34:38.237563 | 2015-05-19T18:29:49 | 2015-05-19T18:29:49 | 35,890,287 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,386 | ino | PinenerdDerby.ino | /*
Copyright (c) 2015 Josh Gunnar
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 <Wire.h>
#include <Adafruit_MCP23017.h>
#include <Adafruit_RGBLCDShield.h>
#include <Servo.h>
#include "HardwareConfig.h"
#define WHITE 0x7 // For the LCD
Servo myservo;
Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();
uint8_t buttons;
void setup()
{
// Setup IR pins
pinMode(IR_OUTPUT_PIN, OUTPUT);
pinMode(IR_INPUT_PIN, INPUT);
// Setup servo acting as the starting gate
myservo.attach(SERVO_PIN);
myservo.write(0);
delay(2000); // Can't call detach() before movement is finished
myservo.detach(); // If left attached, the servo will 'twitch'
// Setup the LCD
lcd.begin(16, 2);
lcd.setBacklight(WHITE);
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("READY");
}
void loop() {
// Basically, just wait for a race to start, signaled by the 'select' button
buttons = lcd.readButtons();
if (buttons) {
if (buttons & BUTTON_SELECT) {
race();
}
}
}
void race() {
// Error flag
boolean error = false;
// Update display
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Race!");
// Turn on the IR beam
digitalWrite(IR_OUTPUT_PIN, HIGH);
// Lower the gate
myservo.attach(SERVO_PIN);
myservo.write(GO_SERVO_POSITION);
// Note the start time
long start = millis();
// Wait until the IR beam at the finish is broken
while (analogRead(IR_INPUT_PIN) < IR_ANALOG_THRESHOLD) {
// It's possible that the IR beam fails to register the finish..
// so provide an out by checking for the left (back) button
buttons = lcd.readButtons();
if (buttons) {
if (buttons & BUTTON_LEFT) {
error = true;
break;
}
}
}
if (!error) {
// Figure out elapsed time in seconds
long time = millis() - start;
float timeSeconds = (float)time/1000;
// Show the result
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Time: ");
lcd.print(timeSeconds, 3);
lcd.print("s");
}
else {
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Ready");
}
// Clean up, set the starting gate back up and turn off
// the IR beam
myservo.write(STOP_SERVO_POSITION);
delay(2000); // Can't detach until the movement is finished
myservo.detach();
digitalWrite(IR_OUTPUT_PIN, LOW);
}
|
74e277e85266473d548e00eaea8f66f118e36eec | 542ac9465b7683ae7c649e739b47a320b8094f05 | /cpp/degree.h | 5d99c74b8dea12bf4d3e2ab4af753163105e46e3 | [] | no_license | ZenoTan/mini_pbg | 4f75a9315d3a33a430a2458741f9d32f422329be | cd337ae8432a0b535c2fb2aed09d99eec8f26499 | refs/heads/master | 2020-06-29T17:03:16.935633 | 2019-09-02T09:43:28 | 2019-09-02T09:43:28 | 200,572,652 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 874 | h | degree.h | #ifndef DEGREE_H
#define DEGREE_H
#include <vector>
#include <string>
#include <fstream>
using namespace std;
namespace degree {
class DegreeBucket {
public:
DegreeBucket(int N, int E): num_node(N), num_edge(E) {
count_in.resize(N);
count_out.resize(N);
count_all.resize(N);
}
void Process(const string &file_name) {
ProcessFile(file_name);
ProcessResult();
}
vector<int> GetInDegree() {
return degree_in;
}
vector<int> GetOutDegree() {
return degree_out;
}
vector<int> GetAllDegree() {
return degree_all;
}
private:
const int num_node;
const int num_edge;
vector<int> degree_in;
vector<int> degree_out;
vector<int> count_in;
vector<int> count_out;
vector<int> degree_all;
vector<int> count_all;
void ProcessFile(const string &file_name);
void ProcessResult();
void BucketSort(vector<int> &count, vector<int> °ree);
};
}
#endif
|
f6ed88865684d30def7ca250dadf1cd4af2dbf15 | 2b0b07242be5ea756aba992e171b43fbee9bfada | /BOJ/1647/1647.cpp | f44c238d1d057f2290e799721c194f387d313c96 | [] | no_license | newdaytrue/PS | 28f138a5e8fd4024836ea7c2b6ce59bea91dbad7 | afffef30fcb59f6abfee2d5b8f00a304e8d80c91 | refs/heads/master | 2020-03-22T13:01:46.555651 | 2018-02-13T18:25:34 | 2018-02-13T18:25:34 | 140,078,090 | 1 | 0 | null | 2018-07-07T11:21:44 | 2018-07-07T11:21:44 | null | UTF-8 | C++ | false | false | 1,150 | cpp | 1647.cpp | // =====================================================================================
//
// Filename: 1647.cpp
// Created: 2017년 04월 29일 13시 41분 04초
// Compiler: g++ -O2 -std=c++14
// Author: baactree , bsj0206@naver.com
// Company: Chonnam National University
//
// =====================================================================================
#include <bits/stdc++.h>
using namespace std;
int n, m;
vector<pair<int, pair<int, int> > > edge;
int par[100005];
int find(int x){
if(par[x]==x)
return x;
return par[x]=find(par[x]);
}
void merge(int x, int y){
x=find(x);
y=find(y);
par[y]=x;
}
int main(){
scanf("%d%d", &n, &m);
for(int i=0;i<m;i++){
int a, b, d;
scanf("%d%d%d", &a, &b, &d);
edge.push_back({d, {a, b}});
}
for(int i=1;i<=n;i++)
par[i]=i;
sort(edge.begin(), edge.end());
int cnt=0;
long long ans=0;
for(int i=0;i<edge.size();i++){
if(cnt==n-2)
break;
int u=edge[i].second.first;
int v=edge[i].second.second;
int w=edge[i].first;
if(find(u)!=find(v)){
cnt++;
merge(u, v);
ans+=w;
}
}
printf("%lld\n", ans);
return 0;
}
|
b47d26d27630eb7e001ea975c34a7cbbff7a95e1 | f5fea98d29872099558d33631bbb0974016ee08e | /include/Menu.hpp | ff986fa20cb8d3738de89def2a5fbe72af708173 | [] | no_license | EsSamdel/superLoloBross | 30ca7768296ab2204a772ac86264e6df35794442 | 75bae9d97e76223f189a9748a262cf765baebf72 | refs/heads/master | 2020-04-27T23:20:37.900162 | 2017-04-04T12:11:27 | 2017-04-04T12:11:27 | 17,454,798 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 324 | hpp | Menu.hpp | /*
* Menu.hpp
*
* Created on: 6 mars 2014
* Author: simon
*/
#ifndef MENU_HPP_
#define MENU_HPP_
#include "Common.hpp"
class Menu {
public:
Menu(const char * fileName);
virtual ~Menu();
void display(SDL_Surface* screen);
private:
SDL_Surface * _image;
SDL_Rect _menuPos;
};
#endif /* MENU_HPP_ */
|
80cecce2ce198fe37bdb238fd625bba55c58198f | 25c9f6d13c101dd6c6e8014c0861bc536c133ce0 | /src/utils/Utils.h | 4107ed9d714d167450129f3bc29898b2687a0778 | [
"MIT"
] | permissive | Patbott/Masterkeys | 1970140ff9e035a7e034a750b57e70ddba9a2341 | a4cc07c21faffd5228e16405eb10b8931c86fdfa | refs/heads/master | 2020-03-15T20:40:45.823405 | 2018-05-06T13:03:19 | 2018-05-06T13:03:19 | 132,338,563 | 0 | 0 | null | 2018-05-06T12:58:36 | 2018-05-06T12:58:36 | null | UTF-8 | C++ | false | false | 279 | h | Utils.h | #ifndef MASTERKEYS_UTILS_H
#define MASTERKEYS_UTILS_H
template<typename T, typename U, typename V, typename W>
inline T clamp(U min, V val, W max) {
if (val < min) { return (T) min; }
if (val > max) { return (T) max; }
return (T)val;
};
#endif //MASTERKEYS_UTILS_H
|
0a6568aba3af150b6301213ccbbc17d85a20149a | b2b9e4d616a6d1909f845e15b6eaa878faa9605a | /C++/1.cpp | 61447d5af78d10cf06942686cc5bcbd91a690737 | [] | no_license | JinbaoWeb/ACM | db2a852816d2f4e395086b2b7f2fdebbb4b56837 | 021b0c8d9c96c1bc6e10374ea98d0706d7b509e1 | refs/heads/master | 2021-01-18T22:32:50.894840 | 2016-06-14T07:07:51 | 2016-06-14T07:07:51 | 55,882,694 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 208 | cpp | 1.cpp | #include <iostream>
using namespace std;
int gcd(long long a,long long b){
if (b==0)
return a;
return gcd(b,a%b);
}
int main(){
long long a,b;
while (cin>>a>>b){
cout<<gcd(a,b)<<endl;
}
return 0;
}
|
105fb79c1f5e387b7646020b78cf2e2eb6f51122 | 20d4f5c63fe27fe4eea9e6e4e318e63928f517ec | /thrill/api/write_lines_one.hpp | eab6c0c9035d386015f90140b3a604e4139bbc26 | [
"BSD-2-Clause"
] | permissive | TiFu/thrill-hyperloglog | 13101b70ae23667940c2bf277ecbc3ea5f9a331e | bac13cd4ba23ec4bf6fe2e32ffa79d68c348cbcf | refs/heads/master | 2020-04-02T13:28:28.679216 | 2017-01-09T21:29:56 | 2017-05-10T13:56:15 | 154,482,700 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,250 | hpp | write_lines_one.hpp | /*******************************************************************************
* thrill/api/write_lines_one.hpp
*
* Part of Project Thrill - http://project-thrill.org
*
* Copyright (C) 2015 Matthias Stumpp <mstumpp@gmail.com>
* Copyright (C) 2015 Timo Bingmann <tb@panthema.net>
* Copyright (C) 2015 Alexander Noe <aleexnoe@gmail.com>
*
* All rights reserved. Published under the BSD-2 license in the LICENSE file.
******************************************************************************/
#pragma once
#ifndef THRILL_API_WRITE_LINES_ONE_HEADER
#define THRILL_API_WRITE_LINES_ONE_HEADER
#include <thrill/api/action_node.hpp>
#include <thrill/api/dia.hpp>
#include <thrill/data/file.hpp>
#include <fstream>
#include <string>
namespace thrill {
namespace api {
/*!
* \ingroup api_layer
*/
template <typename ValueType>
class WriteLinesOneNode final : public ActionNode
{
static constexpr bool debug = false;
public:
using Super = ActionNode;
using Super::context_;
template <typename ParentDIA>
WriteLinesOneNode(const ParentDIA& parent,
const std::string& path_out)
: ActionNode(parent.ctx(), "WriteLinesOne",
{ parent.id() }, { parent.node() }),
path_out_(path_out),
file_(path_out_, std::ios::binary)
{
sLOG << "Creating write node.";
auto pre_op_fn = [this](const ValueType& input) {
PreOp(input);
};
// close the function stack with our pre op and register it at parent
// node for output
auto lop_chain = parent.stack().push(pre_op_fn).fold();
parent.node()->AddChild(this, lop_chain);
}
void PreOp(const ValueType& input) {
writer_.Put(input);
local_size_ += input.size() + 1;
local_lines_++;
}
void StopPreOp(size_t /* id */) final {
writer_.Close();
}
//! Closes the output file
void Execute() final {
Super::logger_
<< "class" << "WriteLinesOneNode"
<< "total_bytes" << local_size_
<< "total_lines" << local_lines_;
// (Portable) allocation of output file, setting individual file pointers.
size_t prefix_elem = context_.net.ExPrefixSum(local_size_);
if (context_.my_rank() == context_.num_workers() - 1) {
file_.seekp(prefix_elem + local_size_ - 1);
file_.put('\0');
}
file_.seekp(prefix_elem);
context_.net.Barrier();
data::File::ConsumeReader reader = temp_file_.GetConsumeReader();
for (size_t i = 0; i < temp_file_.num_items(); ++i) {
file_ << reader.Next<ValueType>() << "\n";
}
}
private:
//! Path of the output file.
std::string path_out_;
//! File to write to
std::ofstream file_;
//! Local file size
size_t local_size_ = 0;
//! Temporary File for splitting correctly?
data::File temp_file_ { context_.GetFile(this) };
//! File writer used.
data::File::Writer writer_ { temp_file_.GetWriter() };
size_t local_lines_ = 0;
};
template <typename ValueType, typename Stack>
void DIA<ValueType, Stack>::WriteLinesOne(
const std::string& filepath) const {
assert(IsValid());
static_assert(std::is_same<ValueType, std::string>::value,
"WriteLinesOne needs an std::string as input parameter");
using WriteLinesOneNode = api::WriteLinesOneNode<ValueType>;
auto node = common::MakeCounting<WriteLinesOneNode>(*this, filepath);
node->RunScope();
}
template <typename ValueType, typename Stack>
Future<void> DIA<ValueType, Stack>::WriteLinesOneFuture(
const std::string& filepath) const {
assert(IsValid());
static_assert(std::is_same<ValueType, std::string>::value,
"WriteLinesOne needs an std::string as input parameter");
using WriteLinesOneNode = api::WriteLinesOneNode<ValueType>;
auto node = common::MakeCounting<WriteLinesOneNode>(*this, filepath);
return Future<void>(node);
}
} // namespace api
} // namespace thrill
#endif // !THRILL_API_WRITE_LINES_ONE_HEADER
/******************************************************************************/
|
8f5e1581257c1678a75059b9c640da1781d37f5a | 73c8a3179b944b63b2a798542896e4cdf0937b6e | /Notebook/src/DP - Subset Sum.cpp | fed25bc2608b0821d9ebc3dbefcd70f9cf99dc52 | [
"Apache-2.0"
] | permissive | aajjbb/contest-files | c151f1ab9b562ca91d2f8f4070cb0aac126a188d | 71de602a798b598b0365c570dd5db539fecf5b8c | refs/heads/master | 2023-07-23T19:34:12.565296 | 2023-07-16T00:57:55 | 2023-07-16T00:57:59 | 52,963,297 | 2 | 4 | null | 2017-08-03T20:12:19 | 2016-03-02T13:05:25 | C++ | UTF-8 | C++ | false | false | 377 | cpp | DP - Subset Sum.cpp | //Subset-Sum -> (G = O valor total sendo testado, N = numero de valores disponiveis no array 'values'
int values[n];
bool subsetSum(int n, int g) {
for(j = 0; j <= g; j++) sub[j] = 0;
sub[0] = 1;
for(j = 0; j < n; j++) if(values[j] != g) {
for(int k = g; k >= values[j]; k--) {
sub[k] |= sub[k - values[j]];
}
}
return sub[g];
}
|
7f313617cca4871d0fa8affdbe291c5c3eb63be9 | a669cbf67299dd54e89562e45927a2f5148d97ab | /vr/shapes/implicitshape.cpp | 95756bd6bd2e3a59375b2d3fbe035ce825032867 | [] | no_license | nicsteinberg/cs123-final | e3713311b8cc4342fce1f1af3bf84f9f3b0e9623 | a11800424956ddfbbf1abe50b7cb77e892643c58 | refs/heads/master | 2020-04-10T10:39:50.441516 | 2018-12-15T21:50:48 | 2018-12-15T21:50:48 | 160,972,525 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 407 | cpp | implicitshape.cpp | #include "implicitshape.h"
// Parent class for all implicit shapes for ray. Each has functionality
// for intersection t values and normals at given intersections.
ImplicitShape::ImplicitShape()
{
}
glm::vec4 ImplicitShape::getNormal(glm::vec4 p, glm::vec4 d, float t) {
return glm::vec4();
}
glm::vec2 ImplicitShape::getTextureCoords(glm::vec4 p, glm::vec4 d, float t) {
return glm::vec2();
}
|
4e6d3739f404b4b3317519d88927c951c6abc0e8 | f2f17f11433e732777c031a8b2af85cc809140d9 | /shared/test/unit_test/gen12lp/test_command_encoder_gen12lp.cpp | 7605e916b5d119e5b8af94271cfaa7d35ceceb2a | [
"MIT"
] | permissive | ConnectionMaster/compute-runtime | 675787c428de81abe96c969ecadd59a13150d3a2 | 1f6c09ba1d6ca19cd17f875c76936d194cc53885 | refs/heads/master | 2023-09-01T04:05:47.747499 | 2022-09-08T11:12:08 | 2022-09-09T09:50:09 | 183,522,897 | 1 | 0 | NOASSERTION | 2023-04-03T23:16:44 | 2019-04-25T23:20:50 | C++ | UTF-8 | C++ | false | false | 6,799 | cpp | test_command_encoder_gen12lp.cpp | /*
* Copyright (C) 2020-2022 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "shared/source/command_container/cmdcontainer.h"
#include "shared/source/command_container/command_encoder.h"
#include "shared/source/gmm_helper/gmm_helper.h"
#include "shared/source/helpers/preamble.h"
#include "shared/source/os_interface/os_context.h"
#include "shared/test/common/cmd_parse/gen_cmd_parse.h"
#include "shared/test/common/fixtures/device_fixture.h"
#include "shared/test/common/test_macros/hw_test.h"
#include "shared/test/unit_test/fixtures/command_container_fixture.h"
#include "reg_configs_common.h"
using namespace NEO;
using CommandEncoderTest = Test<DeviceFixture>;
using CommandEncodeStatesTest = Test<CommandEncodeStatesFixture>;
GEN12LPTEST_F(CommandEncoderTest, WhenAdjustComputeModeIsCalledThenStateComputeModeShowsNonCoherencySet) {
using STATE_COMPUTE_MODE = typename FamilyType::STATE_COMPUTE_MODE;
using FORCE_NON_COHERENT = typename STATE_COMPUTE_MODE::FORCE_NON_COHERENT;
CommandContainer cmdContainer;
auto ret = cmdContainer.initialize(pDevice, nullptr, true);
ASSERT_EQ(CommandContainer::ErrorCode::SUCCESS, ret);
auto usedSpaceBefore = cmdContainer.getCommandStream()->getUsed();
// Adjust the State Compute Mode which sets FORCE_NON_COHERENT_FORCE_GPU_NON_COHERENT
StreamProperties properties{};
properties.stateComputeMode.setProperties(false, GrfConfig::DefaultGrfNumber, 0, PreemptionMode::Disabled, *defaultHwInfo);
NEO::EncodeComputeMode<FamilyType>::programComputeModeCommand(*cmdContainer.getCommandStream(),
properties.stateComputeMode, *defaultHwInfo, nullptr);
auto usedSpaceAfter = cmdContainer.getCommandStream()->getUsed();
ASSERT_GT(usedSpaceAfter, usedSpaceBefore);
auto expectedCmdSize = sizeof(STATE_COMPUTE_MODE);
auto cmdAddedSize = usedSpaceAfter - usedSpaceBefore;
EXPECT_EQ(expectedCmdSize, cmdAddedSize);
auto expectedScmCmd = FamilyType::cmdInitStateComputeMode;
expectedScmCmd.setForceNonCoherent(FORCE_NON_COHERENT::FORCE_NON_COHERENT_FORCE_GPU_NON_COHERENT);
expectedScmCmd.setMaskBits(FamilyType::stateComputeModeForceNonCoherentMask);
auto scmCmd = reinterpret_cast<STATE_COMPUTE_MODE *>(ptrOffset(cmdContainer.getCommandStream()->getCpuBase(), usedSpaceBefore));
EXPECT_TRUE(memcmp(&expectedScmCmd, scmCmd, sizeof(STATE_COMPUTE_MODE)) == 0);
}
GEN12LPTEST_F(CommandEncoderTest, givenCommandContainerWhenEncodeL3StateThenDoNotDispatchMMIOCommand) {
CommandContainer cmdContainer;
cmdContainer.initialize(pDevice, nullptr, true);
EncodeL3State<FamilyType>::encode(cmdContainer, false);
GenCmdList commands;
CmdParse<FamilyType>::parseCommandBuffer(commands, ptrOffset(cmdContainer.getCommandStream()->getCpuBase(), 0), cmdContainer.getCommandStream()->getUsed());
using MI_LOAD_REGISTER_IMM = typename FamilyType::MI_LOAD_REGISTER_IMM;
auto itorLRI = find<MI_LOAD_REGISTER_IMM *>(commands.begin(), commands.end());
EXPECT_EQ(itorLRI, commands.end());
}
struct MockOsContext : public OsContext {
using OsContext::engineType;
};
GEN12LPTEST_F(CommandEncodeStatesTest, givenVariousEngineTypesWhenEncodeSbaThenAdditionalPipelineSelectWAIsAppliedOnlyToRcs) {
using PIPELINE_SELECT = typename FamilyType::PIPELINE_SELECT;
using STATE_COMPUTE_MODE = typename FamilyType::STATE_COMPUTE_MODE;
using STATE_BASE_ADDRESS = typename FamilyType::STATE_BASE_ADDRESS;
CommandContainer cmdContainer;
auto ret = cmdContainer.initialize(pDevice, nullptr, true);
ASSERT_EQ(CommandContainer::ErrorCode::SUCCESS, ret);
auto gmmHelper = cmdContainer.getDevice()->getRootDeviceEnvironment().getGmmHelper();
uint32_t statelessMocsIndex = (gmmHelper->getMOCS(GMM_RESOURCE_USAGE_OCL_BUFFER) >> 1);
{
STATE_BASE_ADDRESS sba;
EncodeStateBaseAddressArgs<FamilyType> args = createDefaultEncodeStateBaseAddressArgs<FamilyType>(&cmdContainer, sba, statelessMocsIndex);
args.isRcs = true;
EncodeStateBaseAddress<FamilyType>::encode(args);
GenCmdList commands;
CmdParse<FamilyType>::parseCommandBuffer(commands, ptrOffset(cmdContainer.getCommandStream()->getCpuBase(), 0), cmdContainer.getCommandStream()->getUsed());
auto itorLRI = find<PIPELINE_SELECT *>(commands.begin(), commands.end());
if (HwInfoConfig::get(defaultHwInfo->platform.eProductFamily)->is3DPipelineSelectWARequired()) {
EXPECT_NE(itorLRI, commands.end());
} else {
EXPECT_EQ(itorLRI, commands.end());
}
}
cmdContainer.reset();
{
STATE_BASE_ADDRESS sba;
EncodeStateBaseAddressArgs<FamilyType> args = createDefaultEncodeStateBaseAddressArgs<FamilyType>(&cmdContainer, sba, statelessMocsIndex);
args.isRcs = false;
EncodeStateBaseAddress<FamilyType>::encode(args);
GenCmdList commands;
CmdParse<FamilyType>::parseCommandBuffer(commands, ptrOffset(cmdContainer.getCommandStream()->getCpuBase(), 0), cmdContainer.getCommandStream()->getUsed());
auto itorLRI = find<PIPELINE_SELECT *>(commands.begin(), commands.end());
EXPECT_EQ(itorLRI, commands.end());
}
}
GEN12LPTEST_F(CommandEncoderTest, GivenGen12LpWhenProgrammingL3StateOnThenExpectNoCommandsDispatched) {
using MI_LOAD_REGISTER_IMM = typename FamilyType::MI_LOAD_REGISTER_IMM;
CommandContainer cmdContainer;
cmdContainer.initialize(pDevice, nullptr, true);
EncodeL3State<FamilyType>::encode(cmdContainer, true);
GenCmdList commands;
CmdParse<FamilyType>::parseCommandBuffer(commands, ptrOffset(cmdContainer.getCommandStream()->getCpuBase(), 0), cmdContainer.getCommandStream()->getUsed());
auto itorLRI = find<MI_LOAD_REGISTER_IMM *>(commands.begin(), commands.end());
EXPECT_EQ(itorLRI, commands.end());
}
GEN12LPTEST_F(CommandEncoderTest, GivenGen12LpWhenProgrammingL3StateOffThenExpectNoCommandsDispatched) {
using MI_LOAD_REGISTER_IMM = typename FamilyType::MI_LOAD_REGISTER_IMM;
CommandContainer cmdContainer;
cmdContainer.initialize(pDevice, nullptr, true);
EncodeL3State<FamilyType>::encode(cmdContainer, false);
GenCmdList commands;
CmdParse<FamilyType>::parseCommandBuffer(commands, ptrOffset(cmdContainer.getCommandStream()->getCpuBase(), 0), cmdContainer.getCommandStream()->getUsed());
auto itorLRI = find<MI_LOAD_REGISTER_IMM *>(commands.begin(), commands.end());
EXPECT_EQ(itorLRI, commands.end());
}
using Gen12lpCommandEncodeTest = testing::Test;
GEN12LPTEST_F(Gen12lpCommandEncodeTest, givenBcsCommandsHelperWhenMiArbCheckWaRequiredThenReturnTrue) {
EXPECT_FALSE(BlitCommandsHelper<FamilyType>::miArbCheckWaRequired());
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.