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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
e543eb4661f562d5296585029e326d07685a4017 | 7ed1ec5fa6cb4072ef6136a68ef3dcd098967c76 | /Command.cpp | df24c1b14fdb4ef3298728d1fba9094597c63573 | [] | no_license | hamadmarri/ToyShell | 9be91f6fb6f62789ee0e2c59f22fd71b40253683 | d2fd359eb20cd1c497fa97aabe4381651a94fc37 | refs/heads/master | 2020-03-26T12:51:07.431730 | 2018-08-15T22:51:30 | 2018-08-15T22:51:30 | 144,910,575 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 505 | cpp | Command.cpp | /*
* Command.cpp
*
* Created on: 2014-10-08
* Author: hamadmarri
*/
#include "Command.h"
void Command::setCommand(string command) {
if (command.find('$') != string::npos) {
this->commandStr = command.substr(0, command.find('$'));
this->commentStr = command.substr(command.find('$'),
command.length() - 1);
} else {
this->commandStr = command;
}
}
string Command::getCommandString() {
return this->commandStr;
}
string Command::getCommentString() {
return this->commentStr;
}
|
7d5715617cc6573adccbf4c7db7da5c33e11d2a0 | 88ccc31563769d7a71f4617c6cd010ac55d84fcb | /2018 0103 닝겐찾기 알고리즘/ConsoleApplication1/cVector3.h | 22dc1fb67eef97752fd1fd76e7212cf109a0df24 | [] | no_license | Dongeun1206/SGA | ee718f26eb501498b27bf3f79b9f7bf366fb32bf | 6892f5d30317b8e833c6cb97db63e105b1649832 | refs/heads/master | 2021-09-02T22:33:48.322890 | 2018-01-04T00:11:54 | 2018-01-04T00:11:54 | 115,492,529 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 909 | h | cVector3.h | #pragma once
class cVector3
{
public:
float x, y, z;
public:
cVector3();
cVector3(float _x, float _y, float _z);
~cVector3();
cVector3 operator + (CONST cVector3& vec) const;
cVector3 operator - (CONST cVector3& vec) const;
cVector3 operator * (float f) const; //스칼라 곱
bool operator == (CONST cVector3& vec) const;
bool operator != (CONST cVector3& vec) const;
/* 연산자 오버라이딩 구현
+
-
* (스칼라 곱)
==
!=
ex)
cVector3 v1, v2 , v3;
v3 = v1 + v2;
if (v1 == v2) cout << "같다";
*/
// 벡터의 길이(크기)
float Length();
// 벡터의 제곱 길이
float LengthSq();
// 정규화 함수(노멀라이즈)
cVector3 Normalize();
// 내적 (닷 프로덕트)
static float Dot(cVector3& v1, cVector3& v2);
// 외적 (크로스 프로덕트)
static cVector3 Cross(cVector3& v1, cVector3& v2);
// 용책 32 ~ 60 까지 읽기 (매트릭스)
};
|
c2e5df7357b4f0ff02fb513e7a305f0d810e27b8 | 66e24003d641aaf26d0d6d81b9de129de387cc36 | /include/jit/JITExecutionRuntime.h | 0cdb1795e00ad2b63d523161879e4245412da043 | [] | no_license | Emeralddddd/grizzly-prototype | 883716ff5490917a9eea869d8e4d886807a05474 | 2de9c6ec067273bfae9ba826979398cf4009583d | refs/heads/master | 2022-10-28T17:38:22.608890 | 2020-06-13T22:30:45 | 2020-06-13T22:30:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,309 | h | JITExecutionRuntime.h | #ifndef RUNTIME_JIT_H
#define RUNTIME_JIT_H
#include "api/Query.h"
#include "condition_variable"
#include "mutex"
#include "runtime/JitRuntime.h"
#include <jit/runtime/Variant.hpp>
enum PipelineState { DEFAULT, INSTRUMENTED, OPTIMIZED };
class JITExecutionRuntime : JitRuntime {
public:
JITExecutionRuntime();
void deoptimize(Variant *variant, void *buffer, int position);
void execute(Query *query);
bool isRunning();
void monitor(int threadID) override;
private:
Variant *currentlyExecutingVariant;
Variant *defaultVariant;
static void runWorker(JITExecutionRuntime *runtime, int threadID);
void deployDefault();
std::mutex redeploy;
int delay;
Query *query;
GlobalState *globalState;
Dispatcher *dispatcher;
std::atomic<PipelineState> currentState;
int variantNr;
std::string basename;
std::atomic_bool running;
void deployInstrumented();
void deployOptimized();
Variant *compileVariant(Query *query, ProfilingDataManager *profilingDataManager, CompileMode mode);
std::condition_variable compileCondition;
std::condition_variable compilationFinish;
std::mutex compilationMutex;
std::mutex waitMutex;
static void compilationLoop(JITExecutionRuntime *jitExecutionRuntime);
static void monitor(JITExecutionRuntime *jitExecutionRuntime);
};
#endif |
04679f1bde756637f97d199129b276288ea69562 | c4596aefe498dc1912615cd9b9c92c1438135ed5 | /src/Level1.cc | 67c9801b15230767c50b24d784a03ed8ad550f11 | [] | no_license | Meem0/a5 | 3feb22b3ed8b19eef3cb01a4f33d9b83cfa5323f | 13859cae6bab509777e2b3b91b30d2db6fcf1a8a | refs/heads/master | 2020-04-18T08:15:33.545312 | 2014-12-01T01:16:33 | 2014-12-01T01:16:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,156 | cc | Level1.cc | #include "Level1.h"
#include "Score.h"
#include "LateralSquare.h"
#include "UprightSquare.h"
#include "UnstableSquare.h"
#include "PsychSquare.h"
#include <cstdlib>
bool Level1::checkLevelUp() const {
return _score->getScore() >= _startScore + 300;
}
Square* Level1::generateSquare() {
Square* result = NULL;
Pos pos;
Square::Colour colour;
// choose colour
switch (rand() % 6) {
case 0: colour = Square::GREEN; break; // green: 1/6 chance
case 1: colour = Square::BLUE; break; // blue: 1/6 chance
case 2:
case 3: colour = Square::WHITE; break; // white: 1/3 chance
case 4:
case 5: colour = Square::RED; break; // red: 1/3 chance
}
// 1/35 chance of generating a special square
if (rand() % 35 == 0) {
// equal chance for each special square, except PsychSquare
int randNum = rand() % 13;
if (randNum < 4)
result = new LateralSquare(pos, colour);
else if (randNum < 8)
result = new UprightSquare(pos, colour);
else if (randNum < 12)
result = new UnstableSquare(pos, colour);
else if (randNum == 12)
result = new PsychSquare(pos, colour);
}
else {
result = new Square(pos, colour);
}
return result;
}
|
976a6132221a0c45b0f3cb8577044557649ae19d | cea4644f038bab89ad223b4fa03d3da2e565aede | /Euler3D/Solver.h | 0f1fe3160a7b5c507bf771823e10bbe0cac8b224 | [] | no_license | patrick-palmetshofer/Euler3D | ccc736d1c8f32d1d09f136b52396ef55299a94b0 | 4db3c31ed50db38e60cc4c37ac4787fd25e39231 | refs/heads/master | 2022-10-01T05:38:41.512575 | 2020-06-05T07:20:24 | 2020-06-05T07:20:24 | 267,640,519 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,070 | h | Solver.h | #pragma once
#include "GlobalTypes.h"
#include "Grid.h"
#include "TimeStepper.h"
#include "Fluid.h"
#include "Solution.h"
#include "Boundary.h"
#include <memory>
class Solver
{
private:
std::unique_ptr<Grid> grid;
std::unique_ptr<TimeStepper> stepper;
std::unique_ptr<Reconstruct> reconstruct;
std::unique_ptr<Fluid> fluid;
std::unique_ptr<Solution> solution;
std::array<std::unique_ptr<Flux>, 3> fluxes;
std::vector<std::unique_ptr<Boundary>> boundaries;
Eigen::Array<StateTensor *, 3, 1> flux_tensors;
double time_write_interval;
int iter_write_interval;
//Use limiter?
bool limit;
double implicit;
//Maximum CFL number, use 0.5 for sure stability
double maxCFL = 0.1;
double p_infty;
//Time step and current time in simulation
double dt;
double time;
double maxTime;
double maxIter;
//conservative variables for Inlet and initial condition
StateVector cons_inlet;
StateVector cons_initial;
//StateTensor primitive;
//StateTensor xi_face_prim;
//StateTensor eta_face_prim;
StateTensor conservative;
StateTensor old_conservative;
//Treatment of Boundary conditions. Hard coded :(
//First-order (constant boundary) conditions
void setBoundaryInletLeft();
void setBoundaryLowerWall();
void setBoundaryUpperLowerWalls();
void setWalls();
void setBoundaryOutlet();
void setBoundaryUpperOutlet();
//LODI Boundary conditions
void setCharacteristicBoundaryRightOutlet();
void setCharacteristicBoundaryUpperOutlet();
public:
void setImplicit(double imp) { implicit = imp; };
void setMaxTime(double t) { maxTime = t; };
void setMaxIter(double iter) { maxIter = iter; };
void setCFL(double c) { maxCFL = c; };
template <typename T> T * set(std::unique_ptr<T>& source, std::unique_ptr<T>& target) { target = std::move(source); return target.get(); };
TimeStepper * setTimeStepper(std::unique_ptr<TimeStepper>& new_stepper) { return set(new_stepper, stepper); };
Reconstruct * setReconstruct(std::unique_ptr<Reconstruct>& new_reconstruct) { return set(new_reconstruct, reconstruct); };
Grid * setGrid(std::unique_ptr<Grid>& new_grid) { return set(new_grid, grid); };
Fluid * setFluid(std::unique_ptr<Fluid>& new_fluid) { return set(new_fluid, fluid); };
Solution * setSolution(std::unique_ptr<Solution>& new_solution) { return set(new_solution, solution); };
std::vector<std::unique_ptr<Boundary>> * setBoundaries(std::vector<std::unique_ptr<Boundary>>& new_boundaries);
Eigen::Array<std::unique_ptr<Flux>,3, 1> * setFluxes(Eigen::Array<std::unique_ptr<Flux>,3,1> &new_fluxes);
void crossPopulatePointers();
void setTimeWriteInterval(double t) { time_write_interval = t; };
void setIterWriteInterval(int i) { iter_write_interval = i; };
//Utilities for Sod problem tests
void setSodXInitial();
void setSodYInitial();
//Set initial and boundary condition values for initialization
void setConsInlet(double p, const DirVector &uvec, double T);
void setConsInitial(double p, const DirVector &uvec, double T);
//Fill all cells with initial condition
void setInitialCondition();
//Constructors/destructors
Solver();
Solver(double eps, double kappa);
Solver(std::string filename, double eps, double kappa);
Solver(std::string filename);
void initSizeFromGrid();
~Solver();
//Get current time for global time stepping. Returns 0 for local time steps
double getTime();
void allocateConservative();
//limiter control
void enableLimiter() {
limit = true;
};
void disableLimiter() {
limit = false;
};
void solve();
// Deprecated prototypes
//StateVector calcFlux();
//StateVector spaceDisc(int i, int j, int k);
//StateVector spaceDisc(const StateVector & c, DirVector &n);
//StateVector calcFlux(const StateVector & c, DirVector &n);
//StateVector calcPhysFluxesXi();
//StateVector mainloop();
//StateVector calcDissip();
//void physicalFluxRight(const StateVector &c);
//void physicalFluxUp(const StateVector &c);
//void RoeDissipRight(int i, int j, int k);
//StateVector calcPhysFlux(const StateVector & prim_left, const StateVector & prim_right, DirVector &n);
};
|
4c458a48c3dc66088beb8f8bf2ae013b724e65cd | a850ee95044e4178bcbf6fc32b0c4baeb6ab7a59 | /RSA_Server/room.cpp | 88d48245f016506e2fa4b3d16621c230bbb5c904 | [] | no_license | thehugh100/RSA_Server | 1da276fa4465cb2c2d3d0e3f4922128b8a51a63d | 1bd2429fb96d65bb09a4cbdf3372b86ccb037086 | refs/heads/master | 2023-03-01T23:10:12.645152 | 2021-02-09T23:33:24 | 2021-02-09T23:33:24 | 334,467,988 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,498 | cpp | room.cpp | #include "room.h"
#include "session.h"
#include "Base64.h"
#include <boost/filesystem.hpp>
Room::Room(std::string name)
:name(name)
{
std::cout << "Created Room: " << name << std::endl;
}
std::string Room::getName()
{
return name;
}
std::string Room::getNameB64()
{
return macaron::Base64::Encode(name);
}
void Room::getFiles(nlohmann::json& j)
{
j["type"] = "files";
for (auto& i : files)
{
nlohmann::json jt;
jt["filename"] = i->filePath.filename().generic_string();
jt["size"] = i->data.size();
jt["uid"] = i->uid;
j["files"].push_back(jt);
}
}
bool Room::isUserSubscribed(std::shared_ptr<session> session)
{
return std::find(sessions.begin(), sessions.end(), session) != sessions.end();
}
void Room::sendToAllEncrypted(nlohmann::json message, std::shared_ptr<session> ignore)
{
for (auto& i : sessions)
{
if(ignore != i)
i->sendEncrypted(message);
}
}
void Room::subscribe(std::shared_ptr<session> session)
{
session->printMessage("<Subscribed to " + name + ">");
sessions.emplace_back(session);
sendToAllEncrypted({ {"type", "notice"}, {"data", macaron::Base64::Encode(session->getUsername() + " Joined") } }, session);
}
void Room::unSubscribe(std::shared_ptr<session> session)
{
session->printMessage("<Unsubscribed from " + name + ">");
auto it = std::find(sessions.begin(), sessions.end(), session);
sessions.erase(it);
sendToAllEncrypted({ {"type", "notice"}, {"data", macaron::Base64::Encode(session->getUsername() + " Left") } }, session);
}
|
e175ac708339d3237e092ba255e4395876eee793 | 35f1385993ba248b8dba5efe6509f21d8204ea0f | /src/client/scenes/IScene.hpp | 5cde3fd807e356ad5e6f4115c0d8446129fdc473 | [] | no_license | Fyloup/r-type | 52e4ede73f76a15dde83e39bf6352d1fbb518be3 | 7b9bb364479b4cb6fa360507bd28ac467376cd55 | refs/heads/master | 2020-12-06T05:45:06.752067 | 2020-01-07T16:17:38 | 2020-01-07T16:17:38 | 232,362,702 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 444 | hpp | IScene.hpp | /*
** EPITECH PROJECT, 2022
** r-type_client
** File description:
** Interface for all scenes,
*/
#ifndef R_TYPE_CLIENT_ISCENE_HPP
#define R_TYPE_CLIENT_ISCENE_HPP
#include "SFML.hpp"
namespace rtype {
class IScene {
public:
virtual ~IScene() = default;
virtual rtype::action getEvent() const = 0;
virtual IScene *update() = 0;
virtual void display() = 0;
};
}
#endif //R_TYPE_CLIENT_ISCENE_HPP
|
2457e911fee736055ad379b875f6298de3e24bf5 | 79e488c00ee8b619b577c997fc3dc5db6c05b7a5 | /comLib/GMRWLockImp.cpp | 4f1e2fa3dcbba237f8a2c08a142f216a15c3ae6b | [] | no_license | wangweichaogit/exc | 6f64aa117f8f57dba827e371dbf899383c5ad9e9 | 9b62ed1a003f10ee7e74caa2bfcfe8fe960420d8 | refs/heads/master | 2021-01-21T13:03:11.018259 | 2016-06-02T12:01:48 | 2016-06-02T12:01:48 | 52,861,877 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,897 | cpp | GMRWLockImp.cpp | /******************************************************************************
Module: binlock.cpp
Notices: Copyright (c) 2000 Jeffrey Richter
******************************************************************************/
//#include "stdafx.h"
#include "GMRWLockImp.h"
///////////////////////////////////////////////////////////////////////////////
namespace DHT
{
GMJRRWLock::GMJRRWLock()
#ifndef WIN32
:rd_cnt(0),wr_cnt(0)
#endif
{
#ifdef WIN32
// Initially no readers want access, no writers want access, and
// no threads are accessing the resource
m_nWaitingReaders = m_nWaitingWriters = m_nActive = 0;
m_hsemReaders = CreateSemaphore(NULL, 0, MAXLONG, NULL);
m_hsemWriters = CreateSemaphore(NULL, 0, MAXLONG, NULL);
InitializeCriticalSection(&m_cs);
#else
pthread_mutex_init(&cnt_mutex, NULL);
pthread_cond_init(&rw_cond, NULL);
#endif
}
///////////////////////////////////////////////////////////////////////////////
GMJRRWLock::~GMJRRWLock()
{
#ifdef WIN32
#ifdef _DEBUG
// A SWMRG shouldn't be destroyed if any threads are using the resource
if (m_nActive != 0)
DebugBreak();
#endif
m_nWaitingReaders = m_nWaitingWriters = m_nActive = 0;
DeleteCriticalSection(&m_cs);
CloseHandle(m_hsemReaders);
CloseHandle(m_hsemWriters);
#else
pthread_mutex_destroy(&cnt_mutex);
pthread_cond_destroy(&rw_cond);
#endif
}
///////////////////////////////////////////////////////////////////////////////
void GMJRRWLock::readLock()
{
#ifdef WIN32
// Ensure exclusive access to the member variables
EnterCriticalSection(&m_cs);
// Are there writers waiting or is a writer writing?
BOOL fResourceWritePending = (m_nWaitingWriters || (m_nActive < 0));
if (fResourceWritePending) {
// This reader must wait, increment the count of waiting readers
m_nWaitingReaders++;
} else {
// This reader can read, increment the count of active readers
m_nActive++;
}
// Allow other threads to attempt reading/writing
LeaveCriticalSection(&m_cs);
if (fResourceWritePending) {
// This thread must wait
WaitForSingleObject(m_hsemReaders, INFINITE);
}
#else
pthread_mutex_lock(&cnt_mutex);
while (wr_cnt > 0 )
{
pthread_cond_wait(&rw_cond,&cnt_mutex);
}
rd_cnt++;
pthread_mutex_unlock(&cnt_mutex);
#endif
}
///////////////////////////////////////////////////////////////////////////////
void GMJRRWLock::writeLock()
{
#ifdef WIN32
// Ensure exclusive access to the member variables
EnterCriticalSection(&m_cs);
// Are there any threads accessing the resource?
BOOL fResourceOwned = (m_nActive != 0);
if (fResourceOwned) {
// This writer must wait, increment the count of waiting writers
m_nWaitingWriters++;
} else {
// This writer can write, decrement the count of active writers
m_nActive = -1;
}
// Allow other threads to attempt reading/writing
LeaveCriticalSection(&m_cs);
if (fResourceOwned) {
// This thread must wait
WaitForSingleObject(m_hsemWriters, INFINITE);
}
#else
pthread_mutex_lock(&cnt_mutex);
while(rd_cnt + wr_cnt > 0)
{
pthread_cond_wait(&rw_cond,&cnt_mutex);
}
wr_cnt++;
pthread_mutex_unlock(&cnt_mutex);
#endif
}
///////////////////////////////////////////////////////////////////////////////
void GMJRRWLock::unlock()
{
#ifdef WIN32
// Ensure exclusive access to the member variables
EnterCriticalSection(&m_cs);
if (m_nActive > 0) {
// Readers have control so a reader must be done
m_nActive--;
} else {
// Writers have control so a writer must be done
m_nActive++;
}
HANDLE hsem = NULL; // Assume no threads are waiting
LONG lCount = 1; // Assume only 1 waiter wakes; always true for writers
if (m_nActive == 0) {
// No thread has access, who should wake up?
// NOTE: It is possible that readers could never get access
// if there are always writers wanting to write
if (m_nWaitingWriters > 0) {
// Writers are waiting and they take priority over readers
m_nActive = -1; // A writer will get access
m_nWaitingWriters--; // One less writer will be waiting
hsem = m_hsemWriters; // Writers wait on this semaphore
// NOTE: The semaphore will release only 1 writer thread
} else if (m_nWaitingReaders > 0) {
// Readers are waiting and no writers are waiting
m_nActive = m_nWaitingReaders; // All readers will get access
m_nWaitingReaders = 0; // No readers will be waiting
hsem = m_hsemReaders; // Readers wait on this semaphore
lCount = m_nActive; // Semaphore releases all readers
} else {
// There are no threads waiting at all; no semaphore gets released
}
}
// Allow other threads to attempt reading/writing
LeaveCriticalSection(&m_cs);
if (hsem != NULL) {
// Some threads are to be released
ReleaseSemaphore(hsem, lCount, NULL);
}
#else
pthread_mutex_lock(&cnt_mutex);
if (wr_cnt > 0)
{
wr_cnt--;
pthread_cond_broadcast(&rw_cond);
}
else if( rd_cnt > 0 )
{
rd_cnt--;
if (0 == rd_cnt)
{
pthread_cond_signal(&rw_cond);
}
}
pthread_mutex_unlock(&cnt_mutex);
#endif
}
#ifndef WIN32
void GMJRRWLock::UnWritelock()
{
pthread_mutex_lock(&cnt_mutex);
wr_cnt--;
pthread_cond_broadcast(&rw_cond);
pthread_mutex_unlock(&cnt_mutex);
}
void GMJRRWLock::UnReadlock()
{
pthread_mutex_lock(&cnt_mutex);
rd_cnt--;
if (0 == rd_cnt)
{
pthread_cond_signal(&rw_cond);
}
pthread_mutex_unlock(&cnt_mutex);
}
#endif
//////////////////////////////// End of File //////////////////////////////////
//#ifdef WIN32
//
//#include <cassert>
//
//GMWinRWLock::PROCINITSRWLOCK GMWinRWLock::m_funInitRWLock = NULL;
//GMWinRWLock::PROCACQSRWLOCKSHARE GMWinRWLock::m_funReadLock = NULL;
//GMWinRWLock::PROCRELSRWLOCKSHARE GMWinRWLock::m_funUnReadLock = NULL;
//GMWinRWLock::PROCACQSRWLOCKEXC GMWinRWLock::m_funWriteLock = NULL;
//GMWinRWLock::PROCRELSRWLOCKEXC GMWinRWLock::m_funUnWriteLock = NULL;
//unsigned long long GMWinRWLock::s_bInit = 0;
//
//bool GMWinRWLock::InitFunPtr()
//{
// do
// {
// HMODULE hLibModule = NULL;
//
// hLibModule = GetModuleHandle( "Kernel32" );
// if( hLibModule == NULL )break;
//
// m_funInitRWLock = (PROCINITSRWLOCK)GetProcAddress(
// hLibModule, "InitializeSRWLock" );
// if( m_funInitRWLock == NULL ) break;
//
// m_funReadLock = (PROCACQSRWLOCKSHARE)GetProcAddress(
// hLibModule, "AcquireSRWLockShared" );
// if( m_funReadLock == NULL ) break;
//
// m_funUnReadLock = (PROCRELSRWLOCKSHARE)GetProcAddress(
// hLibModule, "ReleaseSRWLockShared" );
// if( m_funUnReadLock == NULL ) break;
//
// m_funWriteLock = (PROCACQSRWLOCKEXC)GetProcAddress(
// hLibModule, "AcquireSRWLockExclusive" );
// if( m_funWriteLock == NULL ) break;
//
// m_funUnWriteLock = (PROCRELSRWLOCKEXC)GetProcAddress(
// hLibModule, "ReleaseSRWLockExclusive" );
// if( m_funUnWriteLock == NULL ) break;
//
// s_bInit = 0xbfcde14af5e9f587;
//
// return true;
//
// } while (false);
//
// return false;
//
//}
//bool GMWinRWLock::init()
//{
// if(s_bInit != 0xbfcde14af5e9f587)
// {
// if(!InitFunPtr())
// return false;
// }
//
// m_funInitRWLock( &m_rwLock );
// return true;
//}
//
//void GMWinRWLock::readLock()
//{
// assert( m_funReadLock != NULL );
// m_funReadLock( &m_rwLock );
//}
//
//void GMWinRWLock::unReadLock()
//{
// assert( m_funUnReadLock != NULL );
// m_funUnReadLock( &m_rwLock );
//}
//
//void GMWinRWLock::writeLock()
//{
// assert( m_funWriteLock != NULL );
// m_funWriteLock( &m_rwLock );
//}
//
//void GMWinRWLock::unWriteLock()
//{
// assert( m_funUnWriteLock != NULL );
// m_funUnWriteLock( &m_rwLock );
//}
//
//#endif
}//namespace DHT
|
3c92e4aeaaa026c88a14044e58e930394b3736cb | 31a098c53403638fb69cace30bfc9d321cd58f0b | /Source.cpp | 43fde436e43032c5a627020a89db51959aa8730b | [] | no_license | blumenkratzz/blum | f7ed84e05efaf74d0e4172dca90fb91329cab9b9 | 9bf66ae1c2e0dbe9b2870f5536b205ecdd0cbe6c | refs/heads/master | 2023-02-15T05:43:49.734883 | 2021-01-07T05:47:17 | 2021-01-07T05:47:17 | 272,359,107 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16 | cpp | Source.cpp | int gpntb = 113; |
2465aa2b7661d33c063a621693c12e2775dee3a1 | a3d6556180e74af7b555f8d47d3fea55b94bcbda | /services/service_manager/tests/lifecycle/app_client.cc | fdb00ed5c36319a628f4f97aa885c2b490470d04 | [
"BSD-3-Clause"
] | permissive | chromium/chromium | aaa9eda10115b50b0616d2f1aed5ef35d1d779d6 | a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c | refs/heads/main | 2023-08-24T00:35:12.585945 | 2023-08-23T22:01:11 | 2023-08-23T22:01:11 | 120,360,765 | 17,408 | 7,102 | BSD-3-Clause | 2023-09-10T23:44:27 | 2018-02-05T20:55:32 | null | UTF-8 | C++ | false | false | 2,110 | cc | app_client.cc | // Copyright 2016 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "services/service_manager/tests/lifecycle/app_client.h"
#include "base/run_loop.h"
#include "mojo/public/cpp/bindings/pending_receiver.h"
#include "services/service_manager/public/cpp/service_receiver.h"
namespace service_manager {
namespace test {
AppClient::AppClient(
mojo::PendingReceiver<service_manager::mojom::Service> receiver)
: service_receiver_(this, std::move(receiver)) {
receivers_.set_disconnect_handler(base::BindRepeating(
&AppClient::LifecycleControlBindingLost, base::Unretained(this)));
registry_.AddInterface<mojom::LifecycleControl>(
base::BindRepeating(&AppClient::Create, base::Unretained(this)));
}
AppClient::~AppClient() = default;
void AppClient::OnBindInterface(const BindSourceInfo& source_info,
const std::string& interface_name,
mojo::ScopedMessagePipeHandle interface_pipe) {
registry_.BindInterface(interface_name, std::move(interface_pipe));
}
void AppClient::OnDisconnected() {
DCHECK(service_receiver_.is_bound());
service_receiver_.Close();
Terminate();
}
void AppClient::Create(
mojo::PendingReceiver<mojom::LifecycleControl> receiver) {
receivers_.Add(this, std::move(receiver));
}
void AppClient::Ping(PingCallback callback) {
std::move(callback).Run();
}
void AppClient::GracefulQuit() {
if (service_receiver_.is_bound())
service_receiver_.RequestClose();
else
Terminate();
}
void AppClient::Crash() {
// Rather than actually crash, which causes a bunch of console spray and
// maybe UI clutter on some platforms, just exit without shutting anything
// down properly.
exit(1);
}
void AppClient::CloseServiceManagerConnection() {
if (service_receiver_.is_bound())
service_receiver_.Close();
}
void AppClient::LifecycleControlBindingLost() {
if (!service_receiver_.is_bound() && receivers_.empty())
Terminate();
}
} // namespace test
} // namespace service_manager
|
bc07377cb2d72763d3a452ce3f26befdcfb8dc15 | d6fcbdcdbb452adefbe2868f659fb8e84ac25fe6 | /src/check_venue_spread.h | d7ca690ffe0df2527e59f38a29bb0c22ca67ba1d | [
"MIT"
] | permissive | lulumiffy/blackbird | 49fbcb723da17c865062b00fab939fdda81a734c | 3d92dcc9f0d90083640de8d01f5913108aaa2e08 | refs/heads/master | 2021-09-01T00:47:41.939657 | 2017-12-23T23:05:49 | 2017-12-23T23:05:49 | 113,772,025 | 2 | 0 | null | 2017-12-16T16:28:15 | 2017-12-10T18:10:03 | C++ | UTF-8 | C++ | false | false | 361 | h | check_venue_spread.h | #ifndef CHECK_VENUE_SPREAD_H
#define CHECK_VENUE_SPREAD_H
#include <string>
#include <ctime>
class Bitcoin;
struct VenueSpread;
struct Parameters;
// Checks for entry opportunity between two exchanges
// and returns True if an opporunity is found.
void checkVenueSpread(Bitcoin* btcLong, Bitcoin* btcShort, VenueSpread& res, Parameters& params);
#endif
|
5284a0a750c8fc16d02d83f23c5896acdb3c8faf | 3f69ed3b758a241e4d463ba64f7eb668608d6aea | /GameTemplate/Game/Object/Rotation/RotSelf.h | ec14e7cc042f8bac2673bcc77bbfcf7a3ba99a36 | [] | no_license | komura-athushi/kgEngine | 450c061fff6e0eb981a298662a611a23c676a768 | eaab3c7714b1e40963b32df69db5f762075ecc13 | refs/heads/master | 2021-06-25T11:55:14.689944 | 2020-12-14T02:45:22 | 2020-12-14T02:45:22 | 183,392,600 | 1 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 1,098 | h | RotSelf.h | /*****************************************************************//**
* \file RotSelf.h
* \brief RotSelfクラス
*
* \author komura
* \date November 2020
*********************************************************************/
#pragma once
#include "IRot.h"
/**
* \briefオブジェクトを自転させるクラス.
*/
class RotSelf :public IRotate
{
public:
/**
* \brief コンストラクタ.
*
*/
RotSelf();
/**
* \brief デストラクタ.
*
*/
~RotSelf() override final;
/**
* 回転を計算.
*
* \param move 移動ベクトル
* \return 計算後の回転
*/
const CQuaternion Rot(const CVector3& move) override final;
/**
* \brief 回転ステートを設定.
*
*/
void SetRotState() override final
{
IRotate::SetRotStateBasic(enRot_Rot);
}
/**
* \brief 初期化処理.
*
* \param rot 初期回転
* \param speed 回転速度
*/
void Init(const CQuaternion& rot, const float speed = 0.0f) override final;
private:
float m_speed = 0.0f; //回転スピード
float m_degree = 0.0f; //角度
};
|
3192ceef99e64a2b295701bb8a965a3ac1b51486 | df05713bb78cf039445e0c5e207a3d32c2f0e1e4 | /undoTest/Test/customundostack.cpp | c0fe0f99f28618a897b73f0fc58e3ca67e78ee23 | [] | no_license | haipengyu1013/undoDemo | 21ed4bd1cb92c6658af446e5e39e2fbb03f9f3bb | 79e250e78a5c129ce752a1e1ede55781848048ba | refs/heads/main | 2023-06-05T16:15:25.467542 | 2021-06-29T03:38:34 | 2021-06-29T03:38:34 | 381,229,140 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 580 | cpp | customundostack.cpp | #include "customundostack.h"
#include "addcommand.h"
#include "deletecommand.h"
CustomUndoStack::CustomUndoStack() :
mItemsAdded(0)
{
}
void CustomUndoStack::addItem(QQuickItem *itemParent, QQmlComponent *itemComponent)
{
if (!itemParent || !itemComponent)
return;
QQuickItem *item = qobject_cast<QQuickItem*>(itemComponent->create());
if (!item) {
qWarning() << "Failed to create item";
return;
}
item->setX(mItemsAdded * 25);
item->setY(mItemsAdded * 25);
push(new AddCommand(itemParent, item));
++mItemsAdded;
}
|
f9e00a1f0c673dbab2082c21ffadb0b63b02f428 | f8b046abe51be88e9c158de8844f3f1ed383cdfd | /glpp/src/vertex_array.cpp | 118cd7581c9b78b4729d0e7870a4c5623cf6eed7 | [
"MIT"
] | permissive | jasbok/libshimmer | 71f2265b9b212d98101b73a3f23a8aaedbf73445 | 794b0e27ee8492f46202efebd24dab32a7c5c1da | refs/heads/master | 2021-01-01T17:20:30.680369 | 2018-07-23T23:01:11 | 2018-07-23T23:01:11 | 98,054,700 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,192 | cpp | vertex_array.cpp | #include "vertex_array.h"
#include "program.h"
using namespace glpp;
using namespace std;
vertex_array::vertex_array()
: _handle ( 0 )
{
glGenVertexArrays ( 1, &_handle );
}
vertex_array::vertex_array( vertex_array&& move )
: _handle ( move._handle )
{
move._handle = 0;
}
vertex_array::~vertex_array() {
glDeleteVertexArrays ( 1, &_handle );
}
vertex_array& vertex_array::operator=( vertex_array&& move ) {
glDeleteVertexArrays ( 1, &_handle );
_handle = move._handle;
move._handle = 0;
return *this;
}
GLuint vertex_array::handle() const {
return _handle;
}
vertex_array& vertex_array::bind() {
glBindVertexArray ( _handle );
return *this;
}
void vertex_array::unbind() {
glBindVertexArray ( 0 );
}
vertex_array&
vertex_array::enable_attribute_arrays ( const vector<GLint>& locations ) {
for ( const auto& location : locations ) {
glEnableVertexAttribArray ( location );
}
return *this;
}
vertex_array&
vertex_array::disable_attribute_arrays ( const vector<GLint>& locations ) {
for ( const auto& location : locations ) {
glDisableVertexAttribArray ( location );
}
return *this;
}
|
bbefcb3d9f3adb0583a9c3ebccf38475897049d3 | 35bd87c9c6cacda05252f93b4e30400aa59a0e2f | /export/release/windows/obj/src/CamZoomOption.cpp | 3cdf776bd889e90434cb8c9f5ab39e2ac8b280fa | [
"Apache-2.0"
] | permissive | RE4L-CODE/vsZero-KE | 53599f2099a17a9553adb25a7c8771db0a6bc6d4 | 44c126687ecd3caf7cc3af892164be8d520ae97a | refs/heads/main | 2023-09-01T09:58:39.012592 | 2021-11-18T10:24:21 | 2021-11-18T10:24:21 | 429,388,364 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | true | 5,851 | cpp | CamZoomOption.cpp | // Generated by Haxe 4.1.5
#include <hxcpp.h>
#ifndef INCLUDED_CamZoomOption
#include <CamZoomOption.h>
#endif
#ifndef INCLUDED_Option
#include <Option.h>
#endif
#ifndef INCLUDED_OptionsMenu
#include <OptionsMenu.h>
#endif
#ifndef INCLUDED_flixel_FlxBasic
#include <flixel/FlxBasic.h>
#endif
#ifndef INCLUDED_flixel_FlxG
#include <flixel/FlxG.h>
#endif
#ifndef INCLUDED_flixel_FlxState
#include <flixel/FlxState.h>
#endif
#ifndef INCLUDED_flixel_FlxSubState
#include <flixel/FlxSubState.h>
#endif
#ifndef INCLUDED_flixel_group_FlxTypedGroup
#include <flixel/group/FlxTypedGroup.h>
#endif
#ifndef INCLUDED_flixel_util_FlxSave
#include <flixel/util/FlxSave.h>
#endif
#ifndef INCLUDED_flixel_util_IFlxDestroyable
#include <flixel/util/IFlxDestroyable.h>
#endif
HX_DEFINE_STACK_FRAME(_hx_pos_7858b555654f959a_1463_new,"CamZoomOption","new",0xae7b5429,"CamZoomOption.new","Options.hx",1463,0x9d9a0240)
HX_LOCAL_STACK_FRAME(_hx_pos_7858b555654f959a_1472_left,"CamZoomOption","left",0xfc1bd41e,"CamZoomOption.left","Options.hx",1472,0x9d9a0240)
HX_LOCAL_STACK_FRAME(_hx_pos_7858b555654f959a_1481_right,"CamZoomOption","right",0x134ad3e5,"CamZoomOption.right","Options.hx",1481,0x9d9a0240)
HX_LOCAL_STACK_FRAME(_hx_pos_7858b555654f959a_1488_updateDisplay,"CamZoomOption","updateDisplay",0x0b240842,"CamZoomOption.updateDisplay","Options.hx",1488,0x9d9a0240)
void CamZoomOption_obj::__construct(::String desc){
HX_STACKFRAME(&_hx_pos_7858b555654f959a_1463_new)
HXLINE(1464) super::__construct();
HXLINE(1465) if (::OptionsMenu_obj::isInPause) {
HXLINE(1466) this->description = HX_("This option cannot be toggled in the pause menu.",b4,21,dd,c9);
}
else {
HXLINE(1468) this->description = desc;
}
}
Dynamic CamZoomOption_obj::__CreateEmpty() { return new CamZoomOption_obj; }
void *CamZoomOption_obj::_hx_vtable = 0;
Dynamic CamZoomOption_obj::__Create(::hx::DynamicArray inArgs)
{
::hx::ObjectPtr< CamZoomOption_obj > _hx_result = new CamZoomOption_obj();
_hx_result->__construct(inArgs[0]);
return _hx_result;
}
bool CamZoomOption_obj::_hx_isInstanceOf(int inClassId) {
if (inClassId<=(int)0x27a70eb9) {
return inClassId==(int)0x00000001 || inClassId==(int)0x27a70eb9;
} else {
return inClassId==(int)0x75f1412f;
}
}
bool CamZoomOption_obj::left(){
HX_STACKFRAME(&_hx_pos_7858b555654f959a_1472_left)
HXLINE(1473) if (::OptionsMenu_obj::isInPause) {
HXLINE(1474) return false;
}
HXLINE(1475) ::flixel::FlxG_obj::save->data->__SetField(HX_("camzoom",a2,ca,10,f1),!(( (bool)(::flixel::FlxG_obj::save->data->__Field(HX_("camzoom",a2,ca,10,f1),::hx::paccDynamic)) )),::hx::paccDynamic);
HXLINE(1476) this->display = this->updateDisplay();
HXLINE(1477) return true;
}
bool CamZoomOption_obj::right(){
HX_STACKFRAME(&_hx_pos_7858b555654f959a_1481_right)
HXLINE(1482) this->left();
HXLINE(1483) return true;
}
::String CamZoomOption_obj::updateDisplay(){
HX_STACKFRAME(&_hx_pos_7858b555654f959a_1488_updateDisplay)
HXDLIN(1488) ::String _hx_tmp;
HXDLIN(1488) if (!(( (bool)(::flixel::FlxG_obj::save->data->__Field(HX_("camzoom",a2,ca,10,f1),::hx::paccDynamic)) ))) {
HXDLIN(1488) _hx_tmp = HX_("off",6f,93,54,00);
}
else {
HXDLIN(1488) _hx_tmp = HX_("on",1f,61,00,00);
}
HXDLIN(1488) return ((HX_("Camera Zoom: < ",f8,25,b7,70) + _hx_tmp) + HX_(" >",1e,1c,00,00));
}
::hx::ObjectPtr< CamZoomOption_obj > CamZoomOption_obj::__new(::String desc) {
::hx::ObjectPtr< CamZoomOption_obj > __this = new CamZoomOption_obj();
__this->__construct(desc);
return __this;
}
::hx::ObjectPtr< CamZoomOption_obj > CamZoomOption_obj::__alloc(::hx::Ctx *_hx_ctx,::String desc) {
CamZoomOption_obj *__this = (CamZoomOption_obj*)(::hx::Ctx::alloc(_hx_ctx, sizeof(CamZoomOption_obj), true, "CamZoomOption"));
*(void **)__this = CamZoomOption_obj::_hx_vtable;
__this->__construct(desc);
return __this;
}
CamZoomOption_obj::CamZoomOption_obj()
{
}
::hx::Val CamZoomOption_obj::__Field(const ::String &inName,::hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 4:
if (HX_FIELD_EQ(inName,"left") ) { return ::hx::Val( left_dyn() ); }
break;
case 5:
if (HX_FIELD_EQ(inName,"right") ) { return ::hx::Val( right_dyn() ); }
break;
case 13:
if (HX_FIELD_EQ(inName,"updateDisplay") ) { return ::hx::Val( updateDisplay_dyn() ); }
}
return super::__Field(inName,inCallProp);
}
#ifdef HXCPP_SCRIPTABLE
static ::hx::StorageInfo *CamZoomOption_obj_sMemberStorageInfo = 0;
static ::hx::StaticInfo *CamZoomOption_obj_sStaticStorageInfo = 0;
#endif
static ::String CamZoomOption_obj_sMemberFields[] = {
HX_("left",07,08,b0,47),
HX_("right",dc,0b,64,e9),
HX_("updateDisplay",39,8f,b8,86),
::String(null()) };
::hx::Class CamZoomOption_obj::__mClass;
void CamZoomOption_obj::__register()
{
CamZoomOption_obj _hx_dummy;
CamZoomOption_obj::_hx_vtable = *(void **)&_hx_dummy;
::hx::Static(__mClass) = new ::hx::Class_obj();
__mClass->mName = HX_("CamZoomOption",b7,0b,0a,fc);
__mClass->mSuper = &super::__SGetClass();
__mClass->mConstructEmpty = &__CreateEmpty;
__mClass->mConstructArgs = &__Create;
__mClass->mGetStaticField = &::hx::Class_obj::GetNoStaticField;
__mClass->mSetStaticField = &::hx::Class_obj::SetNoStaticField;
__mClass->mStatics = ::hx::Class_obj::dupFunctions(0 /* sStaticFields */);
__mClass->mMembers = ::hx::Class_obj::dupFunctions(CamZoomOption_obj_sMemberFields);
__mClass->mCanCast = ::hx::TCanCast< CamZoomOption_obj >;
#ifdef HXCPP_SCRIPTABLE
__mClass->mMemberStorageInfo = CamZoomOption_obj_sMemberStorageInfo;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mStaticStorageInfo = CamZoomOption_obj_sStaticStorageInfo;
#endif
::hx::_hx_RegisterClass(__mClass->mName, __mClass);
}
|
bb8692fbd3e57dceb27b2f390ba9409f6a30b0fd | 333b58a211c39f7142959040c2d60b69e6b20b47 | /Odyssey/SSAPI_Server/ManagedObjects/TableStuffRow.h | 33a02a50f5b62a12a1648eccdca0ae2972c7067e | [] | no_license | JoeAltmaier/Odyssey | d6ef505ade8be3adafa3740f81ed8d03fba3dc1a | 121ea748881526b7787f9106133589c7bd4a9b6d | refs/heads/master | 2020-04-11T08:05:34.474250 | 2015-09-09T20:03:29 | 2015-09-09T20:03:29 | 42,187,845 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,263 | h | TableStuffRow.h | //************************************************************************
// FILE: TableStuffRow.h
//
// PURPOSE: Defines that object whose instances will be used to
// represent PTS table rows.
//************************************************************************
#ifndef __TABLE_STUFF_ROW_H__
#define __TABLE_STUFF_ROW_H__
#include "ManagedObject.h"
#include "PtsCommon.h"
class ShadowTable;
class TableStuffRow : public ManagedObject {
ShadowTable *m_pTable;
void *m_pRowData;
U32 m_rowDataSize;
public:
//************************************************************************
//
//************************************************************************
TableStuffRow( ListenManager *pLM,
ObjectManager *pManager,
ShadowTable *pTable,
void *pData,
U32 dataSize );
//************************************************************************
// CreateInstance:
//
// PURPOSE: Creates an instance of the same time as it is.
// The best attempt is made to clone data members that
// are not a part of the object's value set. The ones that
// are will not be copied - they can copied manually thru
// value set's functionality.
//************************************************************************
virtual ManagedObject* CreateInstance(){ return new TableStuffRow(GetListenManager(),
GetManager(),
m_pTable,
m_pRowData,
m_rowDataSize ); }
//************************************************************************
//
//************************************************************************
virtual ~TableStuffRow();
//************************************************************************
// BuildYourValueSet:
//
// PURPOSE: The method is responsible for adding all data to be
// transfered to a client into its value set. All derived
// objects must override this method if they have data members
// they want client proxies to have.
//
// NOTE: If a derived object overrides this this method, it MUST call
// it in its base class BEFORE doing any work!.
//
// RETURN: true: success
//************************************************************************
virtual bool BuildYourValueSet();
//************************************************************************
// BuildYourselfFromYourValueSet:
//
// PURPOSE: Populates data members based on the underlying value set
//
// NOTE: All subclasses that override this method must call to it
// somewhere in the overriding method
//
// RETURN: true: success
//************************************************************************
virtual bool BuildYourselfFromYourValueSet();
//************************************************************************
// operator=:
//************************************************************************
virtual const ValueSet& operator=(const ValueSet& obj ){ return *((ValueSet*)this) = obj; }
//************************************************************************
// ModifyObject:
//
// PURPOSE: Modifes contents of the object
//
// NOTE: Must be overridden by objects that can be modified
//************************************************************************
virtual bool ModifyObject( ValueSet &objectValues, SsapiResponder *pResponder );
//************************************************************************
// DeleteObject:
//
// PURPOSE: Deletes the object from the system
//
// NOTE: Must be overridden by objects that can be deleted
//************************************************************************
virtual bool DeleteObject( ValueSet &objectValues, SsapiResponder *pResponder );
ShadowTable& GetShadowTable() { return *m_pTable; }
private:
//************************************************************************
// PutValue: Based on the value type, adds it properly into the
// value set provided
//************************************************************************
void PutValue( fieldDef *pField, ValueSet *pVs, U32 position, char* &pCurrent );
};
#endif // __TABLE_STUFF_ROW_H__ |
4d9c85cad1a31542b84e86f2c02398ecf715abcd | 185a2fdb2728e8cb0e6d8398a72e90cc66a9d10a | /sddrservice/src/main/jni/source/EbNDevice.cpp | a8dabfa58ec6dd6774b2fe66a53fad7ae49fe044 | [] | no_license | tslilyai/android-BluetoothLeGatt | 3d46ab3cb7839728df646c3bcdf487afbd81570b | 208b70b1f8baa7ef055e0b437d2a969d9aa7115f | refs/heads/master | 2021-05-11T14:10:52.144951 | 2018-01-29T13:18:49 | 2018-01-29T13:18:49 | 117,690,575 | 0 | 0 | null | 2018-01-16T14:00:17 | 2018-01-16T14:00:17 | null | UTF-8 | C++ | false | false | 2,774 | cpp | EbNDevice.cpp | #include "EbNDevice.h"
#include "Logger.h"
extern uint64_t sddrStartTimestamp;
using namespace std;
EbNDevice::EbNDevice(DeviceID id, const Address &address)
: id_(id),
address_(address),
adverts_(),
adverts_to_report_(),
advertsMutex_(),
rssiToReport_(),
lastReportTime_(0),
shakenHands_(false)
{
}
EbNDevice::~EbNDevice()
{
}
void EbNDevice::addAdvert(const std::string advert)
{
bool found = false;
lock_guard<mutex> advertLock(advertsMutex_);
for(auto it = adverts_.begin(); it != adverts_.end(); it++)
{
if (it->compare(advert) == 0)
{
found = true;
break;
}
}
if (!found) {
adverts_.push_back(advert);
adverts_to_report_.push_back(advert);
LOG_P("EbNDevice", "Found advert \'%s\' for id %d", advert.c_str(), id_);
}
}
bool EbNDevice::getEncounterInfo(EncounterEvent &dest, bool expired, bool retroactive)
{
return getEncounterInfo(dest, numeric_limits<uint64_t>::max(), expired, retroactive);
}
void EbNDevice::getEncounterStartAdvert(EncounterEvent &dest)
{
lock_guard<mutex> advertsLock(advertsMutex_);
if (!adverts_to_report_.empty()) {
LOG_P(TAG, "Reporting %d adverts", adverts_.size());
dest.adverts = adverts_;
dest.advertsUpdated = true;
adverts_to_report_.clear();
}
}
bool EbNDevice::getEncounterInfo(EncounterEvent &dest, uint64_t rssiReportingInterval, bool expired, bool retroactive)
{
bool success = false;
if(expired)
{
LOG_P(TAG, "getEncounterInfo -- expired");
dest.type = EncounterEvent::Ended;
dest.id = id_;
dest.address = address_.toString();
if(!rssiToReport_.empty())
{
dest.rssiEvents = rssiToReport_;
rssiToReport_.clear();
}
success = true;
}
else
{
lock_guard<mutex> advertsLock(advertsMutex_);
const bool reportRSSI = !rssiToReport_.empty() && ((getTimeMS() - lastReportTime_) > rssiReportingInterval);
const bool reportAdverts = !adverts_to_report_.empty();
const bool isUpdated = shakenHands_ && (reportRSSI || reportAdverts);
LOG_P(TAG, "getEncounterInfo -- Updated ? %d", isUpdated);
if(isUpdated)
{
dest.type = EncounterEvent::Updated;
dest.id = id_;
dest.address = address_.toString();
if(!rssiToReport_.empty())
{
dest.rssiEvents = rssiToReport_;
rssiToReport_.clear();
}
if (!adverts_to_report_.empty()) {
LOG_P(TAG, "Reporting %d adverts", adverts_.size());
dest.adverts = adverts_;
dest.advertsUpdated = true;
adverts_to_report_.clear();
}
lastReportTime_ = getTimeMS();
}
success = isUpdated;
}
return success;
}
|
e503397743615368bcbc11fb66daef8f6ecc8bd0 | fa11fa3d5cc862075f186033807c49e3fffa601f | /src/KrulProgram.cpp | 1fed956435a694fdfc5f65e76c4303692f4ee3b7 | [] | no_license | jessevdp/krul-interpreter | 4959aef4027ebe8c1b70321369196b61a452d77c | c8695097b70d204d02ab38f2bc186a5f83fd1734 | refs/heads/main | 2023-04-25T02:53:48.192961 | 2021-05-08T16:34:29 | 2021-05-08T16:34:29 | 303,754,353 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,787 | cpp | KrulProgram.cpp | #include "KrulProgram.h"
#include "interpreter/MapVariableRegistry.h"
#include "interpreter/VectorCallStack.h"
#include "interpreter/VectorStack.h"
#include "parser/DefaultParser.h"
#include "parser/Parser.h"
namespace krul {
using namespace parser;
using namespace interpreter;
interpreter::Result KrulProgram::execute() {
while (_current_line < _instructions.size() && !_found_end) {
const auto& instruction = _instructions.at(_current_line);
instruction->execute(*this);
go_to_next_line();
}
return Result(_stack->peek(), _found_end);
}
KrulProgram::KrulProgram(const std::string& source_code)
: _stack {std::make_unique<VectorStack>()}, _call_stack {std::make_unique<VectorCallStack>()},
_variables {std::make_unique<MapVariableRegistry>()} {
std::unique_ptr<Parser> parser = std::make_unique<DefaultParser>();
auto parsed_program = parser->parse(source_code);
_instructions = parsed_program->instructions();
_labels = parsed_program->label_registry();
}
interpreter::Stack& KrulProgram::stack() const {
return *_stack;
}
interpreter::VariableRegistry& KrulProgram::variables() const {
return *_variables;
}
interpreter::LabelRegistry& KrulProgram::labels() const {
return *_labels;
}
interpreter::CallStack& KrulProgram::call_stack() const {
return *_call_stack;
}
interpreter::line_t KrulProgram::current_line() const {
return _current_line;
}
void KrulProgram::found_end() {
_found_end = true;
}
void KrulProgram::go_to_line(interpreter::line_t line) {
goto_executed = true;
_current_line = line;
}
void KrulProgram::go_to_next_line() {
if (goto_executed) goto_executed = false;
else _current_line++;
}
} // namespace krul |
7f0fd7139a5f41bb11027d582cc9bfb8c347f489 | e1c15a8e8ae78184b09894024db98d946ab20de4 | /Code/Keng/WindowSystem/include/Keng/WindowSystem/IWindow.h | 7e2a4fc955e9e7dbb0bcb2778b98768d8a5a86e1 | [] | no_license | Sunday111/D3D_Samples | d33721a36d2557a2aa4807305253be36afa6b06e | 76851283b9f7950d0080deabae829c1751f9a179 | refs/heads/master | 2021-06-04T22:03:36.288475 | 2020-01-12T01:00:27 | 2020-01-12T01:00:27 | 118,942,545 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 397 | h | IWindow.h | #pragma once
#include <cstdint>
namespace keng::window_system
{
class IWindowListener;
class IWindow
{
public:
virtual void Subscribe(IWindowListener*) = 0;
virtual void Unsubscribe(IWindowListener*) = 0;
virtual void GetClientSize(size_t* w, size_t* h) = 0;
virtual int64_t* GetNativeHandle() = 0;
virtual ~IWindow() = default;
};
}
|
a3b938352af1d72941ca7865920e0f44c98eff08 | 6f0f90fbfc12d28b6b8d21b2a41e114b38d5c544 | /player/src/Mesh.cpp | 90504c25f1cff972d494a13cc89b066adc17bb58 | [] | no_license | cha63506/pixelnoir | 6725fe372ffad831c7ae14905c363dfb295e3c1a | 376d85f261b5653c72af54c93ac080eb650cf402 | refs/heads/master | 2018-01-15T17:55:40.117149 | 2011-04-12T08:55:55 | 2011-04-12T08:55:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,519 | cpp | Mesh.cpp | //Copyright (c) 2010 Heinrich Fink <hf (at) hfink (dot) eu>,
// Thomas Weber <weber (dot) t (at) gmx (dot) at>
//
//Permission is hereby granted, free of charge, to any person obtaining a copy
//of this software and associated documentation files (the "Software"), to deal
//in the Software without restriction, including without limitation the rights
//to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//copies of the Software, and to permit persons to whom the Software is
//furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in
//all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//THE SOFTWARE.
#include "Mesh.h"
#include "Shader.h"
#include "rtr_format.pb.h"
#include <fstream>
#include <limits>
using std::ios;
//helper method to determin actual GL type
GLenum primitive_to_gltype(const rtr_format::Mesh::PrimitiveType& pType) {
switch(pType) {
case rtr_format::Mesh::TRIANGLES:
return GL_TRIANGLES;
case rtr_format::Mesh::TRIANGLE_STRIP:
return GL_TRIANGLE_STRIP;
default:
std::cerr << "Could not convert protocol buffer primitive type "
<< pType << " to GL type." << endl;
return 0;
}
}
bool gltype_to_primitive(GLenum gltype, rtr_format::Mesh::PrimitiveType& typeOut) {
switch (gltype) {
case GL_TRIANGLES:
typeOut = rtr_format::Mesh::TRIANGLES;
return true;
case GL_TRIANGLE_STRIP:
typeOut = rtr_format::Mesh::TRIANGLE_STRIP;
return true;
default:
std::cerr << "Could not convert gl primitive type " << gltype
<< " to protocol buffer primitive type." << endl;
return false;
}
}
MeshInitializer::MeshInitializer(string id,
GLenum primitive_type,
GLint vertex_count) :
_id(id),_primitive_type(primitive_type),
_vertex_count(vertex_count) {};
MeshInitializer::MeshInitializer(const rtr_format::Mesh& mesh_buffer)
{
_id = mesh_buffer.id();
_primitive_type = primitive_to_gltype(mesh_buffer.primitive_type());
_vertex_count = mesh_buffer.vertex_count();
ArrayAdapter indices_data(mesh_buffer.index_data().data(), mesh_buffer.index_data_size());
add_indices(indices_data);
for (int i = 0; i < mesh_buffer.layer_size(); ++i) {
const rtr_format::Mesh_VertexAttributeLayer& l = mesh_buffer.layer(i);
//Note: At the moment we assume that all layers only carry
//GL_FLOAT data types. At the moment this is a property on a
//per-layer-source basis. We would have to pass this information
//somewhow, if we allowed int layers as well.
GLenum gl_type = GL_FLOAT;
add_layer( l.name(),
gl_type,
l.num_components(),
l.source_index(),
l.source() );
}
//get the bounding volume data
float b_sphere_radius = 0;
vec3 b_sphere_center;
b_sphere_center.x = mesh_buffer.bounding_sphere().center_x();
b_sphere_center.y = mesh_buffer.bounding_sphere().center_y();
b_sphere_center.z = mesh_buffer.bounding_sphere().center_z();
b_sphere_radius = mesh_buffer.bounding_sphere().radius();
_bounding_sphere = Sphere(b_sphere_radius, b_sphere_center);
}
void MeshInitializer::store(rtr_format::Mesh& mesh_buffer) const
{
// Clear data in protocol buffer.
mesh_buffer.Clear();
// Copy all information into protocol buffer
mesh_buffer.set_id(_id);
rtr_format::Mesh::PrimitiveType prim_type;
bool success = gltype_to_primitive(_primitive_type, prim_type);
assert( success );
mesh_buffer.set_primitive_type(prim_type);
mesh_buffer.set_vertex_count(_vertex_count);
const GLuint* indices = _index_data.access_elements<GLuint>();
for (int i = 0; i < _index_data.size(); ++i) {
mesh_buffer.add_index_data(indices[i]);
}
for (vector<LayerInfo>::const_iterator i = _layers.begin();
i != _layers.end(); ++i) {
rtr_format::Mesh_VertexAttributeLayer* l = mesh_buffer.add_layer();
l->set_name(i->name);
l->set_num_components(i->components);
l->set_source(i->layer_source_id);
l->set_source_index(i->source_index);
}
}
void MeshInitializer::add_layer( string name,
GLenum type,
GLint components,
int source_index,
const string& layer_source_id )
{
LayerInfo layer;
layer.name = name;
layer.type = type;
layer.components = components;
layer.layer_source_id = layer_source_id;
layer.source_index = source_index;
_layers.push_back(layer);
}
void MeshInitializer::add_indices(const ArrayAdapter& index_array)
{
_index_data = index_array;
}
int MeshInitializer::layers_size() const {
return _layers.size();
}
const string& MeshInitializer::layer_source_id_at(int i) const {
return _layers.at(i).layer_source_id;
}
GPUMesh::GPUMesh(const MeshInitializer& init, const GPULayerSourceMap& sources) :
_id(init._id),
_primitive_type(init._primitive_type),
_vertex_count(init._vertex_count),
_index_count(init._index_data.size())
{
const GLuint * idx_ptr = NULL;
for (vector<MeshInitializer::LayerInfo>::const_iterator i = init._layers.begin();
i != init._layers.end(); ++i) {
LayerInfo layer;
layer.name = i->name;
layer.type = i->type;
layer.components = i->components;
//Find the converted source
assert(sources.find(i->layer_source_id) != sources.end());
GPULayerSourceRef source_data = sources.find(i->layer_source_id)->second;
layer.source = source_data;
layer.vbo_offset = (GLvoid*)( source_data->element_size()*i->source_index );
_layers.push_back(layer);
}
// Set up index VBO if necessary
if (_index_count > 0) {
glGenBuffers(1, &_index_buffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _index_buffer);
idx_ptr = init._index_data.access_elements<GLuint>();
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLuint)*_index_count,
idx_ptr, GL_STATIC_READ);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}
//Getbounding volume info
_bounding_volume = BoundingVolume(init._bounding_sphere);
}
GPUMesh::~GPUMesh()
{
// Free index VBO if necessary
if (_index_count > 0) {
glDeleteBuffers(1, &_index_buffer);
}
// Delete all associated VAOs
for (std::map<GLuint, GLuint>::iterator entry = _shader_to_vao_map.begin();
entry != _shader_to_vao_map.end(); ++entry) {
GLuint vao = entry->second;
glDeleteVertexArrays(1, &vao);
}
}
void GPUMesh::prepare_vao(const Shader& shader)
{
// Delete old VAO for this shader if necessary
if (_shader_to_vao_map.count(shader.get_program_ID()) > 0) {
GLuint old_vao = _shader_to_vao_map[shader.get_program_ID()];
glDeleteVertexArrays(1, &old_vao);
}
// Create and bind new VAO
GLuint vao;
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
// Bind index VBO if necessary
if (_index_count > 0)
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _index_buffer);
for (int i = 0; i < shader.get_attrib_count(); ++i) {
string attrib_name = shader.get_attrib_name(i);
list<LayerInfo>::const_iterator l = _layers.begin();
while (l != _layers.end()) {
if (attrib_name == l->name) break;
++l;
}
if (l == _layers.end()) { {
cerr << "Error: Mesh is missing required vertex attribute '"
<< attrib_name << "'!" << endl;
}
} else {
GLint location = shader.get_attrib_location(attrib_name);
//bind the VBO of the source
l->source->bind();
glEnableVertexAttribArray(location);
glVertexAttribPointer(location, l->components,
l->type, GL_FALSE, 0, l->vbo_offset);
//unbind VBOs
l->source->unbind();
}
}
glBindVertexArray(0);
// Store vao index in map
_shader_to_vao_map[shader.get_program_ID()] = vao;
}
void GPUMesh::draw(const Shader& shader)
{
if (_shader_to_vao_map.count(shader.get_program_ID()) < 1) {
prepare_vao(shader);
}
// This is actually trivial with VAOs.
glBindVertexArray(_shader_to_vao_map.at(shader.get_program_ID()));
if (_index_count > 0) {
glDrawElements(_primitive_type, _index_count, GL_UNSIGNED_INT, NULL);
} else {
glDrawArrays(_primitive_type, 0, _vertex_count);
}
glBindVertexArray(0);
}
|
7f50fc142b9307179253bd6df435c8ca68d40cb2 | d5490fcb0b49cc8d407a9e2d08e75a32fa99a1f2 | /process.h | 2a72d3f756dfbdc1e2bd7732d9d0497f05a1c0b9 | [] | no_license | Fiona/PixelPicsCPP | 1038de3b4ff435f15bd03a92f6d73bef4716109d | 9eaa2afd01253c7103927e65cd40f7915a2b7bc0 | refs/heads/master | 2022-05-03T03:57:28.414422 | 2014-07-26T15:09:46 | 2014-07-26T15:09:46 | 3,016,735 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,795 | h | process.h | /****************************
PIXEL PICS
2011/2012 STOMPY BLONDIE GAMES
****************************
Processesss
****************************/
#ifndef _PROCESS_H_
#define _PROCESS_H_
using namespace boost;
#include <vector>
#include <SDL/SDL.h>
#define TEXT_ALIGN_TOP_LEFT 0
#define TEXT_ALIGN_TOP 1
#define TEXT_ALIGN_TOP_RIGHT 2
#define TEXT_ALIGN_CENTER_LEFT 3
#define TEXT_ALIGN_CENTER 4
#define TEXT_ALIGN_CENTER_RIGHT 5
#define TEXT_ALIGN_BOTTOM_LEFT 6
#define TEXT_ALIGN_BOTTOM 7
#define TEXT_ALIGN_BOTTOM_RIGHT 8
#define Z_TEXT -512
struct ProcessWrapper;
/*
*/
class Process
{
public:
Process();
virtual ~Process();
static boost::python::list internal_list;
static std::vector<Process*> Process_List;
static bool z_order_dirty;
static std::vector<Process*> Priority_List;
static bool priority_order_dirty;
static GLuint current_bound_texture;
static vector<float> default_texture_coords;
static std::vector<Process*> Processes_to_kill;
float x;
float y;
int z;
int priority;
Image* image;
float scale;
int rotation;
std::vector<float> colour;
std::vector<float> clip;
float alpha;
int image_sequence;
std::vector<float> scale_pos;
bool is_dead;
string draw_strategy;
PyObject* self;
boost::python::object self_;
virtual void Execute();
virtual void On_Exit();
virtual void Draw();
void Kill();
void Set_z(int new_z);
void Set_priority(int priority_);
void Set_colour(boost::python::object list);
void Set_clip(boost::python::object list);
void Set_scale_pos(boost::python::object list);
void move_forward(float distance_to_travel, int rotation_to_move_in);
float deg_to_rad(float deg);
float rad_to_deg(float rad);
virtual tuple<float, float> get_screen_draw_position();
// Draw strategies
void Draw_strategy_primitive_square();
void Draw_strategy_primitive_line();
void Draw_strategy_gui_button();
void Draw_strategy_gui_window_frame();
void Draw_strategy_gui_text_input();
void Draw_strategy_gui_dropdown_currently_selected();
void Draw_strategy_gui_dropdown_options();
void Draw_strategy_puzzle();
void Draw_strategy_puzzle_pixel_message();
void Draw_strategy_gui_scroll_window();
void Draw_strategy_gui_designer_packs_pack_item();
void Draw_strategy_gui_spinner();
void Draw_strategy_gui_slider();
void Draw_strategy_gui_designer_designer_menu_bar();
void Draw_strategy_gui_designer_monochrome_puzzle_image();
void Draw_strategy_designer_puzzle_background_item();
void Draw_strategy_designer_colour_current_colour();
void Draw_strategy_designer_colour_value_slider();
void Draw_strategy_balloons_background();
void Draw_strategy_tutorial_background();
void Draw_strategy_designer_background();
void Draw_strategy_present_background();
void Draw_strategy_puzzle_select();
void Draw_strategy_puzzle_select_puzzle_item();
void Draw_strategy_main_menu_title();
void create_image_from_puzzle();
void destroy_puzzle_image();
void create_image_as_pallete(int pallete_width, int pallete_height);
};
struct ProcessWrapper : Process
{
ProcessWrapper(PyObject *p);
ProcessWrapper();
bool has_init;
bool has_killed;
bool is_dead;
PyObject *self;
boost::python::object self_;
void Execute();
void Execute_default();
void On_Exit();
void On_Exit_default();
void Kill();
tuple<float, float> get_screen_draw_position();
tuple<float, float> get_screen_draw_position_default();
};
/*
*/
class Text: public Process
{
public:
Text();
Text(Font* _font, float _x, float _y, int _alignment, string _text);
~Text();
float x;
float y;
int z;
int priority;
float scale;
int rotation;
float alpha;
Font* font;
int alignment;
string text;
int text_width;
int text_height;
int shadow;
std::vector<float> shadow_colour;
bool generate_mipmaps;
void Set_z(int new_z);
void set_text(string _text);
void Set_colour(boost::python::object list);
void Set_clip(boost::python::object list);
void Set_shadow_colour(boost::python::object list);
void Set_generate_mipmaps(bool generate_mipmaps_);
tuple<float, float> get_screen_draw_position();
void Draw();
void Kill();
private:
void generate_new_text_image();
};
struct TextWrapper : Text
{
TextWrapper(PyObject *p);
TextWrapper(PyObject *p, Font* _font, float _x, float _y, int _alignment, string _text);
PyObject *self;
boost::python::object self_;
void Execute();
void Execute_default();
void Kill();
};
#endif
|
c21b4f723ff6de55d3b483acfc33a520ddddd970 | 3f8d40e1dbd9ff02e0cedb5180d9b3f7f52875a0 | /src/main.cpp | 1c69cb79bf59d8954ceed494ffd6726ae1025a99 | [] | no_license | AndrePim/Blink | a956c2c4400c33beac0890a818d768146c99a787 | 4b3da7f7b5d8330b4351c366f48374814060d301 | refs/heads/master | 2020-04-07T05:48:56.275554 | 2018-11-19T04:07:09 | 2018-11-19T04:07:09 | 158,111,267 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 561 | cpp | main.cpp | #include <Arduino.h>
#define LED_PIN 13 // Светодиод подключён к 13 пину
#define BLINK_DELAY 1000 // Задержка 1000 мс
void setup() {
pinMode(LED_PIN, OUTPUT); // Установка режима работы на выход
}
void loop() {
digitalWrite(LED_PIN, HIGH); // Включение светодиода
delay(BLINK_DELAY); // Светодиод горит 1с
digitalWrite(LED_PIN, LOW); // Выключение светодиода
delay(BLINK_DELAY); // Светодиод не горит 1с
}
|
f01be04318a1b0cfaed738057307aa0715ea6a23 | 812125f1d67ab7cb468a06171fb6ef86c8ef1483 | /test/point.cpp | 98e00e40de6a47c9b8f35489b9b90d2762a224c4 | [] | no_license | sxw106106/cpp-learning | 861e8d67ed29ce0ceac78acb900e4756667adad6 | 7cd2817699e816acd6725137e6f7254b9fcbe1a0 | refs/heads/master | 2021-01-21T06:46:47.779675 | 2014-03-24T16:20:28 | 2014-03-24T16:20:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 244 | cpp | point.cpp | #include <stdio.h>
int main(void)
{
int *pint;
if(!pint)
{
printf("pint is null\n");
}
char *pchar;
if(!pchar)
{
printf("pchar is null\n");
}
char *pchar2=NULL;
pchar2 = NULL;
if(!pchar2)
{
printf("pchar2 is null\n");
}
}
|
b52f44a9e60d03e9825bb3214016cc5718532763 | 9536b0d7fb1ad7b8ac8e9fb770a69c68ca28bb3e | /Maleg/src/Boss.cpp | 44d5c23138823121d32dae8edfccb28b4d24883e | [] | no_license | TrabajoInformatica/Juego_Maleg_Trabajo_Informatica | 46b1061c91b5e17e3b1b0d0bcae502f6eb0dd140 | b373f7fde9c5462f89d38bf5122a27e090444a0f | refs/heads/master | 2022-11-16T09:13:07.146652 | 2020-07-05T17:51:57 | 2020-07-05T17:51:57 | 268,117,479 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,130 | cpp | Boss.cpp | #include "Boss.h"
#include "ObjetoMovil.h"
Boss::Boss():boss("imagenes/minotauro.png", 9, 5) {
altura = 4.0f;
velocidad = 0;
aceleracion = 0;
}
Boss::~Boss() {
}
void Boss::Mueve(float t) {
ObjetoMovil::Mueve(t);
}
void Boss::Dibuja() {
//Dimensiones del sprite
boss.setCenter(5, 5);
boss.setSize(10, 10);
//Dibujo
glPushMatrix();
glTranslatef(posicion.x, posicion.y, 0.5);
boss.flip(true, false);
boss.draw();
boss.loop();
glPopMatrix();
//HITBOX
if (estado == Show) {
glPushMatrix();
glColor3ub(255, 0, 0);
glTranslatef(posicion.x, posicion.y, 0);
glutWireSphere(altura, 40, 40);
glTranslatef(-posicion.x, -posicion.y, 0);
glPopMatrix();
}
}
void Boss::SetVida(int v) {
vida = v;
}
int Boss::GetVida() {
return vida;
}
bool Boss::Colision(Heroe* p, Boss b) {
if (Interaccion::ColisionEnemigo(p, b))
{
p->PuntoReaparicion();
return true;
//ETSIDI::play("sonidos/estruendo.wav");
}
return false;
}
bool Boss::Colision(ListaArmas a, Boss b) {
for (int i = 0;i < a.GetNum();i++)
{
if (Interaccion::ColisionEnemigo(a.GetLista(i), b))
{
return true;
}
}
return false;
} |
32176ce79615e88cce5b9c4d9586f947dd8f8e80 | b21fcc8cb47ade1997858e4cc6dcb69473dbef53 | /Matrix/Easy/Sort the Matrix Diagonally.cpp | 166a1f2666f9d70c85dcc18b45693a218ef812dc | [] | no_license | manojxk/GFG-DSA-CheatSheet | a72628dea17d0185e01ab38e6386e1e49726024a | 1583761aadba60c093fe14fb3f1b558986aadaad | refs/heads/main | 2023-07-10T03:17:45.024187 | 2021-08-17T10:57:07 | 2021-08-17T10:57:07 | 391,797,866 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 739 | cpp | Sort the Matrix Diagonally.cpp | // Explanation
// A[i][j] on the same diagonal have same value of i - j
// For each diagonal,
// put its elements together, sort, and set them back.
vector<vector<int>> diagonalSort(vector<vector<int>> &mat)
{
int m = mat.size(), n = mat[0].size();
// all elements on same diagonal have same i-j result.
unordered_map<int, priority_queue<int, vector<int>, greater<int>>> map; // min priority queue
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
map[i - j].push(mat[i][j]);
}
}
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
mat[i][j] = map[i - j].top();
map[i - j].pop();
}
}
return mat;
} |
b21ec012abc61dbb7692eb0cdf9671916f90f41a | fd0c132f979ecd77168511c6f4d276c480147e57 | /ios/Classes/Native/AssemblyU2DCSharp_Org_BouncyCastle_Crypto_Prng_Cryp405007133.h | 665b9011dc27f245c30378eb72cb69967aa66f08 | [] | no_license | ping203/gb | 9a4ab562cc6e50145660d2499f860e07a0b6e592 | e1f69a097928c367042192619183d7445de90d85 | refs/heads/master | 2020-04-23T02:29:53.957543 | 2017-02-17T10:33:25 | 2017-02-17T10:33:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,297 | h | AssemblyU2DCSharp_Org_BouncyCastle_Crypto_Prng_Cryp405007133.h | #pragma once
#include "il2cpp-config.h"
#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif
#include <stdint.h>
// System.Security.Cryptography.RandomNumberGenerator
struct RandomNumberGenerator_t2510243513;
#include "mscorlib_System_Object2689449295.h"
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// Org.BouncyCastle.Crypto.Prng.CryptoApiRandomGenerator
struct CryptoApiRandomGenerator_t405007133 : public Il2CppObject
{
public:
// System.Security.Cryptography.RandomNumberGenerator Org.BouncyCastle.Crypto.Prng.CryptoApiRandomGenerator::rndProv
RandomNumberGenerator_t2510243513 * ___rndProv_0;
public:
inline static int32_t get_offset_of_rndProv_0() { return static_cast<int32_t>(offsetof(CryptoApiRandomGenerator_t405007133, ___rndProv_0)); }
inline RandomNumberGenerator_t2510243513 * get_rndProv_0() const { return ___rndProv_0; }
inline RandomNumberGenerator_t2510243513 ** get_address_of_rndProv_0() { return &___rndProv_0; }
inline void set_rndProv_0(RandomNumberGenerator_t2510243513 * value)
{
___rndProv_0 = value;
Il2CppCodeGenWriteBarrier(&___rndProv_0, value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
|
e62fc492ae7f61b033db0b3da57098b3f6b45bdf | 9488e43858db0a0a49d4e75e2a9520770dd3aa11 | /TemplateDeepPractice/2-2_templateClass/classtemplate.hpp | 41306546b5b292b4db1f5f1d8ea461c21034fd50 | [] | no_license | quantity123/CppExamples | 32884c20de5c31f7e57bf16a586ae57f2147fead | e1591a974fc38fbd4c3844a45595e5fd3770027f | refs/heads/master | 2022-11-23T18:16:24.773387 | 2020-07-30T18:51:11 | 2020-07-30T18:51:11 | 283,847,222 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 386 | hpp | classtemplate.hpp | #ifndef CLASSTEMPLATE_H
#define CLASSTEMPLATE_H
template<typename T0>
class ClassTemplate
{
public:
T0 mV;
template<typename T1>
void set(const T1& v)
{
mV = T0(v);
}
template<typename T1>
const T1 get() const;
};
template<typename T0> template<typename T1>
const T1 ClassTemplate<T0>::get() const
{
return T1(mV);
}
#endif // CLASSTEMPLATE_H
|
29b10ec210d1f83a13fd72cd79ca6c30cf25fd81 | e109ba6a36a9ab8422bcc98dfcf225409285fb20 | /ALICE_PLATFORM/src/userSrc/references_alice/sketch_HEMesh_test.cpp | ad92175d7e882628aad489d4a6f5e395238653fd | [] | no_license | Leo-Bieling/Alice | d636ee07628d43acaa8a7e285af8b3437f44b9c3 | a731ef0cf3793c1280b67f66b90a089ae9a93a79 | refs/heads/master | 2022-03-07T20:09:18.804148 | 2019-11-15T18:56:39 | 2019-11-15T18:56:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,995 | cpp | sketch_HEMesh_test.cpp | #define _MAIN_
#ifdef _MAIN_
#include "main.h"
#include "ALICE_ROBOT_DLL.h"
using namespace ROBOTICS;
#include <array>
#include <memory>
#include<time.h>
//#include<experimental/generator>
//using namespace std;
//using namespace std::experimental;
using namespace std;
class HalfVert;
class HalfEdge;
class HalfFace;
class HalfEdge
{
public:
HalfVert *ve;
HalfEdge *twin;
HalfEdge *next;
HalfFace *f;
};
class HalfVert
{
public:
HalfEdge he;
};
class HalfFace
{
public:
HalfEdge *e;
};
const int HE_MAX = 60000;
const int HV_MAX = 60000;
const int HF_MAX = 60000;
class HEMesh
{
public:
array<vec, HV_MAX> positions;
array<HalfEdge, HE_MAX> HE;
array<HalfVert, HV_MAX> HV;
array<HalfFace, HF_MAX> HF;
};
void timeStats(long &strt, long& end, string str)
{
elapsedTime = end - strt;
cout << elapsedTime / 1000.0f << " - " << str << endl;
}
const int sz = 200000;
//array<vec, sz> A;
//array<vec, sz> B;
void setup()
{
//cout << sizeof(HalfVert) << endl;
//cout << sizeof(HalfEdge) << endl;
//cout << sizeof(HalfFace) << endl;
//cout << float(sizeof(HEMesh)) / (1024.0 * 1024.0) << endl;
//HEMesh M;
vec *AA = new vec[sz];
vec *BB = new vec[sz];
cout << float(sizeof(vec)) * sz / (1024.0 * 1024.0) << endl;
long start, end;
//start = GetTickCount();;
//for( auto &a: A)
// for (auto &b : B)
// double d = a*(b);
//end = GetTickCount();
//timeStats(start, end, " n-n distance check static array L1 , object field method : a.distanceTo(b) , store results ");
////
start = GetTickCount();;
for (int i = 0; i < sz; i++)
for (int j = 0; j < sz; j++)
double d = AA[i]*(BB[j]);
end = GetTickCount();
timeStats(start, end, " n-n distance check dyn array, object field method : a.distanceTo(b) , store results ");
}
void update(int value)
{
}
void draw()
{
backGround(0.75);
}
void keyPress(unsigned char k, int xm, int ym)
{
}
void mousePress(int b, int state, int x, int y)
{
}
void mouseMotion(int x, int y)
{
}
#endif
|
e67148645336bf828729062551ae58ab7d160cf2 | 72b94050c7c4ee1231c93099e277ea5f565e1e77 | /Sender.h | 630360d324882118df36a78e26070c23cb871081 | [
"MIT"
] | permissive | JoseTomasTocino/ClipboardFileTransfer | cab737478f45b897d89247511556e6cf15f10bdd | 8ae7876163f82514197dd95a2e1a5a6fcb3b6cf5 | refs/heads/master | 2022-12-15T09:11:23.377827 | 2020-09-19T00:04:36 | 2020-09-19T00:04:36 | 296,751,380 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 824 | h | Sender.h | #ifndef SENDER_H
#define SENDER_H
#include <QClipboard>
#include <QFile>
#include <QObject>
#include <QWidget>
#include "State.h"
class Sender : public QObject
{
Q_OBJECT
public:
explicit Sender(QWidget * parent = nullptr);
void start(QWidget * parent);
signals:
void status(const QString & message);
void progress(quint16 current, quint16 total);
void finishedSending();
private slots:
void clipboardDataChanged();
private:
void handleState();
void sendCurrentChunk();
QWidget * mParentWindow = nullptr;
QClipboard * mClipboard = nullptr;
State mState = State::Initial;
QFile mTheFile;
quint64 mBytesTotal = 0;
quint64 mBytesSent = 0;
quint16 mChunkSize = 1024 * 10;
quint16 mChunkCount = 0;
quint16 mCurrentChunk = 0;
};
#endif // SENDER_H
|
9e37eeeb6117a936119dd5cc67274ee817d968e3 | 42ca9829beb02b7d3d820df4c8e642aa17379ae6 | /code/TaskingGameEngineAnimation_2012/SampleComponents/DebugGraphics.cpp | fca7e386ed5250711ae8796b5267550093e7c196 | [] | no_license | pzxbc/job-system-learn | 93b7cd3bd5d55f702a026616e4f58cfa8572dd26 | a03f7e9f46b757323115e89f8fecd7d33e8bdade | refs/heads/master | 2022-12-19T16:33:26.626212 | 2020-10-23T12:53:23 | 2020-10-23T12:53:23 | 306,620,618 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,038 | cpp | DebugGraphics.cpp | //#include "stdafx.h"
// #include "Particle_common.h"
//#include "D3DX11.h"
//#include "D3D11.h"
// use this macro to silence compiler warning C4100 "unreferenced formal parameter"
#define UNREF_PARAM( param_ ) static_cast<void>( param_ )
#include "DXUT.h"
#include "d3dx11effect.h"
#include "DebugGraphics.h"
#include "SDKmisc.h"
#ifdef ENABLE_DEBUG_GRAPHICS
HRESULT CreateEffectFromFile( const wchar_t* fxFile, ID3D11Device* pd3dDevice, const D3D10_SHADER_MACRO* pDefines, DWORD dwShaderFlags, ID3DX11Effect** ppEffect );
#define VERIFY(x)
// TODO: move to static class members (instead of globals)
bool gEnableDebugInfo = true;
#define MAX_THREADS 4
int gCurrentDebugFrameIndex = 0;
int gLastDebugFrame = 0;
LONG gDebugGraphicsIndex[NUM_DEBUG_FRAMES] = {-1,-1};
UINT gDebugGraphicsColor[NUM_DEBUG_FRAMES][MAX_DEBUG_GRAPHICS_TIME_ENTRIES];
UINT gDebugGraphicsThreadIndex[NUM_DEBUG_FRAMES][MAX_DEBUG_GRAPHICS_TIME_ENTRIES];
char *gDebugGraphicsName[NUM_DEBUG_FRAMES][MAX_DEBUG_GRAPHICS_TIME_ENTRIES];
LARGE_INTEGER gDebugGraphicsStartTime[NUM_DEBUG_FRAMES][MAX_DEBUG_GRAPHICS_TIME_ENTRIES];
LARGE_INTEGER gDebugGraphicsEndTime[NUM_DEBUG_FRAMES][MAX_DEBUG_GRAPHICS_TIME_ENTRIES];
LONG glDebugStartIdx[ MAX_THREADS ];
LONG glDebugEndIdx[ MAX_THREADS ];
LONG glDebugDepth[ MAX_THREADS ];
LARGE_INTEGER gllDebugStartTime[ MAX_THREADS ][ MAX_DEBUG_GRAPHICS_TIME_ENTRIES ];
LARGE_INTEGER gllDebugEndTime[ MAX_THREADS ][ MAX_DEBUG_GRAPHICS_TIME_ENTRIES ];
DWORD gldwCPU[ MAX_THREADS ][ MAX_DEBUG_GRAPHICS_TIME_ENTRIES ];
// TODO: move all this sprite stuff to a sprite class. And, use that also for render targets, etc...
ID3DX11Effect *gpSpriteD3dEffect = NULL;
ID3DX11EffectTechnique *gpSpriteTechnique = NULL;
ID3D11InputLayout *gpSpriteInputLayout = NULL;
ID3D11Buffer *gpSpriteVertexBuffer = NULL;
// ***********************************************
class SpriteVertex
{
public:
float mpPos[3];
DWORD mColor;
};
// ***********************************************
int StartDebugMeter( UINT uContext, UINT color, char *pName )
{
UNREF_PARAM( pName );
if( !gEnableDebugInfo )
{
return 0;
}
// int index = ++gDebugGraphicsIndex;
DWORD dwCPU = GetCurrentProcessorNumber();
LONG index = glDebugStartIdx[ uContext ]++;
index &= ( MAX_DEBUG_GRAPHICS_TIME_ENTRIES - 1 );
QueryPerformanceCounter( &gllDebugStartTime[ uContext ][ index ] );
gldwCPU[ uContext ][ index ] = dwCPU;
return index;
}
// ***********************************************
void EndDebugMeter( UINT uContext, int index )
{
if( !gEnableDebugInfo )
{
return;
}
LONG index = glDebugEndIdx[ uContext ]++;
index &= ( MAX_DEBUG_GRAPHICS_TIME_ENTRIES - 1 );
QueryPerformanceCounter( &gllDebugEndTime[ uContext ][ index ] );
}
// ***********************************************
void DrawDebugGraphics()
{
if( !gEnableDebugInfo )
{
return;
}
// previous render state
static LONG slPrevDebugEndIdx[ MAX_THREADS ];
LONG lCurrDebugEndIdx[ MAX_THREADS ];
static bool sbFirst = true;
if( sbFirst )
{
memset( slPrevDebugEndIdx, 0, sizeof( slPrevDebugEndIdx ) );
memset( lCurrDebugEndIdx, 0, sizeof( lCurrDebugEndIdx ) );
sbFirst = false;
}
__int64 frameStartTime = LLONG_MAX;
__int64 frameEndTime = 0;
for( UINT uIdx = 0; uIdx < MAX_THREADS; ++uIdx )
{
// read start then end for each thread
lCurrDebugEndIdx[ uIdx ] = glDebugEndIdx[ uIdx ] & (MAX_DEBUG_GRAPHICS_TIME_ENTRIES-1);
LONG lDbgEndIdx = lCurrDebugEndIdx[ uIdx ];
LONG lDbgStartIdx = slPrevDebugEndIdx[ uIdx ];
if( gllDebugStartTime[ uIdx ][ lDbgStartIdx ].QuadPart < frameStartTime )
{
frameStartTime = gllDebugStartTime[ uIdx ][ lDbgStartIdx ].QuadPart;
}
if( gllDebugEndTime[ uIdx ][ lDbgEndIdx ].QuadPart > frameEndTime )
{
frameEndTime = gllDebugEndTime[ uIdx ][ lDbgEndIdx ].QuadPart;
}
}
// read current
ID3D11Device* pd3dDevice = DXUTGetD3D11Device();
ID3D11DeviceContext* pd3dImmediateContext = DXUTGetD3D11DeviceContext();
HRESULT hr;
if( !gpSpriteD3dEffect )
{
V( CreateEffectFromFile( L"UI\\SolidColorSprite.fx", pd3dDevice, NULL, 0, &gpSpriteD3dEffect ) );
gpSpriteTechnique = gpSpriteD3dEffect->GetTechniqueByName( "TransformAndTexture" );
// Define the input layout
D3D11_INPUT_ELEMENT_DESC layout[] =
{
{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 }
};
UINT numElements = sizeof( layout ) / sizeof( layout[0] );
// Create the input layout
D3DX11_PASS_DESC PassDesc;
gpSpriteTechnique->GetPassByIndex( 0 )->GetDesc( &PassDesc );
hr = pd3dDevice->CreateInputLayout(
layout,
numElements,
PassDesc.pIAInputSignature,
PassDesc.IAInputSignatureSize,
&gpSpriteInputLayout
);
VERIFY(hr);
// ***************************************************
// Create Vertex Buffers
// ***************************************************
D3D11_BUFFER_DESC bd;
bd.Usage = D3D11_USAGE_DYNAMIC;
bd.ByteWidth = sizeof(SpriteVertex) * 6 * MAX_DEBUG_GRAPHICS_TIME_ENTRIES; // 2 tris, 3 verts each vertices * max entries
bd.BindFlags = D3D11_BIND_VERTEX_BUFFER;
bd.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
bd.MiscFlags = 0;
hr = pd3dDevice->CreateBuffer( &bd, NULL, &gpSpriteVertexBuffer );
VERIFY(hr);
}
SYSTEM_INFO info;
GetSystemInfo( &info );
DWORD numProcessors = MAX_THREADS;//info.dwNumberOfProcessors;
double totalTime = (double)(frameEndTime - frameStartTime);
float pPos[6][3] = { {0.0f,0.0f,0.5f}, {1.0f,0.0f,0.5f}, {0.0f,1.0f,0.5f}, {1.0f,0.0f,0.5f}, {1.0f,1.0f,0.5f}, {0.0f,1.0f,0.5f} };
D3D11_MAPPED_SUBRESOURCE pTempData;
V( pd3dImmediateContext->Map( gpSpriteVertexBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &pTempData ) );
SpriteVertex *pData = (SpriteVertex*)pTempData.pData;
const DWORD guideColors[2] = {0x80808080, 0x80FFFFFF }; // ABGR
const float viewportStartX = 0.1f, viewportStartY = 0.7f, viewportWidth = 0.8f, viewportHeight = 0.2f;
// Draw debug overlay guides
int ii;
for( ii=0; ii<(int)numProcessors; ii++ )
{
DWORD color = guideColors[ii%2];
for( UINT vv=0; vv<6; vv++ )
{
pData->mpPos[0] = (pPos[vv][0] * viewportWidth + viewportStartX) * 2.0f - 1.0f; // X position
pData->mpPos[1] = ((ii + pPos[vv][1])/(float)numProcessors * viewportHeight + viewportStartY) * -2.0f + 1.0f; // Y position
pData->mpPos[2] = pPos[vv][2]; // Z position
pData->mColor = color;
pData++;
}
}
for( UINT uProcessor = 0; uProcessor < numProcessors; ++uProcessor )
{
UINT uCount;
if( slPrevDebugEndIdx[ uProcessor ] > lCurrDebugEndIdx[ uProcessor ] )
{
uCount = MAX_DEBUG_GRAPHICS_TIME_ENTRIES - slPrevDebugEndIdx[ uProcessor ] + slPrevDebugEndIdx[ uProcessor ];
}
else
{
uCount = lCurrDebugEndIdx[ uProcessor ] - slPrevDebugEndIdx[ uProcessor ];
}
for( ii=0; ii<=gDebugGraphicsIndex[gLastDebugFrame]; ii++ )
{
__int64 meterStartTime = gDebugGraphicsStartTime[gLastDebugFrame][ii].QuadPart;
__int64 meterEndTime = gDebugGraphicsEndTime[gLastDebugFrame][ii].QuadPart;
double deltaTime = (double)(meterEndTime - meterStartTime);
float processor = (float)uProcessor;
for( UINT vv=0; vv<6; vv++ )
{
pData->mpPos[0] = (float)((double)(((meterStartTime-frameStartTime) + pPos[vv][0]*deltaTime)/totalTime * viewportWidth + viewportStartX) * 2.0f - 1.0f); // X position
pData->mpPos[1] = ((processor + pPos[vv][1])/(float)numProcessors * viewportHeight + viewportStartY) * -2.0f + 1.0f; // Y position
pData->mpPos[2] = pPos[vv][2]; // Z position
pData->mColor = gDebugGraphicsColor[gLastDebugFrame][ii];
pData++;
}
}
}
pd3dImmediateContext->Unmap( gpSpriteVertexBuffer, 0 );
UINT stride = sizeof( SpriteVertex );
UINT offset = 0;
pd3dImmediateContext->IASetVertexBuffers( 0, 1, &gpSpriteVertexBuffer, &stride, &offset );
pd3dImmediateContext->IASetInputLayout( gpSpriteInputLayout );
pd3dImmediateContext->IASetPrimitiveTopology( D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST );
D3DX11_TECHNIQUE_DESC techDesc;
gpSpriteTechnique->GetDesc( &techDesc );
for( UINT pp = 0; pp < techDesc.Passes; ++pp )
{
gpSpriteTechnique->GetPassByIndex( pp )->Apply( 0, pd3dImmediateContext );
pd3dImmediateContext->Draw( 6 * (gDebugGraphicsIndex[gLastDebugFrame]+1) + 6*numProcessors, 0 );
}
static int count = 0;
if( count++ % 1000 == 0 )
{
LARGE_INTEGER qpfreq;
QueryPerformanceFrequency(&qpfreq);
for( UINT tt=0; tt<nextTotalTimeIndex; tt++ )
{
char tmp[1024];
sprintf( tmp, "%4.2f, %s (note: not normalized for core count)\n", 1000.0f * (accumulatedTime[tt]/qpfreq.QuadPart), pNames[tt] );
OutputDebugStringA( tmp );
}
}
}
// ***********************************************
void ResetDebugGraphics()
{
memset( glDebugStartIdx, 0x0, sizeof( glDebugStartIdx ) );
memset( glDebugEndIdx, 0x0, sizeof( glDebugEndIdx ) );
memset( glDebugDepth, 0x0, sizeof( glDebugDepth ) );
memset( gllDebugStartTime, 0x0, sizeof( gllDebugStartTime ) );
memset( gllDebugEndTime, 0x0, sizeof( gllDebugEndTime ) );
gLastDebugFrame = gCurrentDebugFrameIndex;
gCurrentDebugFrameIndex = (gCurrentDebugFrameIndex+1) % NUM_DEBUG_FRAMES;
gDebugGraphicsIndex[gCurrentDebugFrameIndex] = -1;
int meter = StartDebugMeter( gCurrentDebugFrameIndex, 0 );
EndDebugMeter( gCurrentDebugFrameIndex, meter);
}
// ***********************************************
void DestroyDebugGraphics()
{
SAFE_RELEASE( gpSpriteD3dEffect );
SAFE_RELEASE( gpSpriteInputLayout );
SAFE_RELEASE( gpSpriteVertexBuffer );
}
//-----------------------------------------------------------------------------
// CreateEffectFromFile()
//-----------------------------------------------------------------------------
HRESULT CreateEffectFromFile( const wchar_t* fxFile, ID3D11Device* pd3dDevice, const D3D10_SHADER_MACRO* pDefines, DWORD dwShaderFlags, ID3DX11Effect** ppEffect )
{
assert( fxFile );
assert( pd3dDevice );
assert( ppEffect );
HRESULT hr;
WCHAR str[MAX_PATH];
V_RETURN( DXUTFindDXSDKMediaFileCch( str, MAX_PATH, fxFile ) );
ID3D10Blob *pBuffer = NULL;
ID3D10Blob *pError = NULL;
hr = D3DX11CompileFromFile( str, pDefines, NULL, NULL, "fx_5_0", dwShaderFlags, 0, NULL, &pBuffer, &pError, NULL );
if( FAILED( hr ) )
{
// Print the error to the debug-output window.
char *pErrorMsg = (char*)pBuffer->GetBufferPointer();
// Display the error in a message box.
wchar_t msg[ 4096 ];
int nChars = swprintf_s( msg, L"Error loading effect '%s':\n ", str );
// pError is a multi-byte string. Convert and write it to the wide character msg string.
mbstowcs_s( NULL, msg + nChars, _countof( msg ) - nChars, pErrorMsg, _TRUNCATE );
wcscat_s( msg, L"\n" );
MessageBox( NULL, msg, L"Error", NULL );
pBuffer->Release();
return hr;
}
V_RETURN( D3DX11CreateEffectFromMemory( pBuffer->GetBufferPointer(), pBuffer->GetBufferSize(), 0, pd3dDevice, ppEffect ) );
return S_OK;
}
#endif // ENABLE_DEBUG_GRAPHICS
|
bcba540beb5709e27ee931f55f0db1fcb336d729 | 4f0757f0c1116d8e3fdcdd4e1938a560fbe83eb8 | /src/Core/BomberGame.cpp | 0dc79f97cd254bf180dd847c82e97795bf73e433 | [] | no_license | jlouazel/bomberman | da07602ba5a64ab363e405c0de1fef8bb89b1aea | 4d59ae333570bef1cd1b03a440e0a5ba4e6f71bd | refs/heads/master | 2016-09-05T17:15:30.311236 | 2013-06-09T21:41:13 | 2013-06-09T21:41:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 32,778 | cpp | BomberGame.cpp | #include <iostream>
#include <sstream>
#include "BomberOptions.hh"
#include <ctime>
#include <unistd.h>
#include <fmod.h>
#include <fstream>
#include <Input.hpp>
#include <Clock.hpp>
#include <GameClock.hpp>
#include "EndOfBomberMan.hh"
#include "SoundManager.hh"
#include "Texture3d.hpp"
#include "Texture2d.hpp"
#include "BomberGame.hh"
#include "Player.hh"
#include "Enums.hh"
#include "Gif.hpp"
#include "Xml.hh"
#include "Wall.hh"
#include "Gif.hpp"
#include "Xml.hh"
#include "MyGame.hpp"
#include "EventManager.hh"
#include "EventEnum.hh"
#include "Action.hh"
#include "Pause.hh"
#include "Text.hpp"
#include <iostream>
#include <sstream>
#include <unistd.h>
namespace BomberMan
{
namespace Core
{
BomberGame::BomberGame(bool cont, const std::string &file)
{
this->_loading = true;
Sound::SoundManager::getInstance()->stopSound("./resources/sounds/musicIntro2.mp3");
Sound::SoundManager::getInstance()->playSound("./resources/sounds/ambianceGame.mp3", true);
if (cont)
this->load(file);
else
this->_manager = new Field::Manager;
int LightPos[4] = {0,0,3,1};
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glLightiv(GL_LIGHT0,GL_POSITION,LightPos);
Display::Vector3f vectorPosition(0, 0.0, 0);
Display::Vector3f vectorLen(0.0, 0.0, 0.0);
Display::Vector3f vectorRot(0.0, 0.0, 0.0);
// this->_players.push_front(new Field::Player(0, 100, 10, 1, 0, 0, 0, new Display::Texture3d("models/WWunmoved.fbx", vectorPosition, vectorRot, vectorLen), 0, 0));
// this->_manager->randomize(this->_players);
// std::list<Field::Player *>::iterator it = this->_players.begin();
// for (; it != this->_players.end(); ++it)
BomberOptions::getOptions()->getNbPlayer();
BomberOptions::getOptions()->getNbIA();
this->_players.push_back(new Field::Player(0, 100, 10, 1, 0, this->_manager->getWidth(), 0, new Display::Texture3d("models/WWunmoved.fbx", vectorPosition, vectorRot, vectorLen), 0, 0, 0, 0, 255));
this->_players.back()->setCamera(new Display::Camera(BomberOptions::getOptions()->getNbPlayer()));
if (BomberOptions::getOptions()->getNbPlayer() == 2)
{
this->_players.push_back(new Field::Player(1, 100, 10, 1, 0, 0, 0, new Display::Texture3d("models/WWunmoved.fbx", vectorPosition, vectorRot, vectorLen), 0, 0, 255, 0, 0));
this->_players.back()->setCamera(new Display::Camera(BomberOptions::getOptions()->getNbPlayer()));
}
for (unsigned int i = 1; i <= BomberOptions::getOptions()->getNbIA(); ++i)
{
this->_players.push_back(new Field::Player(i + 1, 100, 10, 1, 0, 0, 0, new Display::Texture3d("models/WWunmoved.fbx", vectorPosition, vectorRot, vectorLen), 0, 0, rand() % 255, rand() % 255, rand() % 255));
this->_players.back()->startIA(this->_manager->getWidth(), this->_manager->getHeight(), this->_manager->getMap(), this->_players);
std::cout << "IA : "<< i << " is ready" << std::endl;
}
this->_manager->randomize(this->_players);
std::list<Field::Player *>::iterator it = this->_players.begin();
for (; it != this->_players.end(); ++it)
(*it)->initialize();
Display::Vector3f vectorPosition_(0, 0, 0);
Display::Vector3f vectorLen_(1.5, 2, 0.0);
Display::Vector3f vectorRot_(0.0, 0.0, 0.0);
Display::Vector3f vectorPosition2_(0, 70, 0);
Display::Vector3f vectorLen2_(20, 40, 0.0);
Display::Vector3f vectorPosition3_(20, 75, 0);
Display::Vector3f vectorLen3_(5, 10, 0.0);
Display::Vector3f vectorPosition4_(20, 85, 0);
Display::Vector3f vectorLen4_(5, 5, 0.0);
this->_infos["barrel"] = new Display::Texture2d("images/MMbarrel.png", vectorPosition_, vectorRot_, vectorLen_);
this->_infos["barrel"]->initialize();
this->_infos["wall"] = new Display::Texture2d("images/MMcuve.png", vectorPosition_, vectorRot_, vectorLen_);
this->_infos["wall"]->initialize();
this->_infos["floor"] = new Display::Texture2d("images/MMfloor.png", vectorPosition_, vectorRot_, vectorLen_);
this->_infos["floor"]->initialize();
this->_infos["player"] = new Display::Texture2d("images/MMplayer.png", vectorPosition_, vectorRot_, vectorLen_);
this->_infos["player"]->initialize();
this->_infos["walter"] = new Display::Texture2d("images/WWmenu.png", vectorPosition2_, vectorRot_, vectorLen2_);
this->_infos["walter"]->initialize();
this->_infos["jesse"] = new Display::Texture2d("images/JPmenu.png", vectorPosition2_, vectorRot_, vectorLen2_);
this->_infos["jesse"]->initialize();
this->_infos["fiole0"] = new Display::Texture2d("images/Fiole0.png", vectorPosition3_, vectorRot_, vectorLen3_);
this->_infos["fiole0"]->initialize();
this->_infos["fiole10"] = new Display::Texture2d("images/Fiole10.png", vectorPosition3_, vectorRot_, vectorLen3_);
this->_infos["fiole10"]->initialize();
this->_infos["fiole20"] = new Display::Texture2d("images/Fiole20.png", vectorPosition3_, vectorRot_, vectorLen3_);
this->_infos["fiole20"]->initialize();
this->_infos["fiole30"] = new Display::Texture2d("images/Fiole30.png", vectorPosition3_, vectorRot_, vectorLen3_);
this->_infos["fiole30"]->initialize();
this->_infos["fiole40"] = new Display::Texture2d("images/Fiole40.png", vectorPosition3_, vectorRot_, vectorLen3_);
this->_infos["fiole40"]->initialize();
this->_infos["fiole50"] = new Display::Texture2d("images/Fiole50.png", vectorPosition3_, vectorRot_, vectorLen3_);
this->_infos["fiole50"]->initialize();
this->_infos["fiole60"] = new Display::Texture2d("images/Fiole60.png", vectorPosition3_, vectorRot_, vectorLen3_);
this->_infos["fiole60"]->initialize();
this->_infos["fiole70"] = new Display::Texture2d("images/Fiole70.png", vectorPosition3_, vectorRot_, vectorLen3_);
this->_infos["fiole70"]->initialize();
this->_infos["fiole80"] = new Display::Texture2d("images/Fiole80.png", vectorPosition3_, vectorRot_, vectorLen3_);
this->_infos["fiole80"]->initialize();
this->_infos["fiole90"] = new Display::Texture2d("images/Fiole90.png", vectorPosition3_, vectorRot_, vectorLen3_);
this->_infos["fiole90"]->initialize();
this->_infos["fiole100"] = new Display::Texture2d("images/Fiole100.png", vectorPosition3_, vectorRot_, vectorLen3_);
this->_infos["fiole100"]->initialize();
vectorPosition3_.setX(0);
vectorPosition3_.setY(0);
vectorLen3_.setX(100);
vectorLen3_.setY(100);
this->_infos["background"] = new Display::Texture2d("images/black.png", vectorPosition3_, vectorRot_, vectorLen3_);
this->_infos["background"]->initialize();
this->_infos["clean"] = new Display::Texture2d("images/BlackFond.png", vectorPosition3_, vectorRot_, vectorLen3_);
this->_infos["clean"]->initialize();
vectorPosition3_.setX(25);
vectorPosition3_.setY(0);
vectorLen3_.setX(50);
vectorLen3_.setY(100);
this->_infos["lose1"] = new Display::Texture2d("images/YouAreDead.png", vectorPosition3_, vectorRot_, vectorLen3_);
this->_infos["lose1"]->initialize();
this->_infos["win1"] = new Display::Texture2d("images/YouWin.png", vectorPosition3_, vectorRot_, vectorLen3_);
this->_infos["win1"]->initialize();
this->_infos["lose2"] = new Display::Texture2d("images/YouAreDead.png", vectorPosition3_, vectorRot_, vectorLen3_);
this->_infos["lose2"]->initialize();
this->_infos["win2"] = new Display::Texture2d("images/YouWin.png", vectorPosition3_, vectorRot_, vectorLen3_);
this->_infos["win2"]->initialize();
this->_infos["bomb"] = new Display::Texture2d("images/Bomb.png", vectorPosition4_, vectorRot_, vectorLen4_);
this->_infos["bomb"]->initialize();
this->_loading = false;
this->_clock = new gdl::Clock();
this->_clock->play();
this->_fps = 30;
this->_constElapsedTime = 1.0 / static_cast<float>(this->_fps);
}
BomberGame::~BomberGame()
{
}
static void updateObjs(Field::IGameComponent * comp, gdl::GameClock const & gameClock, Field::Manager *manager)
{
comp->update(gameClock, manager);
}
bool BomberGame::isLoaded() const
{
return !this->_loading;
}
void BomberGame::update(gdl::GameClock const & gameClock)
{
this->_clock->update();
static int i = 0;
if (i++ == 0)
{
//this->save();
}
for (unsigned int y = 0; y != this->getManager()->Field::Manager::getHeight(); y++)
for (unsigned int x = 0; x != this->getManager()->Field::Manager::getWidth(); x++)
{
for (std::list<Field::IGameComponent *>::iterator it = this->getManager()->Field::Manager::get(x, y).begin(); it != this->getManager()->Field::Manager::get(x, y).end(); ++it)
{
if ((*it)->isEnd() == true)
{
if (dynamic_cast<Field::Wall *>(*it) == *it)
{
Field::Wall *actualWall = static_cast<Field::Wall *>(*it);
Field::Object *buff = actualWall->getContent();
if (buff)
this->_manager->get(x, y).insert(it, buff);
int idPlayer = actualWall->getWhoDestroyedMe();
for (std::list<Field::Player *>::iterator it = this->_players.begin(); it != this->_players.end(); ++it)
if ((*it)->getId() == idPlayer)
(*it)->setNbCaisseDestroyed((*it)->getNbCaisseDestroyed() + 1);
}
it = this->_manager->get(x, y).erase(it);
}
else
updateObjs(*it, gameClock, this->_manager);
}
}
for (std::list<Field::Player *>::iterator it = this->_players.begin(); it != this->_players.end(); ++it)
updateObjs(*it, gameClock, this->_manager);
this->eventPlayer();
}
void BomberGame::eventPlayer()
{
int id;
const Event::IEvent* event;
int i = 0;
while ((event = Event::EventManager::getEvent()) != NULL)
{
id = event->getPlayerId();
Field::Player *actualPlayer = 0;
for (std::list<Field::Player *>::iterator it = this->_players.begin(); it != this->_players.end(); ++it)
if ((*it)->getId() == id)
actualPlayer = (*it);
if (dynamic_cast<const Event::Pause *>(event) == event)
event->interaction(this->checkIfEnd());
else if (actualPlayer && dynamic_cast<const Event::Move *>(event) == event && actualPlayer->getMoveOk() == false && actualPlayer->getPv() > 0)
{
const Event::Move *move = dynamic_cast<const Event::Move *>(event);
actualPlayer->setIsRunning(move->isRunning());
actualPlayer->setIsMoving(true);
i++;
float angle = move->getAngle() * 3.14159 / 180.0;
float x = -(cosf(angle) * actualPlayer->getSpeed());
float z = sinf(angle) * actualPlayer->getSpeed();
if (actualPlayer->checkMyMove(actualPlayer->getAsset()->getPosition().getZ() + z, actualPlayer->getAsset()->getPosition().getX() + x, this->_manager) == true)
actualPlayer->move(x, z, angle, this->_manager);
else
{
if (actualPlayer->checkMyMove(actualPlayer->getAsset()->getPosition().getZ(), actualPlayer->getAsset()->getPosition().getX() + x, this->_manager) == true)
actualPlayer->move(x, 0, angle, this->_manager);
else if (actualPlayer->checkMyMove(actualPlayer->getAsset()->getPosition().getZ() + z, actualPlayer->getAsset()->getPosition().getX(), this->_manager) == true)
actualPlayer->move(0, z, angle, this->_manager);
}
actualPlayer->setMoveOk(true);
}
else if (actualPlayer && dynamic_cast<const Event::Action *>(event) == event && actualPlayer->getNbBombSet() < actualPlayer->getNbBombMax() && actualPlayer->getPv() > 0)
actualPlayer->setBomb(this->_manager);
// if (actualPlayer && actualPlayer->getPv() <= 0)
// {
// }
delete event;
}
for (std::list<Field::Player *>::iterator it = this->_players.begin(); it != this->_players.end(); ++it)
{
if ((*it)->getMoveOk() == false)
{
(*it)->setIsMoving(false);
(*it)->setIsRunning(false);
}
}
}
static void affObjs(Field::IGameComponent * comp, gdl::GameClock const & gameClock)
{
comp->draw(gameClock);
}
bool BomberGame::checkIfEnd() const
{
int i = 0;
for (std::list<Field::Player *>::const_iterator it = this->_players.begin(); it != this->_players.end(); ++it)
if ((*it)->getPv() > 0)
i++;
return i > 1 ? false : true;
}
bool BomberGame::checkIfIWin(int id_player) const
{
for (std::list<Field::Player *>::const_iterator it = this->_players.begin(); it != this->_players.end(); ++it)
if ((*it)->getId() != id_player && (*it)->getPv() > 0)
return (false);
return (true);
}
void BomberGame::drawForPlayer2D(gdl::GameClock const &, int id_player) const
{
this->_infos.at("background")->draw();
float startx = 88;
float starty = 85;
Field::Player * player = 0;
for (std::list<Field::Player *>::const_iterator it = this->_players.begin(); it != this->_players.end(); ++it)
if ((*it)->getId() == id_player)
player = (*it);
if (player == 0)
return;
if (this->checkIfIWin(id_player) == true)
{
this->_infos.at("clean")->draw();
if (id_player == 0)
this->_infos.at("win1")->draw();
else if (id_player == 1)
this->_infos.at("win2")->draw();
}
if (player->getRealDead() == true)
{
this->_infos.at("clean")->draw();
if (id_player == 0)
this->_infos.at("lose1")->draw();
else if (id_player == 1)
this->_infos.at("lose2")->draw();
}
for (int y = -5; y != 5; y++)
{
for (int x = -5; x != 5; x++)
{
Field::Player * tmp = this->getPlayers().front();
unsigned int real_y = static_cast<int>(((tmp->getY() - 110) / 220) + 1) + y;
unsigned int real_x = static_cast<int>(((tmp->getX() - 110) / 220) + 1) + x;
if (real_y < this->getManager()->Field::Manager::getHeight() && real_x < this->getManager()->Field::Manager::getWidth())
{
int imp = 0;
for (std::list<Field::IGameComponent *>::iterator it = this->getManager()->Field::Manager::get(real_y, real_x).begin(); it != this->getManager()->Field::Manager::get(real_y, real_x).end(); ++it)
{
Display::Vector3f newPosition(startx + y * 1.5, starty - x * 2 ,0);
if (dynamic_cast<Field::Wall *>(*it) == *it)
{
Field::Wall * tmp = static_cast<Field::Wall *>(*it);
if (tmp->isBreakable())
{
this->_infos.at("barrel")->setPosition(newPosition);
this->_infos.at("barrel")->draw();
}
else
{
this->_infos.at("wall")->setPosition(newPosition);
this->_infos.at("wall")->draw();
}
imp = 1;
}
else if (!imp)
{
this->_infos.at("floor")->setPosition(newPosition);
this->_infos.at("floor")->draw();
}
}
}
}
}
Display::Vector3f newPosition2(startx, starty, 0);
this->_infos.at("player")->setPosition(newPosition2);
this->_infos.at("player")->draw();
// if (BomberOptions::getOptions()->getSkinForPlayer(player->getId()) == BomberOptions::WW)
// this->_infos.at("walter")->draw();
// else
this->_infos.at("jesse")->draw();
if (BomberOptions::getOptions()->getSkinForPlayer(player->getId()) == BomberOptions::WW)
this->_infos.at("walter")->draw();
else
this->_infos.at("jesse")->draw();
switch (player->getPv())
{
case (0):
{
this->_infos.at("fiole0")->draw();
break;
}
case (10):
{
this->_infos.at("fiole10")->draw();
break;
}
case (20):
{
this->_infos.at("fiole20")->draw();
break;
}
case (30):
{
this->_infos.at("fiole30")->draw();
break;
}
case (40):
{
this->_infos.at("fiole40")->draw();
break;
}
case (50):
{
this->_infos.at("fiole50")->draw();
break;
}
case (60):
{
this->_infos.at("fiole60")->draw();
break;
}
case (70):
{
this->_infos.at("fiole70")->draw();
break;
}
case (80):
{
this->_infos.at("fiole80")->draw();
break;
}
case (90):
{
this->_infos.at("fiole90")->draw();
break;
}
case (100):
{
this->_infos.at("fiole100")->draw();
break;
}
default:
{
this->_infos.at("fiole0")->draw();
break;
}
}
for (int i = player->getNbBombMax() - player->getNbBombSet() - 1; i >= 0; i--)
{
Display::Vector3f newPosition5(20 + (i * 3), 90, 0);
this->_infos.at("bomb")->setPosition(newPosition5);
this->_infos.at("bomb")->draw();
}
gdl::Text text;
std::ostringstream ostream;
ostream << player->getNbCaisseDestroyed() * 100;
text.setText(ostream.str());
if (id_player == 0)
text.setPosition(120, 1020);
else if (id_player == 1)
text.setPosition(1080, 1020);
text.setSize(50);
text.draw();
}
void BomberGame::drawForPlayer3D(gdl::GameClock const & gameClock, int id_player) const
{
Field::Player *actualPlayer = 0;
for (std::list<Field::Player *>::const_iterator it = this->_players.begin(); it != this->_players.end(); ++it)
if ((*it)->getId() == id_player)
actualPlayer = (*it);
if (actualPlayer == 0)
return;
actualPlayer->updateCamera(gameClock);
affObjs(actualPlayer, gameClock);
for (unsigned int y = 0; y != this->getManager()->Field::Manager::getHeight(); y++)
for (unsigned int x = 0; x != this->getManager()->Field::Manager::getWidth(); x++)
for (std::list<Field::IGameComponent *>::iterator it = this->getManager()->Field::Manager::get(x, y).begin(); it != this->getManager()->Field::Manager::get(x, y).end(); ++it)
{
if (BomberOptions::getOptions()->getNbPlayer() == 1)
{
if (y > ((actualPlayer->getX() - 110) / 220) - 2 && y < ((actualPlayer->getX() + 110) / 220) + 3 && x > ((actualPlayer->getY() - 110) / 220) - 2 && x < ((actualPlayer
->getY() + 110) / 220) + 2)
affObjs(*it, gameClock);
}
else
if (y > ((actualPlayer->getX() - 110) / 220) - 1 && y < ((actualPlayer->getX() + 110) / 220) + 3 && x > ((actualPlayer->getY() - 110) / 220) - 2 && x < ((actualPlayer->getY() + 110) / 220) + 2)
affObjs(*it, gameClock);
}
for (std::list<Field::Player *>::const_iterator it = this->_players.begin(); it != this->_players.end(); ++it)
{
if ((*it) != actualPlayer)
affObjs(*it, gameClock);
}
}
void BomberGame::draw(gdl::GameClock const & gameClock) const
{
float elapsedTime = this->_clock->getElapsedTime();
this->_clock->getUpdateElapsedTime();
if (BomberOptions::getOptions()->getNbPlayer() == 2)
{
glViewport(0, 0, WIDTH / 2, HEIGHT);
this->drawForPlayer3D(gameClock, 0);
glViewport(WIDTH / 2, 0, WIDTH / 2, HEIGHT);
this->drawForPlayer3D(gameClock, 1);
glViewport(0, 0, WIDTH / 2, HEIGHT);
this->drawForPlayer2D(gameClock, 0);
glViewport(WIDTH / 2 - 2, 0, WIDTH / 2 - 2, HEIGHT);
this->drawForPlayer2D(gameClock, 1);
}
else
{
glViewport(0, 0, WIDTH, HEIGHT);
this->drawForPlayer3D(gameClock, 0);
this->drawForPlayer2D(gameClock, 0);
}
if (elapsedTime < this->_constElapsedTime)
usleep((this->_constElapsedTime - elapsedTime) * 1000000);
}
void BomberGame::updateCamera(gdl::GameClock const & gameClock, gdl::Input & input)
{
static_cast<void>(gameClock);
static_cast<void>(input);
// this->_camera.update(gameClock, input);
}
Field::Manager * BomberGame::getManager() const
{
return this->_manager;
}
std::list<Field::Player *> BomberGame::getPlayers() const
{
return this->_players;
}
template <typename T>
static std::string intToString(T i)
{
std::stringstream s;
s << i;
return s.str();
}
static unsigned int stringToInt(std::string const & str)
{
int ret;
std::stringstream s;
s << str.c_str();
s >> ret;
return ret;
}
void BomberGame::load(std::string const & filename)
{
DataFormat::Xml xml(filename);
unsigned int width = stringToInt(xml.getBalisesWthName("field")->getAttrValue("width"));
unsigned int height = stringToInt(xml.getBalisesWthName("field")->getAttrValue("height"));
std::list<Field::IGameComponent *> objs;
Field::Manager * manager = new Field::Manager(width, height);
for (std::list<DataFormat::Xml::Balise *>::const_iterator it = xml.getBalises().begin(); it != xml.getBalises().end(); ++it)
{
if ((*it)->getName().empty() != true && (*it)->getName() == "wall" && (*it)->getState() == DataFormat::OPENING)
{
unsigned int x = stringToInt((*it)->getAttrValue("x"));
unsigned int y = stringToInt((*it)->getAttrValue("y"));
Display::Vector3f vectorLen(0.0, 0.0, 0.0);
Display::Vector3f vectorRot(0.0, manager->randAngle(5), 0.0);
Display::Vector3f vectorPosition(y * 220, 0.0, x * 220);
manager->addComponent(x, y, new Field::Wall(true, 1, y, x, new Display::Texture3d("models/Barrel.fbx", vectorPosition, vectorRot, vectorLen), 0, 0));
}
else if ((*it)->getName().empty() != true && (*it)->getName() == "object" && (*it)->getState() == DataFormat::OPENING)
{
unsigned int x = stringToInt((*it)->getAttrValue("x"));
unsigned int y = stringToInt((*it)->getAttrValue("y"));
Display::Vector3f vectorLen(0.0, 0.0, 0.0);
Display::Vector3f vectorRot(0.0, 0.0, 0.0);
Display::Vector3f vectorPosition(y * 220, 0.0, x * 220);
switch (stringToInt((*it)->getAttrValue("buffType")))
{
case 0:
if (dynamic_cast<Field::Wall *>(manager->get(x, y).front()) == manager->get(x, y).front())
dynamic_cast<Field::Wall *>(manager->get(x, y).front())->setContent(new Field::Object(y, x, new Display::Texture3d("models/PorteeBonus.fbx", vectorPosition, vectorRot, vectorLen), 0, 0, Field::BUFF, Field::RANGE, 0, 0, -1));
else
manager->addComponent(x, y, new Field::Object(y, x, new Display::Texture3d("models/PorteeBonus.fbx", vectorPosition, vectorRot, vectorLen), 0, 0, Field::BUFF, Field::RANGE, 0, 0, -1));
break;
case 1:
if (dynamic_cast<Field::Wall *>(manager->get(x, y).front()) == manager->get(x, y).front())
dynamic_cast<Field::Wall *>(manager->get(x, y).front())->setContent(new Field::Object(y, x, new Display::Texture3d("models/SpeedBonus.fbx", vectorPosition, vectorRot, vectorLen), 0, 0, Field::BUFF, Field::SPEED, 0, 0, -1));
else
manager->addComponent(x, y, new Field::Object(y, x, new Display::Texture3d("models/SpeedBonus.fbx", vectorPosition, vectorRot, vectorLen), 0, 0, Field::BUFF, Field::SPEED, 0, 0, -1));
break;
case 2:
if (dynamic_cast<Field::Wall *>(manager->get(x, y).front()) == manager->get(x, y).front())
dynamic_cast<Field::Wall *>(manager->get(x, y).front())->setContent(new Field::Object(y, x, new Display::Texture3d("models/LifeBonus.fbx", vectorPosition, vectorRot, vectorLen), 0, 0, Field::BUFF, Field::LIFE, 0, 0, -1));
else
manager->addComponent(x, y, new Field::Object(y, x, new Display::Texture3d("models/LifeBonus.fbx", vectorPosition, vectorRot, vectorLen), 0, 0, Field::BUFF, Field::LIFE, 0, 0, -1));
break;
case 3:
if (dynamic_cast<Field::Wall *>(manager->get(x, y).front()) == manager->get(x, y).front())
dynamic_cast<Field::Wall *>(manager->get(x, y).front())->setContent(new Field::Object(y, x, new Display::Texture3d("models/MoreBombBonus.fbx", vectorPosition, vectorRot, vectorLen), 0, 0, Field::BUFF, Field::MORE, 0, 0, -1));
else
manager->addComponent(x, y, new Field::Object(y, x, new Display::Texture3d("models/MoreBombBonus.fbx", vectorPosition, vectorRot, vectorLen), 0, 0, Field::BUFF, Field::MORE, 0, 0, -1));
break;
default:
break;
}
}
for (std::list<DataFormat::Xml::Balise *>::const_iterator it = xml.getBalises().begin(); it != xml.getBalises().end(); ++it)
{
if ((*it)->getName().empty() != true && (*it)->getName() == "player" && (*it)->getState() == DataFormat::OPENING)
{
Display::Vector3f vectorPosition(stringToInt((*it)->getAttrValue("y")) * 220, 0, stringToInt((*it)->getAttrValue("x")) * 220);
Display::Vector3f vectorLen(0, 0, 0.0);
Display::Vector3f vectorRot(0.0, 0.0, 0.0);
if (stringToInt((*it)->getAttrValue("id")) == 0)
this->_players.push_back(new Field::Player(stringToInt((*it)->getAttrValue("id")), stringToInt((*it)->getAttrValue("pv")), stringToInt((*it)->getAttrValue("speed")), stringToInt((*it)->getAttrValue("bombmax")), stringToInt((*it)->getAttrValue("bombset")), stringToInt((*it)->getAttrValue("x")), stringToInt((*it)->getAttrValue("y")), new Display::Texture3d("models/WWunmoved.fbx", vectorPosition, vectorRot, vectorLen), 0, 0, 0, 0, 255));
else if (stringToInt((*it)->getAttrValue("id")) == 1)
this->_players.push_back(new Field::Player(stringToInt((*it)->getAttrValue("id")), stringToInt((*it)->getAttrValue("pv")), stringToInt((*it)->getAttrValue("speed")), stringToInt((*it)->getAttrValue("bombmax")), stringToInt((*it)->getAttrValue("bombset")), stringToInt((*it)->getAttrValue("x")), stringToInt((*it)->getAttrValue("y")), new Display::Texture3d("models/WWunmoved.fbx", vectorPosition, vectorRot, vectorLen), 0, 0, 255, 0, 0));
else
this->_players.push_back(new Field::Player(stringToInt((*it)->getAttrValue("id")), stringToInt((*it)->getAttrValue("pv")), stringToInt((*it)->getAttrValue("speed")), stringToInt((*it)->getAttrValue("bombmax")), stringToInt((*it)->getAttrValue("bombset")), stringToInt((*it)->getAttrValue("x")), stringToInt((*it)->getAttrValue("y")), new Display::Texture3d("models/WWunmoved.fbx", vectorPosition, vectorRot, vectorLen), 0, 0, rand() % 255, rand() % 255, rand() % 255));
}
}
}
this->_manager = manager;
}
void BomberGame::save()
{
if (access(".data/", F_OK) == -1 || access(".data/.saves/", F_OK) == -1)
throw(EndOfBomberMan("unable to access saves directory", "save method", "./data/.saves/"));
time_t t = time(0);
struct tm * now = localtime(&t);
static std::string extend = ".xml";
static std::string path = ".data/.saves/";
std::string name = intToString(time(0));
DataFormat::Xml xml;
std::list<DataFormat::Xml::Balise *> bals;
bals.push_back(new DataFormat::Xml::Balise("backup", DataFormat::OPENING));
bals.back()->addAttribute(std::make_pair("id", name));
bals.push_back(new DataFormat::Xml::Balise("infos", DataFormat::OPENING));
bals.back()->addAttribute(std::make_pair("second", intToString(now->tm_sec)));
bals.back()->addAttribute(std::make_pair("minute", intToString(now->tm_min)));
bals.back()->addAttribute(std::make_pair("hour", intToString(now->tm_hour)));
bals.back()->addAttribute(std::make_pair("day", intToString(now->tm_mday)));
bals.back()->addAttribute(std::make_pair("month", intToString(now->tm_mon)));
bals.back()->addAttribute(std::make_pair("year", intToString(now->tm_year)));
bals.push_back(new DataFormat::Xml::Balise("infos", DataFormat::CLOSING));
bals.push_back(new DataFormat::Xml::Balise("players", DataFormat::OPENING));
for (std::list<Field::Player *>::iterator itPl = this->_players.begin(); itPl != this->_players.end(); ++itPl)
{
bals.push_back(new DataFormat::Xml::Balise("player", DataFormat::OPENING));
bals.back()->addAttribute(std::make_pair("id", intToString((*itPl)->getId())));
bals.back()->addAttribute(std::make_pair("x", intToString((*itPl)->getX())));
bals.back()->addAttribute(std::make_pair("y", intToString((*itPl)->getY())));
bals.back()->addAttribute(std::make_pair("pv", intToString((*itPl)->getPv())));
bals.back()->addAttribute(std::make_pair("speed", intToString((*itPl)->getSpeed())));
bals.back()->addAttribute(std::make_pair("readSpeed", intToString((*itPl)->getRealSpeed())));
bals.back()->addAttribute(std::make_pair("power", intToString((*itPl)->getPower())));
bals.back()->addAttribute(std::make_pair("bombmax", intToString((*itPl)->getNbBombMax())));
bals.back()->addAttribute(std::make_pair("bombset", intToString((*itPl)->getNbBombSet())));
bals.back()->addAttribute(std::make_pair("nbCaisseDestroyed", intToString((*itPl)->getNbCaisseDestroyed())));
bals.back()->addAttribute(std::make_pair("nbPlayerKilled", intToString((*itPl)->getNbPlayerKilled())));
bals.back()->addAttribute(std::make_pair("buffTaked", intToString((*itPl)->getNbBuffTaked())));
bals.push_back(new DataFormat::Xml::Balise("player", DataFormat::CLOSING));
}
bals.push_back(new DataFormat::Xml::Balise("players", DataFormat::CLOSING));
bals.push_back(new DataFormat::Xml::Balise("field", DataFormat::OPENING));
bals.back()->addAttribute(std::make_pair("width", intToString(this->_manager->getWidth())));
bals.back()->addAttribute(std::make_pair("height", intToString(this->_manager->getHeight())));
for (unsigned int y = 0; y != this->_manager->getHeight(); y++)
for (unsigned int x = 0; x != this->_manager->getWidth(); x++)
{
std::list<Field::IGameComponent *>::iterator it;
for (it = this->_manager->get(x, y).begin(); it != this->_manager->get(x, y).end(); ++it)
if (dynamic_cast<Field::Wall *>(*it) == *it && dynamic_cast<Field::Wall *>(*it)->isBreakable() == true)
{
bals.push_back(new DataFormat::Xml::Balise("wall", DataFormat::OPENING));
bals.back()->addAttribute(std::make_pair("x", intToString(x)));
bals.back()->addAttribute(std::make_pair("y", intToString(y)));
bals.push_back(new DataFormat::Xml::Balise("wall", DataFormat::CLOSING));
if (dynamic_cast<Field::Wall *>(*it)->getContent() != 0)
{
bals.push_back(new DataFormat::Xml::Balise("object", DataFormat::OPENING));
bals.back()->addAttribute(std::make_pair("x", intToString(x)));
bals.back()->addAttribute(std::make_pair("y", intToString(y)));
bals.back()->addAttribute(std::make_pair("objectType", intToString(dynamic_cast<Field::Wall *>(*it)->getContent()->getObjectType())));
bals.back()->addAttribute(std::make_pair("buffType", intToString(dynamic_cast<Field::Wall *>(*it)->getContent()->getBuffType())));
bals.back()->addAttribute(std::make_pair("power", intToString(dynamic_cast<Field::Wall *>(*it)->getContent()->getPower())));
bals.back()->addAttribute(std::make_pair("timer", intToString(dynamic_cast<Field::Wall *>(*it)->getContent()->getTimer())));
bals.push_back(new DataFormat::Xml::Balise("object", DataFormat::CLOSING));
}
}
else if (dynamic_cast<Field::Object *>(*it) == *it)
{
bals.push_back(new DataFormat::Xml::Balise("object", DataFormat::OPENING));
bals.back()->addAttribute(std::make_pair("x", intToString(x)));
bals.back()->addAttribute(std::make_pair("y", intToString(y)));
bals.back()->addAttribute(std::make_pair("objectType", intToString(dynamic_cast<Field::Wall *>(*it)->getContent()->getObjectType())));
bals.back()->addAttribute(std::make_pair("buffType", intToString(dynamic_cast<Field::Wall *>(*it)->getContent()->getBuffType())));
bals.back()->addAttribute(std::make_pair("power", intToString(dynamic_cast<Field::Wall *>(*it)->getContent()->getPower())));
bals.back()->addAttribute(std::make_pair("timer", intToString(dynamic_cast<Field::Wall *>(*it)->getContent()->getTimer())));
bals.push_back(new DataFormat::Xml::Balise("object", DataFormat::CLOSING));
}
}
bals.push_back(new DataFormat::Xml::Balise("field", DataFormat::CLOSING));
bals.push_back(new DataFormat::Xml::Balise("backup", DataFormat::CLOSING));
xml.addBalises(bals);
xml.generate(path + name + extend);
}
}
}
|
b12d34d1d459ca293669c09aba2f0770b8b1a8f1 | 46c840dc311a833881b9afebfa0a19de40ed4f2d | /658.cpp | 15f97fbaa187c44792e532152753dcfb96d83358 | [] | no_license | zxth93/leetcode | 9d033c7082ab57dc5d292f36f0a05984d1d642a5 | 72562cb303000b9981f129c51a7e5fce8fcb37b4 | refs/heads/master | 2020-04-17T19:32:35.902221 | 2018-08-19T14:21:20 | 2018-08-19T14:21:20 | 67,509,355 | 6 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 971 | cpp | 658.cpp | //
// 658.cpp
// leetcode
//
// Created by R Z on 2017/12/8.
// Copyright © 2017年 R Z. All rights reserved.
//
#include <stdio.h>
#include <vector>
#include <stdlib.h>
using namespace std;
class Solution {
public:
vector<int> findClosestElements(vector<int>& arr, int k, int x) {
int len=arr.size();
int index = low_bound(arr, len, x);
int i=index-1, j=index;
while(k--){
i<0||(j<len && abs(arr[i]-x)>abs(arr[j]-x))?j++:i--;
}
return vector<int>(arr.begin()+i+1,arr.begin()+j);
}
int low_bound(vector<int> &nums, int len, int target){
if(!len) return 0;
if(nums[0]>=target) return 0;
else if(nums[len-1]<target) return len-1;
int lo=0, hi=len-1;
while(lo<hi){
int mid=lo+(hi-lo)/2;
if(nums[mid]==target) return mid;
if(nums[mid]<target) lo=mid+1;
else hi=mid;
}
return lo;
}
};
|
7c709d9a36ef5c9601b8c54ad5890c4953957cb7 | ba63886c2366679dbd132a1142bd55cf8870b0bf | /lab_03/implementation/objects/model/model_details/point/point.hpp | f0da1d436465c7ecf20eabdcdcd569e7fc8bc5c7 | [] | no_license | ivaaahn/bmstu-oop | 27d2edf96584ba784e112c7b0b69b2eab00f5f6b | bcbf6d289f782d5104860c60eb99f5206bf3f5d9 | refs/heads/main | 2023-05-13T03:19:35.359648 | 2021-06-08T11:40:47 | 2021-06-08T11:40:47 | 345,132,023 | 4 | 1 | null | 2021-03-12T13:39:46 | 2021-03-06T15:51:04 | null | UTF-8 | C++ | false | false | 1,238 | hpp | point.hpp | //
// Created by ivaaahn on 23.05.2021.
//
#ifndef __LAB_03_POINT_HPP__
#define __LAB_03_POINT_HPP__
class Point {
public:
Point() = default;
~Point() = default;
Point(double x, double y, double z);
Point(const Point &other) = default;
Point &operator=(const Point &other) = default;
Point(const Point &&other) noexcept;
Point &operator=(Point &&other) noexcept;
Point operator-() const;
bool operator==(const Point &other) const noexcept;
[[nodiscard]] bool equ(const Point &other) const noexcept;
bool operator!=(const Point &point) const noexcept;
[[nodiscard]] double getX() const;
[[nodiscard]] double getY() const;
[[nodiscard]] double getZ() const;
void setX(double x);
void setY(double y);
void setZ(double z);
Point operator+(const Point &other);
Point operator-(const Point &other);
void move(double dx, double dy, double dz);
void scale(double kx, double ky, double kz);
void rotate(double ax, double ay, double az);
void rotateX(double ax);
void rotateY(double ay);
void rotateZ(double az);
Point relativeTo(const Point &point);
private:
double x, y, z;
};
#endif //__LAB_03_POINT_HPP__
|
08d94d10a33e9ede6ca80ceff3f686131985b1ff | 9968d6d8cf66cd33ca37cae9a7051c1b1c8c1ae8 | /example/picket_fence.cpp | c267a9490c9e8641d32da68d0cc7443ab587ae89 | [] | no_license | Cresspresso/opengl-shadowmap-experiment | b75117e127c1cb5400f2d452d841fe37750e4d54 | ccf2078c20121e6387c07e98f2df0fad595253ad | refs/heads/master | 2023-03-25T16:06:41.642260 | 2021-03-26T00:56:58 | 2021-03-26T00:56:58 | 317,020,919 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,576 | cpp | picket_fence.cpp |
#include "assets.hpp"
#include "picket_fence.hpp"
namespace example
{
PicketFenceShader::PicketFenceShader()
{
char const* const vertexShader = R"__(
#version 330 core
layout(location = 0) in vec3 inPosition;
layout(location = 1) in vec3 inNormal;
layout(location = 2) in vec2 inTexCoords;
out V2F {
vec3 FragPos;
vec3 Normal;
vec2 TexCoords;
vec4 FragPosLightSpace;
} v2f;
uniform mat4 mvp;
uniform mat4 model;
uniform mat3 fixNormals;
uniform mat4 lightSpaceMatrix;
void main()
{
vec4 p = vec4(inPosition, 1.0f);
gl_Position = mvp * p;
v2f.FragPos = vec3(model * p);
v2f.Normal = normalize(fixNormals * inNormal);
v2f.TexCoords = inTexCoords;
v2f.FragPosLightSpace = lightSpaceMatrix * vec4(v2f.FragPos, 1.0f);
}
)__";
char const* const fragmentShader = R"__(
#version 330 core
out vec4 outColor;
in V2F {
vec3 FragPos;
vec3 Normal;
vec2 TexCoords;
vec4 FragPosLightSpace;
} v2f;
uniform sampler2D diffuseTextures[4];
uniform sampler2D shadowMap;
uniform vec3 lightPos;
uniform vec3 viewPos;
float ShadowCalculation(vec4 fragPosLightSpace)
{
// perform perspective divide
vec3 projCoords = fragPosLightSpace.xyz / fragPosLightSpace.w;
// transform to [0,1] range
projCoords = projCoords * 0.5 + 0.5;
// get closest depth value from light's perspective (using [0,1] range fragPosLight as coords)
float closestDepth = texture(shadowMap, projCoords.xy).r;
// get depth of current fragment from light's perspective
float currentDepth = projCoords.z;
// check whether current frag pos is in shadow
float shadow = currentDepth > closestDepth ? 1.0 : 0.0;
return shadow;
}
void main()
{
vec3 color = texture(diffuseTextures[0], v2f.TexCoords).rgb;
vec3 normal = v2f.Normal;
vec3 lightColor = vec3(1.0f);
// ambient
vec3 ambient = 0.15 * color;
// diffuse
vec3 lightDir = normalize(lightPos - v2f.FragPos);
float diff = max(dot(lightDir, normal), 0.0);
vec3 diffuse = diff * lightColor;
// specular
vec3 viewDir = normalize(viewPos - v2f.FragPos);
float spec = 0.0;
vec3 halfwayDir = normalize(lightDir + viewDir);
spec = pow(max(dot(normal, halfwayDir), 0.0f), 64.0f);
vec3 specular = spec * lightColor;
// calculate shadow
float shadow = ShadowCalculation(v2f.FragPosLightSpace);
vec3 lighting = (ambient + (1.0f - shadow) * (diffuse + specular)) * color;
outColor = vec4(lighting, 1.0f);
// DEBUG
outColor = vec4(1.0f, 0.0f, 0.0f, 1.0f);
}
)__";
m_shader = be::gl::makeBasicShaderProgram(vertexShader, fragmentShader, "picket_fence.cpp");
m_uniformLocations.mvp = glGetUniformLocation(program(), "mvp");
m_uniformLocations.model = glGetUniformLocation(program(), "model");
m_uniformLocations.fixNormals = glGetUniformLocation(program(), "fixNormals");
m_uniformLocations.lightSpaceMatrix = glGetUniformLocation(program(), "lightSpaceMatrix");
m_uniformLocations.viewPos = glGetUniformLocation(program(), "viewPos");
m_uniformLocations.lightPos = glGetUniformLocation(program(), "lightPos");
for (size_t i = 0; i < m_uniformLocations.diffuseTextures.size(); ++i)
{
std::string str = "diffuseTextures[";
str += std::to_string(i);
str += ']';
m_uniformLocations.diffuseTextures[i] = glGetUniformLocation(program(), str.c_str());
}
}
be::pink::model::Model loadPicketFenceModel()
{
return be::pink::model::loadModel((assets::projectAssetsFolder / "models/Fence.dae").string());
}
void renderPicketFence(
PicketFenceShader const& shader,
be::pink::model::Model const& model,
be::pink::Camera const& camera,
glm::vec3 const& lightPos,
glm::mat4 const& lightSpaceMatrix,
GLuint const shadowMapTextureIndex,
glm::mat4 const& parentModelMatrix
)
{
BE_USE_PROGRAM_SCOPE(shader.program());
be::gl::uniformMat4(shader.uniformLocations().lightSpaceMatrix, lightSpaceMatrix);
be::gl::uniformVec3(shader.uniformLocations().lightPos, lightPos);
be::gl::uniformVec3(shader.uniformLocations().viewPos, camera.position);
glUniform1i(shader.uniformLocations().shadowMap, shadowMapTextureIndex);
be::pink::model::DrawNodeCallback const drawNode = [&](be::pink::model::Node const& node, glm::mat4 const& modelMatrix)
{
auto const mvp = camera.vp * modelMatrix;
be::gl::uniformMat4(shader.uniformLocations().mvp, mvp);
be::gl::uniformMat4(shader.uniformLocations().model, modelMatrix);
auto const fixNormals = glm::transpose(glm::inverse(glm::mat3(modelMatrix)));
be::gl::uniformMat3(shader.uniformLocations().fixNormals, fixNormals);
for (auto const& w : node.meshes)
{
if (auto const mesh = w.lock())
{
if (auto const material = mesh->material.lock())
{
std::vector<std::function<void()>> deferred;
CRESS_MOO_DEFER_BEGIN(_);
for (auto const& f : deferred) { f(); }
CRESS_MOO_DEFER_END(_);
if (auto const it = material->textureMap.find(aiTextureType_DIFFUSE);
it != material->textureMap.end())
{
auto const& textures = it->second;
auto const N = std::min<size_t>(textures.size(), shader.uniformLocations().diffuseTextures.size());
for (size_t i = 0; i < N; ++i)
{
glActiveTexture(GL_TEXTURE0 + i);
glBindTexture(GL_TEXTURE_2D, textures[i].get());
glUniform1i(shader.uniformLocations().diffuseTextures[i], i);
deferred.push_back([&shader, i]()noexcept {
glActiveTexture(GL_TEXTURE0 + i);
glBindTexture(GL_TEXTURE_2D, 0);
});
}
}
be::gl::drawBasicMesh(mesh->data);
}
}
}
};
be::pink::model::renderModel(model, drawNode, parentModelMatrix);
}
}
|
be6e59ac4d4950e190e45ec8e7da5f0e163aea64 | 8eb7a4590787900509af3268300c6a3a1bf11b25 | /QT/Server/mytcpclient.h | c407fa96d11a28a8ae19a0b8ee7bfe37c1717782 | [] | no_license | Mikycrazy/pb173-project | f862bf1c8dfe81fd3dac2b80b45f598257e49053 | c3885c935d08fbcdd032072d9be9ad535a653cbe | refs/heads/master | 2021-01-01T06:10:09.375924 | 2015-01-23T16:19:00 | 2015-01-23T16:19:00 | 26,128,372 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,538 | h | mytcpclient.h | #ifndef MYTCPCLIENT_H
#define MYTCPCLIENT_H
#include <stdlib.h>
#include <iostream>
#include <string.h>
#include <QtNetwork>
#include <QObject>
#include <QString>
#include <QTcpServer>
#include <QTcpSocket>
using namespace std;
class MyTcpClient : public QObject
{
Q_OBJECT
private:
QTcpSocket* mSocket;
unsigned char* mLastReicevedData;
int mLastReicevedDataSize;
int mLastReicevedDataType;
public:
/**
* Konstruktor pre triedu NetworkManager.
*/
explicit MyTcpClient() {}
~MyTcpClient(){}
/**
* Zahaji spojeni tcp spojeni s nastavenou adresou a portem
*
* @param address server ip
* @param port server port
* @return true ak sa spojenie podarilo
*/
bool startConnection(QString ipAddress, quint16 port);
/**
* Odosle data serveru
*
* @param data data na odoslanie
* @param size velkost dat na odoslanie
*
* @return true ak sa odoslanie podarilo, inak false
*/
bool sendData(unsigned char* data, int size);
unsigned char* getLastData() {return mLastReicevedData; }
int getLastDataSize() { return mLastReicevedDataSize; }
int getLastDataType() { return mLastReicevedDataType; }
public slots:
/**
* Vykona potrebne akcie v pripade odpojenia od servera
*/
void disconnected();
/**
* Prijme data od servera a posunie na spracovanie
*/
void receiveData();
signals:
void networkReceivedData(unsigned char* data, int size);
};
#endif // MYTCPCLIENT_H
|
d20fa684c9ca7ca2c38e68896d1ceb4c43316fd8 | f499577c0b8f1365608f223aab3b3f85936088b4 | /OpenCVLibs/MouseEvent.h | afc08098a6378bfc73e196b5e794320238204ed3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | laikuaut/MyLibrarys | eb9b66f8b92291c5e63af99cee0f02f6d670a7e4 | 38420b2205ee3ba3e34d87a7cc56c22f56aef970 | refs/heads/master | 2020-12-28T22:12:24.662331 | 2013-10-20T17:19:14 | 2013-10-20T17:19:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 376 | h | MouseEvent.h | #pragma once
#include"..\Core\Core.h"
#include"opencv2\core\core.hpp"
#include"opencv2\highgui\highgui.hpp"
namespace pro{
class PRO_EXPORTS MouseEvent
{
public:
int event,x,y,flag;
public:
MouseEvent(void);
~MouseEvent(void);
virtual void onMouse_impl(int event,int x,int y,int flag) = 0;
static void onMouse(int event, int x, int y, int flag, void* data);
};
} |
a87107719768e15081f3cbe469ac8524e88c6cbf | a27e939e7d5db9f4bc6ca9afdc1c2b9f8a3e5c2e | /infra/acceptor.h | e963912ea5fcc527d3ea598b2613d6cf22a67491 | [] | no_license | ecilaz/ecila | 116004a5541913d06e86f4c3c38b66a6ffd58115 | 230e1efcec476c9b09e78094fcea1f50b23b4f12 | refs/heads/master | 2021-01-10T20:26:17.114891 | 2019-11-24T02:22:01 | 2019-11-24T02:22:01 | 223,353,075 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 390 | h | acceptor.h | #pragma once
#include "node.h"
NS_ECILA_START
class IAcceptor;
class IPacketHandler;
class DECL_SPEC_DLL Acceptor
: public Node
{
public:
Acceptor();
virtual ~Acceptor();
CLASSNAME("Acceptor");
void Initialize(Node *root, IPacketHandler *pkt_handler);
IAcceptor* AcceptorImpl();
private:
IAcceptor *acceptor_;
IPacketHandler *pkt_handler_;
};
NS_ECILA_END
|
b9425f0b7f9fc1d742f7a2c7af8adb2f1d4f085f | f500e51c5190766d476c00d0ebed2508790f1f62 | /Android/h/adWhirl.h | f975f770049dcee93ac7b8dd61c59434c564ce66 | [] | no_license | primap6/CandyMare | 0d65624d79d8b32aa24258761ff7aa5212723170 | cb19707c88c47c0199fc193213d1e660773c9ad4 | refs/heads/master | 2020-05-16T23:50:50.846773 | 2015-04-29T13:52:07 | 2015-04-29T13:52:07 | 183,379,896 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,131 | h | adWhirl.h | #ifndef ADWHIRL
#define ADWHIRL
#include "util.h"
//#include "s3eAdWhirl.h"
namespace
{
const char* g_LastMessage;
bool displayAd;
bool availableAd;
int adW;
int adH;
float GetAdScale()
{
// the banners are 320x50 but they may be scaled up depending on the screen size
float adScale = s3eSurfaceGetInt(S3E_SURFACE_WIDTH) / 320.0f;
return adScale;
}
int32 AdLoad(void* system, void* user)
{
availableAd = true;
g_LastMessage = "`x666666Ad loaded";
float adScale = s3eSurfaceGetInt(S3E_SURFACE_WIDTH) / 320.0f;
adW = (int)(320 * adScale);
adH = (int)(50 * adScale);
return 0;
}
int32 AdFail(void* system, void* user)
{
availableAd = false;
g_LastMessage = "`x666666Ad failed";
return 0;
}
int32 AdFullscreenBegin(void* system, void* user)
{
g_LastMessage = "`x666666Fullscreen ad began";
return 0;
}
int32 AdFullscreenEnd(void* system, void* user)
{
g_LastMessage = "`x666666Fullscreen ad ended";
return 0;
}
// avoid bringing in conflicting SC++L implementations
int iabs(int x)
{
return x < 0 ? -x : x;
}
}
class AdWhirl{
public:
void construct()
{
g_LastMessage = NULL;
bool displayAd = true;
bool availableAd = false;
int adW = 1;
int adH = 1;
// initialise s3eAdWhirl
s3eDeviceOSID osid = (s3eDeviceOSID)s3eDeviceGetInt(S3E_DEVICE_OS);
if (osid == S3E_OS_ID_IPHONE)
{
// this ID is specifically made for testing s3eAdWhirl
// make sure you change this ID to your iPhone app AdWhirl ID when building your own app
s3eAdWhirlStart("319df3beaa5441eea9ebe5c41f5621cc");
}
else if (osid == S3E_OS_ID_ANDROID)
{
// this ID is specifically made for testing s3eAdWhirl
// make sure you change this ID to your Android app AdWhirl ID when building your own app
s3eAdWhirlStart("052b0e7247e7432db29f8e527a37b509");
}
else
{
s3eDebugErrorShow(S3E_MESSAGE_CONTINUE, "AdWhirl only works on iOS/Android");
}
s3eAdWhirlRegister(S3E_ADWHIRL_CALLBACK_AD_LOAD, &AdLoad, NULL);
s3eAdWhirlRegister(S3E_ADWHIRL_CALLBACK_AD_FAIL, &AdFail, NULL);
s3eAdWhirlRegister(S3E_ADWHIRL_CALLBACK_FULLSCREEN_BEGIN, &AdFullscreenBegin, NULL);
s3eAdWhirlRegister(S3E_ADWHIRL_CALLBACK_FULLSCREEN_END, &AdFullscreenEnd, NULL);
}
void destruct()
{
}
/* bool Update()
{
if (!s3eAdWhirlAvailable())
return true;
return true;
}
*/
void showAd()
{
if (!displayAd)
{
g_LastMessage = "`x666666Showing ad";
s3eAdWhirlShow();
displayAd = true;
}
}
void hideAd()
{
if (displayAd)
{
g_LastMessage = "`x666666Hiding ad";
s3eAdWhirlHide();
displayAd = false;
}
}
void refreshAd()
{
g_LastMessage = "`x666666Refreshing ad";
s3eAdWhirlRequestFreshAd();
}
void Render()
{
/*if (g_LastMessage != NULL)
{
s3eDebugPrintf(10, 350, S3E_FALSE, g_LastMessage);
}
if (displayAd && availableAd)
{
// draw a fake ad for the simulator
//Iw2DDrawImage( util.pNotificationFrame,CIwSVec2(0,0),
//CIwSVec2 size
//)
//Iw2DDrawRect(CIwSVec2(0, 0),CIwSVec2(adW,adH));
//s3eDebugPrintf(10, 400, S3E_FALSE, "`x666666Loaded ad...yahoo!");
}*/
}
};
#endif |
91c93372c11c169697e6138c78e8d1baca5e9d97 | a92b18defb50c5d1118a11bc364f17b148312028 | /src/prod/test/FabricTest/TestWatchDog.h | 9bc50ddcef4901472b278428122023a283465554 | [
"MIT"
] | permissive | KDSBest/service-fabric | 34694e150fde662286e25f048fb763c97606382e | fe61c45b15a30fb089ad891c68c893b3a976e404 | refs/heads/master | 2023-01-28T23:19:25.040275 | 2020-11-30T11:11:58 | 2020-11-30T11:11:58 | 301,365,601 | 1 | 0 | MIT | 2020-11-30T11:11:59 | 2020-10-05T10:05:53 | null | UTF-8 | C++ | false | false | 1,536 | h | TestWatchDog.h | // ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#pragma once
namespace FabricTest
{
class FabricTestDispatcher;
class TestHealthTable;
class TestWatchDog
{
DENY_COPY(TestWatchDog);
public:
TestWatchDog(FabricTestDispatcher & dispatcher, std::wstring const & sourceId, Common::TimeSpan reportInterval);
__declspec(property(get=get_SourceId)) std::wstring const& SourceId;
std::wstring const& get_SourceId() const { return sourceId_; }
int64 GetSequence();
int NextInt(int max)
{
return random_.Next(max);
}
double NextDouble()
{
return random_.NextDouble();
}
void Report(FABRIC_HEALTH_REPORT const & report);
void Start(std::shared_ptr<TestWatchDog> const & thisSPtr);
void Stop();
private:
void Run();
FabricTestDispatcher & dispatcher_;
std::shared_ptr<TestHealthTable> healthTable_;
std::wstring sourceId_;
Common::TimeSpan reportInterval_;
Random random_;
bool active_;
Common::TimerSPtr timer_;
ComPointer<IFabricHealthClient4> healthClient_;
static int64 Sequence;
};
typedef std::shared_ptr<TestWatchDog> TestWatchDogSPtr;
}
|
a71d8ef82e17406a6dbb1bdbb06d857050615004 | 999023e04644f071c32319959701169c14e149a3 | /level.cpp | fc839c0686ccd047be34ccfbe097a93c3a7b430d | [
"MIT"
] | permissive | ptbw/32blox | 959d61e9f8a1894d376e73969b9b6dcaa2a19e51 | 3dff98cf836afc51c0b9f64a1de2cd53359f07ec | refs/heads/master | 2022-10-05T00:26:10.346273 | 2020-05-31T20:36:41 | 2020-05-31T20:36:41 | 268,119,114 | 0 | 0 | MIT | 2020-05-30T16:35:18 | 2020-05-30T16:35:18 | null | UTF-8 | C++ | false | false | 3,003 | cpp | level.cpp | /*
* level.cpp - part of 32Blox, a breakout game for the 32blit built to
* explore the API.
*
* Defines the game levels, and maintains the current level state as well.
* Levels are grids of up to 20x20 blocks.
*
* Please note that this is a first attempt at understanding a somewhat fluid
* API on a shiny new bit of kit, so it probably is not full of 'best practice'.
* It will hopefully serve as some sort of starting point, however.
*
* Coyright (C) 2020 Pete Favelle <pete@fsquared.co.uk>
*
* This software is provided under the MIT License. See LICENSE.txt for details.
*/
/* System headers. */
#include <string.h>
/* Local headers. */
#include "32blit.hpp"
#include "32blox.hpp"
/* Module variables. */
static uint8_t m_current_level[BOARD_HEIGHT][BOARD_WIDTH];
/* Raw level data. */
#include "levels.h"
/* Functions. */
using namespace blit;
/*
* level_init - initialises the current level state to the provided level.
*
* uint8_t - the current level the player is on.
*/
void level_init( uint8_t p_level )
{
/* Quite easy really, we just copy the whole block of level data. */
memcpy( m_current_level, &m_levels[ p_level ],
sizeof( uint8_t ) * ( BOARD_HEIGHT * BOARD_WIDTH ) );
}
/*
* level_get_line - returns the current bricks in the requested line.
*
* uint8_t - the line of bricks to fetch, between 0 and 10
*
* Returns a 10 byte array of brick types.
*/
uint8_t *level_get_line( uint8_t p_line )
{
/* Simple return of the required line. */
return m_current_level[ p_line ];
}
/*
* level_hit_brick - hits the specified brick with a ball. Depending on the
* type of brick, we might modify or remove it.
*
* uint8_t - the row the brick is on
* uint8_t - the column the brick is in
*/
void level_hit_brick( uint8_t p_row, uint8_t p_column )
{
/* Sanity check the location. */
if ( ( p_row >= BOARD_HEIGHT ) || ( p_column >= BOARD_WIDTH ) )
{
return;
}
/* And only act if a brick is there. */
if ( m_current_level[p_row][p_column] == 0 )
{
return;
}
/* For now, we'll just decrement the brick type. */
m_current_level[p_row][p_column]--;
}
const char *level_get_bricktype( uint8_t p_bricktype )
{
switch( p_bricktype )
{
case 3:
return "brick_yellow";
case 2:
return "brick_orange";
case 1:
return "brick_red";
}
/* Default to a red brick, should never be reached though... */
return "brick_red";
}
/*
* level_get_bricks - returns the number of bricks remaining in the level
*
* Returns a brick count.
*/
uint16_t level_get_bricks( void )
{
uint8_t l_row, l_column;
uint16_t l_bricks = 0;
/* Simply count the non-zero entries in the level. */
for ( l_row = 0; l_row < BOARD_HEIGHT; l_row++ )
{
for ( l_column = 0; l_column < BOARD_WIDTH; l_column++ )
{
if ( m_current_level[l_row][l_column] > 0 )
{
l_bricks++;
}
}
}
return l_bricks;
}
/* End of level.cpp */
|
55f222c0d9d39d1d48fae69b40e55417aa34ec60 | f4dd8e3ab9f82445b0394c7f9874788380150ed1 | /src/contract/processing.cpp | 5031b2e84cbd3bd392c4b2856b3fa7be4f500a43 | [
"MIT"
] | permissive | kugwa/ourcoin | 620a5fcedb3b236d69123435cc4987e3ed310697 | 674fa8ca205efc8102bd23945a33e9319b16d482 | refs/heads/master | 2021-04-06T19:36:13.400872 | 2018-02-05T09:46:03 | 2018-02-05T09:46:03 | 98,856,227 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,891 | cpp | processing.cpp | #include "contract/processing.h"
#include "util.h"
#include <string>
#include <fstream>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
static fs::path contracts_dir;
const static fs::path &GetContractsDir()
{
if(!contracts_dir.empty()) return contracts_dir;
contracts_dir = GetDataDir() / "contracts";
fs::create_directories(contracts_dir);
return contracts_dir;
}
static int call_mkdll(const std::string &contract)
{
int pid, status;
pid = fork();
if(pid == 0) {
int fd = open((GetContractsDir().string() + "/err").c_str(),
O_WRONLY | O_APPEND | O_CREAT,
0664);
dup2(fd, STDERR_FILENO);
close(fd);
execlp("ourcontract-mkdll",
"ourcontract-mkdll",
GetContractsDir().string().c_str(),
contract.c_str(),
NULL);
exit(EXIT_FAILURE);
}
waitpid(pid, &status, 0);
if (WIFEXITED(status) == false) return -1;
if (WEXITSTATUS(status) != 0) return -1;
return 0;
}
static int call_rt(const std::string &contract, const std::vector<std::string> &args)
{
int pid, status;
pid = fork();
if(pid == 0) {
int fd = open((GetContractsDir().string() + "/err").c_str(),
O_WRONLY | O_APPEND | O_CREAT,
0664);
dup2(fd, STDERR_FILENO);
close(fd);
const char **argv = (const char**)malloc((args.size() + 4) * sizeof(char*));
argv[0] = "ourcontract-rt";
argv[1] = GetContractsDir().string().c_str();
argv[2] = contract.c_str();
for (unsigned i = 0; i < args.size(); i++) argv[i + 3] = args[i].c_str();
argv[args.size() + 3] = NULL;
execvp("ourcontract-rt", (char* const*)argv);
exit(EXIT_FAILURE);
}
waitpid(pid, &status, 0);
if (WIFEXITED(status) == false) return -1;
if (WEXITSTATUS(status) != 0) return -1;
return 0;
}
bool ProcessContract(const std::string &txid, const Contract &contract)
{
if (contract.action == contract_action::ACTION_NEW) {
fs::path new_dir = GetContractsDir() / txid;
fs::create_directories(new_dir);
std::ofstream contract_code(new_dir.string() + "/code.c");
contract_code.write(contract.code.c_str(), contract.code.size());
contract_code.close();
if (call_mkdll(txid) < 0) {
/* TODO: clean up files */
return false;
}
if (call_rt(txid, contract.args) < 0) {
/* TODO: perform state recovery */
return false;
}
} else if (contract.action == contract_action::ACTION_CALL) {
if (call_rt(contract.callee.ToString(), contract.args) < 0) {
/* TODO: perform state recovery */
return false;
}
}
return true;
}
|
96256e6962afce4923fe4e2050f5550cb7921380 | bd2139703c556050403c10857bde66f688cd9ee6 | /panama-foreign/279/webrev.02/src/hotspot/share/code/compiledMethod.cpp | 3c9787df6e7ee7c3f2da6eb56b2622b08effdc7b | [] | no_license | isabella232/cr-archive | d03427e6fbc708403dd5882d36371e1b660ec1ac | 8a3c9ddcfacb32d1a65d7ca084921478362ec2d1 | refs/heads/master | 2023-02-01T17:33:44.383410 | 2020-12-17T13:47:48 | 2020-12-17T13:47:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 30,733 | cpp | compiledMethod.cpp | /*
* Copyright (c) 2015, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
#include "precompiled.hpp"
#include "code/compiledIC.hpp"
#include "code/compiledMethod.inline.hpp"
#include "code/exceptionHandlerTable.hpp"
#include "code/scopeDesc.hpp"
#include "code/codeCache.hpp"
#include "code/icBuffer.hpp"
#include "gc/shared/barrierSet.hpp"
#include "gc/shared/barrierSetNMethod.hpp"
#include "gc/shared/gcBehaviours.hpp"
#include "interpreter/bytecode.inline.hpp"
#include "logging/log.hpp"
#include "logging/logTag.hpp"
#include "memory/resourceArea.hpp"
#include "oops/methodData.hpp"
#include "oops/method.inline.hpp"
#include "prims/methodHandles.hpp"
#include "runtime/atomic.hpp"
#include "runtime/deoptimization.hpp"
#include "runtime/handles.inline.hpp"
#include "runtime/mutexLocker.hpp"
#include "runtime/sharedRuntime.hpp"
CompiledMethod::CompiledMethod(Method* method, const char* name, CompilerType type, const CodeBlobLayout& layout,
int frame_complete_offset, int frame_size, ImmutableOopMapSet* oop_maps,
bool caller_must_gc_arguments)
: CodeBlob(name, type, layout, frame_complete_offset, frame_size, oop_maps, caller_must_gc_arguments),
_mark_for_deoptimization_status(not_marked),
_method(method),
_gc_data(NULL)
{
init_defaults();
}
CompiledMethod::CompiledMethod(Method* method, const char* name, CompilerType type, int size,
int header_size, CodeBuffer* cb, int frame_complete_offset, int frame_size,
OopMapSet* oop_maps, bool caller_must_gc_arguments)
: CodeBlob(name, type, CodeBlobLayout((address) this, size, header_size, cb), cb,
frame_complete_offset, frame_size, oop_maps, caller_must_gc_arguments),
_mark_for_deoptimization_status(not_marked),
_method(method),
_gc_data(NULL)
{
init_defaults();
}
void CompiledMethod::init_defaults() {
_has_unsafe_access = 0;
_has_method_handle_invokes = 0;
_lazy_critical_native = 0;
_has_wide_vectors = 0;
}
bool CompiledMethod::is_method_handle_return(address return_pc) {
if (!has_method_handle_invokes()) return false;
PcDesc* pd = pc_desc_at(return_pc);
if (pd == NULL)
return false;
return pd->is_method_handle_invoke();
}
// Returns a string version of the method state.
const char* CompiledMethod::state() const {
int state = get_state();
switch (state) {
case not_installed:
return "not installed";
case in_use:
return "in use";
case not_used:
return "not_used";
case not_entrant:
return "not_entrant";
case zombie:
return "zombie";
case unloaded:
return "unloaded";
default:
fatal("unexpected method state: %d", state);
return NULL;
}
}
//-----------------------------------------------------------------------------
void CompiledMethod::mark_for_deoptimization(bool inc_recompile_counts) {
MutexLocker ml(CompiledMethod_lock->owned_by_self() ? NULL : CompiledMethod_lock,
Mutex::_no_safepoint_check_flag);
_mark_for_deoptimization_status = (inc_recompile_counts ? deoptimize : deoptimize_noupdate);
}
//-----------------------------------------------------------------------------
ExceptionCache* CompiledMethod::exception_cache_acquire() const {
return Atomic::load_acquire(&_exception_cache);
}
void CompiledMethod::add_exception_cache_entry(ExceptionCache* new_entry) {
assert(ExceptionCache_lock->owned_by_self(),"Must hold the ExceptionCache_lock");
assert(new_entry != NULL,"Must be non null");
assert(new_entry->next() == NULL, "Must be null");
for (;;) {
ExceptionCache *ec = exception_cache();
if (ec != NULL) {
Klass* ex_klass = ec->exception_type();
if (!ex_klass->is_loader_alive()) {
// We must guarantee that entries are not inserted with new next pointer
// edges to ExceptionCache entries with dead klasses, due to bad interactions
// with concurrent ExceptionCache cleanup. Therefore, the inserts roll
// the head pointer forward to the first live ExceptionCache, so that the new
// next pointers always point at live ExceptionCaches, that are not removed due
// to concurrent ExceptionCache cleanup.
ExceptionCache* next = ec->next();
if (Atomic::cmpxchg(&_exception_cache, ec, next) == ec) {
CodeCache::release_exception_cache(ec);
}
continue;
}
ec = exception_cache();
if (ec != NULL) {
new_entry->set_next(ec);
}
}
if (Atomic::cmpxchg(&_exception_cache, ec, new_entry) == ec) {
return;
}
}
}
void CompiledMethod::clean_exception_cache() {
// For each nmethod, only a single thread may call this cleanup function
// at the same time, whether called in STW cleanup or concurrent cleanup.
// Note that if the GC is processing exception cache cleaning in a concurrent phase,
// then a single writer may contend with cleaning up the head pointer to the
// first ExceptionCache node that has a Klass* that is alive. That is fine,
// as long as there is no concurrent cleanup of next pointers from concurrent writers.
// And the concurrent writers do not clean up next pointers, only the head.
// Also note that concurent readers will walk through Klass* pointers that are not
// alive. That does not cause ABA problems, because Klass* is deleted after
// a handshake with all threads, after all stale ExceptionCaches have been
// unlinked. That is also when the CodeCache::exception_cache_purge_list()
// is deleted, with all ExceptionCache entries that were cleaned concurrently.
// That similarly implies that CAS operations on ExceptionCache entries do not
// suffer from ABA problems as unlinking and deletion is separated by a global
// handshake operation.
ExceptionCache* prev = NULL;
ExceptionCache* curr = exception_cache_acquire();
while (curr != NULL) {
ExceptionCache* next = curr->next();
if (!curr->exception_type()->is_loader_alive()) {
if (prev == NULL) {
// Try to clean head; this is contended by concurrent inserts, that
// both lazily clean the head, and insert entries at the head. If
// the CAS fails, the operation is restarted.
if (Atomic::cmpxchg(&_exception_cache, curr, next) != curr) {
prev = NULL;
curr = exception_cache_acquire();
continue;
}
} else {
// It is impossible to during cleanup connect the next pointer to
// an ExceptionCache that has not been published before a safepoint
// prior to the cleanup. Therefore, release is not required.
prev->set_next(next);
}
// prev stays the same.
CodeCache::release_exception_cache(curr);
} else {
prev = curr;
}
curr = next;
}
}
// public method for accessing the exception cache
// These are the public access methods.
address CompiledMethod::handler_for_exception_and_pc(Handle exception, address pc) {
// We never grab a lock to read the exception cache, so we may
// have false negatives. This is okay, as it can only happen during
// the first few exception lookups for a given nmethod.
ExceptionCache* ec = exception_cache_acquire();
while (ec != NULL) {
address ret_val;
if ((ret_val = ec->match(exception,pc)) != NULL) {
return ret_val;
}
ec = ec->next();
}
return NULL;
}
void CompiledMethod::add_handler_for_exception_and_pc(Handle exception, address pc, address handler) {
// There are potential race conditions during exception cache updates, so we
// must own the ExceptionCache_lock before doing ANY modifications. Because
// we don't lock during reads, it is possible to have several threads attempt
// to update the cache with the same data. We need to check for already inserted
// copies of the current data before adding it.
MutexLocker ml(ExceptionCache_lock);
ExceptionCache* target_entry = exception_cache_entry_for_exception(exception);
if (target_entry == NULL || !target_entry->add_address_and_handler(pc,handler)) {
target_entry = new ExceptionCache(exception,pc,handler);
add_exception_cache_entry(target_entry);
}
}
// private method for handling exception cache
// These methods are private, and used to manipulate the exception cache
// directly.
ExceptionCache* CompiledMethod::exception_cache_entry_for_exception(Handle exception) {
ExceptionCache* ec = exception_cache_acquire();
while (ec != NULL) {
if (ec->match_exception_with_space(exception)) {
return ec;
}
ec = ec->next();
}
return NULL;
}
//-------------end of code for ExceptionCache--------------
bool CompiledMethod::is_at_poll_return(address pc) {
RelocIterator iter(this, pc, pc+1);
while (iter.next()) {
if (iter.type() == relocInfo::poll_return_type)
return true;
}
return false;
}
bool CompiledMethod::is_at_poll_or_poll_return(address pc) {
RelocIterator iter(this, pc, pc+1);
while (iter.next()) {
relocInfo::relocType t = iter.type();
if (t == relocInfo::poll_return_type || t == relocInfo::poll_type)
return true;
}
return false;
}
void CompiledMethod::verify_oop_relocations() {
// Ensure sure that the code matches the current oop values
RelocIterator iter(this, NULL, NULL);
while (iter.next()) {
if (iter.type() == relocInfo::oop_type) {
oop_Relocation* reloc = iter.oop_reloc();
if (!reloc->oop_is_immediate()) {
reloc->verify_oop_relocation();
}
}
}
}
ScopeDesc* CompiledMethod::scope_desc_at(address pc) {
PcDesc* pd = pc_desc_at(pc);
guarantee(pd != NULL, "scope must be present");
return new ScopeDesc(this, pd->scope_decode_offset(),
pd->obj_decode_offset(), pd->should_reexecute(), pd->rethrow_exception(),
pd->return_oop());
}
ScopeDesc* CompiledMethod::scope_desc_near(address pc) {
PcDesc* pd = pc_desc_near(pc);
guarantee(pd != NULL, "scope must be present");
return new ScopeDesc(this, pd->scope_decode_offset(),
pd->obj_decode_offset(), pd->should_reexecute(), pd->rethrow_exception(),
pd->return_oop());
}
address CompiledMethod::oops_reloc_begin() const {
// If the method is not entrant or zombie then a JMP is plastered over the
// first few bytes. If an oop in the old code was there, that oop
// should not get GC'd. Skip the first few bytes of oops on
// not-entrant methods.
if (frame_complete_offset() != CodeOffsets::frame_never_safe &&
code_begin() + frame_complete_offset() >
verified_entry_point() + NativeJump::instruction_size)
{
// If we have a frame_complete_offset after the native jump, then there
// is no point trying to look for oops before that. This is a requirement
// for being allowed to scan oops concurrently.
return code_begin() + frame_complete_offset();
}
// It is not safe to read oops concurrently using entry barriers, if their
// location depend on whether the nmethod is entrant or not.
assert(BarrierSet::barrier_set()->barrier_set_nmethod() == NULL, "Not safe oop scan");
address low_boundary = verified_entry_point();
if (!is_in_use() && is_nmethod()) {
low_boundary += NativeJump::instruction_size;
// %%% Note: On SPARC we patch only a 4-byte trap, not a full NativeJump.
// This means that the low_boundary is going to be a little too high.
// This shouldn't matter, since oops of non-entrant methods are never used.
// In fact, why are we bothering to look at oops in a non-entrant method??
}
return low_boundary;
}
int CompiledMethod::verify_icholder_relocations() {
ResourceMark rm;
int count = 0;
RelocIterator iter(this);
while(iter.next()) {
if (iter.type() == relocInfo::virtual_call_type) {
if (CompiledIC::is_icholder_call_site(iter.virtual_call_reloc(), this)) {
CompiledIC *ic = CompiledIC_at(&iter);
if (TraceCompiledIC) {
tty->print("noticed icholder " INTPTR_FORMAT " ", p2i(ic->cached_icholder()));
ic->print();
}
assert(ic->cached_icholder() != NULL, "must be non-NULL");
count++;
}
}
}
return count;
}
// Method that knows how to preserve outgoing arguments at call. This method must be
// called with a frame corresponding to a Java invoke
void CompiledMethod::preserve_callee_argument_oops(frame fr, const RegisterMap *reg_map, OopClosure* f) {
if (method() != NULL && !method()->is_native()) {
address pc = fr.pc();
SimpleScopeDesc ssd(this, pc);
if (ssd.is_optimized_linkToNative()) return; // call was replaced
Bytecode_invoke call(methodHandle(Thread::current(), ssd.method()), ssd.bci());
bool has_receiver = call.has_receiver();
bool has_appendix = call.has_appendix();
Symbol* signature = call.signature();
// The method attached by JIT-compilers should be used, if present.
// Bytecode can be inaccurate in such case.
Method* callee = attached_method_before_pc(pc);
if (callee != NULL) {
has_receiver = !(callee->access_flags().is_static());
has_appendix = false;
signature = callee->signature();
}
fr.oops_compiled_arguments_do(signature, has_receiver, has_appendix, reg_map, f);
}
}
Method* CompiledMethod::attached_method(address call_instr) {
assert(code_contains(call_instr), "not part of the nmethod");
RelocIterator iter(this, call_instr, call_instr + 1);
while (iter.next()) {
if (iter.addr() == call_instr) {
switch(iter.type()) {
case relocInfo::static_call_type: return iter.static_call_reloc()->method_value();
case relocInfo::opt_virtual_call_type: return iter.opt_virtual_call_reloc()->method_value();
case relocInfo::virtual_call_type: return iter.virtual_call_reloc()->method_value();
default: break;
}
}
}
return NULL; // not found
}
Method* CompiledMethod::attached_method_before_pc(address pc) {
if (NativeCall::is_call_before(pc)) {
NativeCall* ncall = nativeCall_before(pc);
return attached_method(ncall->instruction_address());
}
return NULL; // not a call
}
void CompiledMethod::clear_inline_caches() {
assert(SafepointSynchronize::is_at_safepoint(), "cleaning of IC's only allowed at safepoint");
if (is_zombie()) {
return;
}
RelocIterator iter(this);
while (iter.next()) {
iter.reloc()->clear_inline_cache();
}
}
// Clear IC callsites, releasing ICStubs of all compiled ICs
// as well as any associated CompiledICHolders.
void CompiledMethod::clear_ic_callsites() {
assert(CompiledICLocker::is_safe(this), "mt unsafe call");
ResourceMark rm;
RelocIterator iter(this);
while(iter.next()) {
if (iter.type() == relocInfo::virtual_call_type) {
CompiledIC* ic = CompiledIC_at(&iter);
ic->set_to_clean(false);
}
}
}
#ifdef ASSERT
// Check class_loader is alive for this bit of metadata.
class CheckClass : public MetadataClosure {
void do_metadata(Metadata* md) {
Klass* klass = NULL;
if (md->is_klass()) {
klass = ((Klass*)md);
} else if (md->is_method()) {
klass = ((Method*)md)->method_holder();
} else if (md->is_methodData()) {
klass = ((MethodData*)md)->method()->method_holder();
} else {
md->print();
ShouldNotReachHere();
}
assert(klass->is_loader_alive(), "must be alive");
}
};
#endif // ASSERT
bool CompiledMethod::clean_ic_if_metadata_is_dead(CompiledIC *ic) {
if (ic->is_clean()) {
return true;
}
if (ic->is_icholder_call()) {
// The only exception is compiledICHolder metdata which may
// yet be marked below. (We check this further below).
CompiledICHolder* cichk_metdata = ic->cached_icholder();
if (cichk_metdata->is_loader_alive()) {
return true;
}
} else {
Metadata* ic_metdata = ic->cached_metadata();
if (ic_metdata != NULL) {
if (ic_metdata->is_klass()) {
if (((Klass*)ic_metdata)->is_loader_alive()) {
return true;
}
} else if (ic_metdata->is_method()) {
Method* method = (Method*)ic_metdata;
assert(!method->is_old(), "old method should have been cleaned");
if (method->method_holder()->is_loader_alive()) {
return true;
}
} else {
ShouldNotReachHere();
}
}
}
return ic->set_to_clean();
}
// Clean references to unloaded nmethods at addr from this one, which is not unloaded.
template <class CompiledICorStaticCall>
static bool clean_if_nmethod_is_unloaded(CompiledICorStaticCall *ic, address addr, CompiledMethod* from,
bool clean_all) {
// Ok, to lookup references to zombies here
CodeBlob *cb = CodeCache::find_blob_unsafe(addr);
CompiledMethod* nm = (cb != NULL) ? cb->as_compiled_method_or_null() : NULL;
if (nm != NULL) {
// Clean inline caches pointing to both zombie and not_entrant methods
if (clean_all || !nm->is_in_use() || nm->is_unloading() || (nm->method()->code() != nm)) {
// Inline cache cleaning should only be initiated on CompiledMethods that have been
// observed to be is_alive(). However, with concurrent code cache unloading, it is
// possible that by now, the state has become !is_alive. This can happen in two ways:
// 1) It can be racingly flipped to unloaded if the nmethod // being cleaned (from the
// sweeper) is_unloading(). This is fine, because if that happens, then the inline
// caches have already been cleaned under the same CompiledICLocker that we now hold during
// inline cache cleaning, and we will simply walk the inline caches again, and likely not
// find much of interest to clean. However, this race prevents us from asserting that the
// nmethod is_alive(). The is_unloading() function is completely monotonic; once set due
// to an oop dying, it remains set forever until freed. Because of that, all unloaded
// nmethods are is_unloading(), but notably, an unloaded nmethod may also subsequently
// become zombie (when the sweeper converts it to zombie).
// 2) It can be racingly flipped to zombie if the nmethod being cleaned (by the concurrent
// GC) cleans a zombie nmethod that is concurrently made zombie by the sweeper. In this
// scenario, the sweeper will first transition the nmethod to zombie, and then when
// unregistering from the GC, it will wait until the GC is done. The GC will then clean
// the inline caches *with IC stubs*, even though no IC stubs are needed. This is fine,
// as long as the IC stubs are guaranteed to be released until the next safepoint, where
// IC finalization requires live IC stubs to not be associated with zombie nmethods.
// This is guaranteed, because the sweeper does not have a single safepoint check until
// after it completes the whole transition function; it will wake up after the GC is
// done with concurrent code cache cleaning (which blocks out safepoints using the
// suspendible threads set), and then call clear_ic_callsites, which will release the
// associated IC stubs, before a subsequent safepoint poll can be reached. This
// guarantees that the spuriously created IC stubs are released appropriately before
// IC finalization in a safepoint gets to run. Therefore, this race is fine. This is also
// valid in a scenario where an inline cache of a zombie nmethod gets a spurious IC stub,
// and then when cleaning another inline cache, fails to request an IC stub because we
// exhausted the IC stub buffer. In this scenario, the GC will request a safepoint after
// yielding the suspendible therad set, effectively unblocking safepoints. Before such
// a safepoint can be reached, the sweeper similarly has to wake up, clear the IC stubs,
// and reach the next safepoint poll, after the whole transition function has completed.
// Due to the various races that can cause an nmethod to first be is_alive() and then
// racingly become !is_alive(), it is unfortunately not possible to assert the nmethod
// is_alive(), !is_unloaded() or !is_zombie() here.
if (!ic->set_to_clean(!from->is_unloading())) {
return false;
}
assert(ic->is_clean(), "nmethod " PTR_FORMAT "not clean %s", p2i(from), from->method()->name_and_sig_as_C_string());
}
}
return true;
}
static bool clean_if_nmethod_is_unloaded(CompiledIC *ic, CompiledMethod* from,
bool clean_all) {
return clean_if_nmethod_is_unloaded(ic, ic->ic_destination(), from, clean_all);
}
static bool clean_if_nmethod_is_unloaded(CompiledStaticCall *csc, CompiledMethod* from,
bool clean_all) {
return clean_if_nmethod_is_unloaded(csc, csc->destination(), from, clean_all);
}
// Cleans caches in nmethods that point to either classes that are unloaded
// or nmethods that are unloaded.
//
// Can be called either in parallel by G1 currently or after all
// nmethods are unloaded. Return postponed=true in the parallel case for
// inline caches found that point to nmethods that are not yet visited during
// the do_unloading walk.
bool CompiledMethod::unload_nmethod_caches(bool unloading_occurred) {
ResourceMark rm;
// Exception cache only needs to be called if unloading occurred
if (unloading_occurred) {
clean_exception_cache();
}
if (!cleanup_inline_caches_impl(unloading_occurred, false)) {
return false;
}
#ifdef ASSERT
// Check that the metadata embedded in the nmethod is alive
CheckClass check_class;
metadata_do(&check_class);
#endif
return true;
}
void CompiledMethod::run_nmethod_entry_barrier() {
BarrierSetNMethod* bs_nm = BarrierSet::barrier_set()->barrier_set_nmethod();
if (bs_nm != NULL) {
// We want to keep an invariant that nmethods found through iterations of a Thread's
// nmethods found in safepoints have gone through an entry barrier and are not armed.
// By calling this nmethod entry barrier, it plays along and acts
// like any other nmethod found on the stack of a thread (fewer surprises).
nmethod* nm = as_nmethod_or_null();
if (nm != NULL) {
bool alive = bs_nm->nmethod_entry_barrier(nm);
assert(alive, "should be alive");
}
}
}
void CompiledMethod::cleanup_inline_caches(bool clean_all) {
for (;;) {
ICRefillVerifier ic_refill_verifier;
{ CompiledICLocker ic_locker(this);
if (cleanup_inline_caches_impl(false, clean_all)) {
return;
}
}
// Call this nmethod entry barrier from the sweeper.
run_nmethod_entry_barrier();
InlineCacheBuffer::refill_ic_stubs();
}
}
// Called to clean up after class unloading for live nmethods and from the sweeper
// for all methods.
bool CompiledMethod::cleanup_inline_caches_impl(bool unloading_occurred, bool clean_all) {
assert(CompiledICLocker::is_safe(this), "mt unsafe call");
ResourceMark rm;
// Find all calls in an nmethod and clear the ones that point to non-entrant,
// zombie and unloaded nmethods.
RelocIterator iter(this, oops_reloc_begin());
bool is_in_static_stub = false;
while(iter.next()) {
switch (iter.type()) {
case relocInfo::virtual_call_type:
if (unloading_occurred) {
// If class unloading occurred we first clear ICs where the cached metadata
// is referring to an unloaded klass or method.
if (!clean_ic_if_metadata_is_dead(CompiledIC_at(&iter))) {
return false;
}
}
if (!clean_if_nmethod_is_unloaded(CompiledIC_at(&iter), this, clean_all)) {
return false;
}
break;
case relocInfo::opt_virtual_call_type:
if (!clean_if_nmethod_is_unloaded(CompiledIC_at(&iter), this, clean_all)) {
return false;
}
break;
case relocInfo::static_call_type:
if (!clean_if_nmethod_is_unloaded(compiledStaticCall_at(iter.reloc()), this, clean_all)) {
return false;
}
break;
case relocInfo::static_stub_type: {
is_in_static_stub = true;
break;
}
case relocInfo::metadata_type: {
// Only the metadata relocations contained in static/opt virtual call stubs
// contains the Method* passed to c2i adapters. It is the only metadata
// relocation that needs to be walked, as it is the one metadata relocation
// that violates the invariant that all metadata relocations have an oop
// in the compiled method (due to deferred resolution and code patching).
// This causes dead metadata to remain in compiled methods that are not
// unloading. Unless these slippery metadata relocations of the static
// stubs are at least cleared, subsequent class redefinition operations
// will access potentially free memory, and JavaThread execution
// concurrent to class unloading may call c2i adapters with dead methods.
if (!is_in_static_stub) {
// The first metadata relocation after a static stub relocation is the
// metadata relocation of the static stub used to pass the Method* to
// c2i adapters.
continue;
}
is_in_static_stub = false;
if (is_unloading()) {
// If the nmethod itself is dying, then it may point at dead metadata.
// Nobody should follow that metadata; it is strictly unsafe.
continue;
}
metadata_Relocation* r = iter.metadata_reloc();
Metadata* md = r->metadata_value();
if (md != NULL && md->is_method()) {
Method* method = static_cast<Method*>(md);
if (!method->method_holder()->is_loader_alive()) {
Atomic::store(r->metadata_addr(), (Method*)NULL);
if (!r->metadata_is_immediate()) {
r->fix_metadata_relocation();
}
}
}
break;
}
default:
break;
}
}
return true;
}
// Iterating over all nmethods, e.g. with the help of CodeCache::nmethods_do(fun) was found
// to not be inherently safe. There is a chance that fields are seen which are not properly
// initialized. This happens despite the fact that nmethods_do() asserts the CodeCache_lock
// to be held.
// To bundle knowledge about necessary checks in one place, this function was introduced.
// It is not claimed that these checks are sufficient, but they were found to be necessary.
bool CompiledMethod::nmethod_access_is_safe(nmethod* nm) {
Method* method = (nm == NULL) ? NULL : nm->method(); // nm->method() may be uninitialized, i.e. != NULL, but invalid
return (nm != NULL) && (method != NULL) && (method->signature() != NULL) &&
!nm->is_zombie() && !nm->is_not_installed() &&
os::is_readable_pointer(method) &&
os::is_readable_pointer(method->constants()) &&
os::is_readable_pointer(method->signature());
}
address CompiledMethod::continuation_for_implicit_exception(address pc, bool for_div0_check) {
// Exception happened outside inline-cache check code => we are inside
// an active nmethod => use cpc to determine a return address
int exception_offset = pc - code_begin();
int cont_offset = ImplicitExceptionTable(this).continuation_offset( exception_offset );
#ifdef ASSERT
if (cont_offset == 0) {
Thread* thread = Thread::current();
ResetNoHandleMark rnm; // Might be called from LEAF/QUICK ENTRY
HandleMark hm(thread);
ResourceMark rm(thread);
CodeBlob* cb = CodeCache::find_blob(pc);
assert(cb != NULL && cb == this, "");
ttyLocker ttyl;
tty->print_cr("implicit exception happened at " INTPTR_FORMAT, p2i(pc));
print();
method()->print_codes();
print_code();
print_pcs();
}
#endif
if (cont_offset == 0) {
// Let the normal error handling report the exception
return NULL;
}
if (cont_offset == exception_offset) {
#if INCLUDE_JVMCI
Deoptimization::DeoptReason deopt_reason = for_div0_check ? Deoptimization::Reason_div0_check : Deoptimization::Reason_null_check;
JavaThread *thread = JavaThread::current();
thread->set_jvmci_implicit_exception_pc(pc);
thread->set_pending_deoptimization(Deoptimization::make_trap_request(deopt_reason,
Deoptimization::Action_reinterpret));
return (SharedRuntime::deopt_blob()->implicit_exception_uncommon_trap());
#else
ShouldNotReachHere();
#endif
}
return code_begin() + cont_offset;
}
class HasEvolDependency : public MetadataClosure {
bool _has_evol_dependency;
public:
HasEvolDependency() : _has_evol_dependency(false) {}
void do_metadata(Metadata* md) {
if (md->is_method()) {
Method* method = (Method*)md;
if (method->is_old()) {
_has_evol_dependency = true;
}
}
}
bool has_evol_dependency() const { return _has_evol_dependency; }
};
bool CompiledMethod::has_evol_metadata() {
// Check the metadata in relocIter and CompiledIC and also deoptimize
// any nmethod that has reference to old methods.
HasEvolDependency check_evol;
metadata_do(&check_evol);
if (check_evol.has_evol_dependency() && log_is_enabled(Debug, redefine, class, nmethod)) {
ResourceMark rm;
log_debug(redefine, class, nmethod)
("Found evol dependency of nmethod %s.%s(%s) compile_id=%d on in nmethod metadata",
_method->method_holder()->external_name(),
_method->name()->as_C_string(),
_method->signature()->as_C_string(),
compile_id());
}
return check_evol.has_evol_dependency();
}
|
c90e6df621701ffc6d69944b863c1520cbf65e34 | 30fee353c5a3c219b5f1c20aef313f3fae07d6cf | /r2_sk_mm/src/events.cpp | c33ae34c47124d98068b184f4b371000d3f4ea8a | [] | no_license | edduby/Symulacja_cyfrowa_Port | 65096ad643aba772d2da9011cc8e55de50cd549f | fd5694d1cdb69c3dd05e33ab5a07a59bcad16101 | refs/heads/master | 2020-03-17T22:31:20.511939 | 2018-05-18T22:43:59 | 2018-05-18T22:43:59 | 134,007,047 | 0 | 0 | null | null | null | null | WINDOWS-1250 | C++ | false | false | 15,450 | cpp | events.cpp | /********************************************//**
* \file events.cpp
* \brief Time events.
* \author Maciej Maciejewski
* \date 2015-04-15
***********************************************/
#include "sc.h"
using namespace symulacja;
/////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////pojawienie sie statku///////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
pojawienieSieStatku::pojawienieSieStatku(double in_lambda, int in_seed): Event(sim_clock + Exponential(in_lambda, in_seed))
{
lambda = in_lambda;
seed = in_seed;
}
void pojawienieSieStatku::execute(){
/////////////////////////////////pojawienie sie staku////////////////////////////////////
Kanal *temp=NULL;
double czasTemp=0;
agenda.schedule(new pojawienieSieStatku((lambda), seed));
Statek *StatekPlynie;
Statek *tempStatek;
Zrodlo Generator;
StatekPlynie = Generator.generacjaStatku();
StatekPlynie->czasPrzybycia = sim_clock;
ileWygenerowalem++;
qMorze.statekZajmujeMiejsce(StatekPlynie);
////////////////////////////////////////////////////////////////////////////////////////////////////////
tempStatek = qMorze.wyborStatkuDoZwolnienia(KanalJeden1, KanalDwa2, KanalTrzy3, KanalCztery4, NowyPort);
if (tempStatek)
{
temp = tempStatek->wyborKanalu(KanalJeden1, KanalDwa2, KanalTrzy3, KanalCztery4);
NowyPort.zajecieNarzedzi(tempStatek);
qMorze.statekZwalniaMiejsce(tempStatek);
if (temp->numer == KanalJeden1.numer){
KanalJeden1.zajecieKanaluDo(tempStatek);
tempStatek->numerKanalu = 1;
}
else if (temp->numer == KanalDwa2.numer){
KanalDwa2.zajecieKanaluDo(tempStatek);
tempStatek->numerKanalu = 2;
}
else if (temp->numer == KanalTrzy3.numer){
KanalTrzy3.zajecieKanaluDo(tempStatek);
tempStatek->numerKanalu = 3;
}
else if (temp->numer == KanalCztery4.numer){
KanalCztery4.zajecieKanaluDo(tempStatek);
tempStatek->numerKanalu = 4;
}
//////////////////////////////=============czas===============//////////////////////////////
i++; //ilosc statków opuszczajacych port
tempStatek->czazOczekiwania(sim_clock - tempStatek->czasPrzybycia);
czasTemp = tempStatek->czasPrzeplyniecia(temp);
agenda.schedule(new wyplyniecieZToru(czasTemp, tempStatek));
//////////////////////////////=============czas===============//////////////////////////////
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////wyplyniecie z toru//////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
wyplyniecieZToru::wyplyniecieZToru(double in_czas,Statek* in_StatekPlynie) : Event(sim_clock + in_czas){
czas = in_czas;
StatekPlynie = in_StatekPlynie;
}
void wyplyniecieZToru::execute(){
double czasTemp = 0;
Statek *tempStatek;
//cerr << ":///////////////////////////////Wyplyniecie z toru do portu///////////////////////////////////\n";
czasTemp = StatekPlynie->czasRozladunku();
agenda.schedule(new konczenieObslugi(czasTemp, StatekPlynie));
Kanal *temp = NULL;
int tkanal = 0;
//--zwolnienie kanalu
tkanal=(StatekPlynie->wKtorymTorzeJestem(StatekPlynie));
if (tkanal == KanalJeden1.numer){
KanalJeden1.zwolnienieKanalu(StatekPlynie);
}
else if (tkanal == KanalDwa2.numer){
KanalDwa2.zwolnienieKanalu(StatekPlynie);
}
else if (tkanal == KanalTrzy3.numer){
KanalTrzy3.zwolnienieKanalu(StatekPlynie);
}
else if (tkanal == KanalCztery4.numer){
KanalCztery4.zwolnienieKanalu(StatekPlynie);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////
tempStatek = qMorze.wyborStatkuDoZwolnienia(KanalJeden1, KanalDwa2, KanalTrzy3, KanalCztery4, NowyPort);
if (tempStatek)
{
temp = tempStatek->wyborKanalu(KanalJeden1, KanalDwa2, KanalTrzy3, KanalCztery4);
NowyPort.zajecieNarzedzi(tempStatek);
qMorze.statekZwalniaMiejsce(tempStatek);
if (temp->numer == KanalJeden1.numer){
KanalJeden1.zajecieKanaluDo(tempStatek);
tempStatek->numerKanalu = 1;
}
else if (temp->numer == KanalDwa2.numer){
KanalDwa2.zajecieKanaluDo(tempStatek);
tempStatek->numerKanalu = 2;
}
else if (temp->numer == KanalTrzy3.numer){
KanalTrzy3.zajecieKanaluDo(tempStatek);
tempStatek->numerKanalu = 3;
}
else if (temp->numer == KanalCztery4.numer){
KanalCztery4.zajecieKanaluDo(tempStatek);
tempStatek->numerKanalu = 4;
}
//////////////////////////////=============czas===============//////////////////////////////
czas = czas + (sim_clock - tempStatek->czasPrzybycia);
i++;
tempStatek->czazOczekiwania(sim_clock - tempStatek->czasPrzybycia);
czasTemp = tempStatek->czasPrzeplyniecia(temp);
//cerr << "Czas przelyniecia statku:" << czasTemp << "\n";
agenda.schedule(new wyplyniecieZToru(czasTemp, tempStatek));
//////////////////////////////=============czas===============//////////////////////////////
}
////////////////////////////////////////////////////////////////////////////////////////////
tempStatek = qPort.wyborStatkuDoZwolnieniaZportu(KanalJeden1, KanalDwa2, KanalTrzy3, KanalCztery4, NowyPort);
if (tempStatek)
{
temp = tempStatek->wyborKanalu(KanalJeden1, KanalDwa2, KanalTrzy3, KanalCztery4);
if (temp->numer == KanalJeden1.numer){
KanalJeden1.zajecieKanaluZ(tempStatek);
tempStatek->numerKanalu = 1;
}
else if (temp->numer == KanalDwa2.numer){
KanalDwa2.zajecieKanaluZ(tempStatek);
tempStatek->numerKanalu = 2;
}
else if (temp->numer == KanalTrzy3.numer){
KanalTrzy3.zajecieKanaluZ(tempStatek);
tempStatek->numerKanalu = 3;
}
else if (temp->numer == KanalCztery4.numer){
KanalCztery4.zajecieKanaluZ(tempStatek);
tempStatek->numerKanalu = 4;
}
qPort.statekZwalniaMiejsce(tempStatek);
//////////////////////////////=============czas===============//////////////////////////////
czas = tempStatek->czasPrzeplyniecia(temp);
NowyPort.zwolnienieNarzedzi(tempStatek);
agenda.schedule(new opuszczenieToru(czas, tempStatek));
//////////////////////////////=============czas===============/////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////konczenie obslugi//////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
konczenieObslugi::konczenieObslugi(double in_czas, Statek* in_statek) : Event(sim_clock + in_czas){
czas=in_czas;
StatekPlynie = in_statek;
}
void konczenieObslugi::execute(){
// cerr << ":///////////////////////////////ZAKONCZENIE OBSLUGI////////////////////////////////////\n";
double czasTemp=0;
Kanal *temp;
Statek *tempStatek;
qPort.statekZajmujeMiejsce(StatekPlynie);
tempStatek = qPort.wyborStatkuDoZwolnieniaZportu(KanalJeden1, KanalDwa2, KanalTrzy3, KanalCztery4, NowyPort);
if (tempStatek)
{
temp = tempStatek->wyborKanalu(KanalJeden1, KanalDwa2, KanalTrzy3, KanalCztery4);
if (temp->numer == KanalJeden1.numer){
KanalJeden1.zajecieKanaluZ(tempStatek);
tempStatek->numerKanalu = 1;
}
else if (temp->numer == KanalDwa2.numer){
KanalDwa2.zajecieKanaluZ(tempStatek);
tempStatek->numerKanalu = 2;
}
else if (temp->numer == KanalTrzy3.numer){
KanalTrzy3.zajecieKanaluZ(tempStatek);
tempStatek->numerKanalu = 3;
}
else if (temp->numer == KanalCztery4.numer){
KanalCztery4.zajecieKanaluZ(tempStatek);
tempStatek->numerKanalu = 4;
}
qPort.statekZwalniaMiejsce(tempStatek);
//////////////////////////////=============czas===============//////////////////////////////
czas = tempStatek->czasPrzeplyniecia(temp);
NowyPort.zwolnienieNarzedzi(tempStatek);
agenda.schedule(new opuszczenieToru(czas, tempStatek));
//////////////////////////////=============czas===============/////////////////////////////
}
////////////////////////////////////////////////////////////////////////////////////////////////////////
tempStatek = qMorze.wyborStatkuDoZwolnienia(KanalJeden1, KanalDwa2, KanalTrzy3, KanalCztery4, NowyPort);
if (tempStatek)
{
temp = tempStatek->wyborKanalu(KanalJeden1, KanalDwa2, KanalTrzy3, KanalCztery4);
NowyPort.zajecieNarzedzi(tempStatek);
qMorze.statekZwalniaMiejsce(tempStatek);
if (temp->numer == KanalJeden1.numer){
KanalJeden1.zajecieKanaluDo(tempStatek);
tempStatek->numerKanalu = 1;
}
else if (temp->numer == KanalDwa2.numer){
KanalDwa2.zajecieKanaluDo(tempStatek);
tempStatek->numerKanalu = 2;
}
else if (temp->numer == KanalTrzy3.numer){
KanalTrzy3.zajecieKanaluDo(tempStatek);
tempStatek->numerKanalu = 3;
}
else if (temp->numer == KanalCztery4.numer){
KanalCztery4.zajecieKanaluDo(tempStatek);
tempStatek->numerKanalu = 4;
}
//////////////////////////////=============czas===============//////////////////////////////
czas = czas + (sim_clock - tempStatek->czasPrzybycia);
i++;
tempStatek->czazOczekiwania(sim_clock - tempStatek->czasPrzybycia);
czasTemp = tempStatek->czasPrzeplyniecia(temp);
agenda.schedule(new wyplyniecieZToru(czasTemp, tempStatek));
//////////////////////////////=============czas===============//////////////////////////////
}
////////////////////////////////////////////////////////////////////////////////////////////
tempStatek = qPort.wyborStatkuDoZwolnieniaZportu(KanalJeden1, KanalDwa2, KanalTrzy3, KanalCztery4, NowyPort);
if (tempStatek)
{
temp = tempStatek->wyborKanalu(KanalJeden1, KanalDwa2, KanalTrzy3, KanalCztery4);
if (temp->numer == KanalJeden1.numer){
KanalJeden1.zajecieKanaluZ(tempStatek);
tempStatek->numerKanalu = 1;
}
else if (temp->numer == KanalDwa2.numer){
KanalDwa2.zajecieKanaluZ(tempStatek);
tempStatek->numerKanalu = 2;
}
else if (temp->numer == KanalTrzy3.numer){
KanalTrzy3.zajecieKanaluZ(tempStatek);
tempStatek->numerKanalu = 3;
}
else if (temp->numer == KanalCztery4.numer){
KanalCztery4.zajecieKanaluZ(tempStatek);
tempStatek->numerKanalu = 4;
}
qPort.statekZwalniaMiejsce(tempStatek);
//////////////////////////////=============czas===============//////////////////////////////
czas = tempStatek->czasPrzeplyniecia(temp);
NowyPort.zwolnienieNarzedzi(tempStatek);
agenda.schedule(new opuszczenieToru(czas, tempStatek));
//////////////////////////////=============czas===============/////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////
}
}
opuszczenieToru::opuszczenieToru(double in_czas, Statek* in_statek) : Event(sim_clock + in_czas){
czas = in_czas;
StatekPlynie = in_statek;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////opuszczenie toru//////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void opuszczenieToru::execute(){
// ///////////////////////////////opuszczenie toru do morza////////////////////////////////////
double czasTemp=0;
Kanal *temp = NULL;
Statek *tempStatek;
liczbaWszystkich++;
int tkanal = 0;
//=-------------------zwolnic kanal!
tkanal = (StatekPlynie->wKtorymTorzeJestem(StatekPlynie));
if (tkanal == KanalJeden1.numer){
KanalJeden1.zwolnienieKanalu(StatekPlynie);
}
else if (tkanal == KanalDwa2.numer){
KanalDwa2.zwolnienieKanalu(StatekPlynie);
}
else if (tkanal == KanalTrzy3.numer){
KanalTrzy3.zwolnienieKanalu(StatekPlynie);
}
else if (tkanal == KanalCztery4.numer){
KanalCztery4.zwolnienieKanalu(StatekPlynie);
}
statkiWyplywajace++;
delete StatekPlynie;
////////////////////////////////////////////////////////////////////////////////////////////////////////
tempStatek = qMorze.wyborStatkuDoZwolnienia(KanalJeden1, KanalDwa2, KanalTrzy3, KanalCztery4, NowyPort);
if (tempStatek)
{
temp = tempStatek->wyborKanalu(KanalJeden1, KanalDwa2, KanalTrzy3, KanalCztery4);
NowyPort.zajecieNarzedzi(tempStatek);
qMorze.statekZwalniaMiejsce(tempStatek);
if (temp->numer == KanalJeden1.numer){
KanalJeden1.zajecieKanaluDo(tempStatek);
tempStatek->numerKanalu = 1;
}
else if (temp->numer == KanalDwa2.numer){
KanalDwa2.zajecieKanaluDo(tempStatek);
tempStatek->numerKanalu = 2;
}
else if (temp->numer == KanalTrzy3.numer){
KanalTrzy3.zajecieKanaluDo(tempStatek);
tempStatek->numerKanalu = 3;
}
else if (temp->numer == KanalCztery4.numer){
KanalCztery4.zajecieKanaluDo(tempStatek);
tempStatek->numerKanalu = 4;
}
//////////////////////////////=============czas===============//////////////////////////////
czas = czas + (sim_clock - tempStatek->czasPrzybycia);
i++;
tempStatek->czazOczekiwania(sim_clock - tempStatek->czasPrzybycia);
czasTemp = tempStatek->czasPrzeplyniecia(temp);
agenda.schedule(new wyplyniecieZToru(czasTemp, tempStatek));
//////////////////////////////=============czas===============//////////////////////////////
}
////////////////////////////////////////////////////////////////////////////////////////////
tempStatek = qPort.wyborStatkuDoZwolnieniaZportu(KanalJeden1, KanalDwa2, KanalTrzy3, KanalCztery4, NowyPort);
if (tempStatek)
{
temp = tempStatek->wyborKanalu(KanalJeden1, KanalDwa2, KanalTrzy3, KanalCztery4);
if (temp->numer == KanalJeden1.numer){
KanalJeden1.zajecieKanaluZ(tempStatek);
tempStatek->numerKanalu = 1;
}
else if (temp->numer == KanalDwa2.numer){
KanalDwa2.zajecieKanaluZ(tempStatek);
tempStatek->numerKanalu = 2;
}
else if (temp->numer == KanalTrzy3.numer){
KanalTrzy3.zajecieKanaluZ(tempStatek);
tempStatek->numerKanalu = 3;
}
else if (temp->numer == KanalCztery4.numer){
KanalCztery4.zajecieKanaluZ(tempStatek);
tempStatek->numerKanalu = 4;
}
qPort.statekZwalniaMiejsce(tempStatek);
//////////////////////////////=============czas===============//////////////////////////////
czas = tempStatek->czasPrzeplyniecia(temp);
NowyPort.zwolnienieNarzedzi(tempStatek);
agenda.schedule(new opuszczenieToru(czas, tempStatek));
//////////////////////////////=============czas===============/////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////
}
}
/////////////////////////////////////////////////
//***********************************************
|
eec9335883f6f5b342839ea6d02afd4e41cbaeef | b32cd23f4a35f9da6c72ad6b36407e4c8f4c1d98 | /dotarg.hpp | b237c762a63950ec717540eda60ca86948dcbab3 | [] | no_license | justanothercoder/Compiler | 0ea2936c679ca7340217ce636fce603c98293144 | 79a44744be646cf8edfeefff44c28f776889ed6e | refs/heads/master | 2021-03-12T19:59:08.085875 | 2015-03-20T04:39:46 | 2015-03-20T04:39:46 | 18,298,874 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 534 | hpp | dotarg.hpp | #ifndef _DOTARG_HPP_
#define _DOTARG_HPP_
#include <memory>
#include "arg.hpp"
class VarSymbol;
class DotArg : public Arg
{
public:
DotArg(Argument expr, int offset, const VarSymbol* member);
std::string toString() const override;
void gen(const Block& block, CodeObject& code_obj) const override;
const Type* type() const override;
Arg* expr() const;
int offset() const;
const VarSymbol* member() const;
private:
Argument expr_;
int offset_;
const VarSymbol* member_;
};
#endif
|
7aff7dedf455103bc8a7f17606fb9fe5d86a394c | 8146f410595c1cdf9681dc8ead2f05fa31db4bda | /SnowfallEngine/UIComponent.h | 79cf282427d8b743289445b53945990fadc6841d | [] | no_license | flyhex/Snowfall-New | 39eb825239cf09308dd5386c09929aa418ef8b22 | 85d3ac4b52f6c15c3485ce338dff6a58d7264756 | refs/heads/master | 2022-02-27T20:32:59.277773 | 2019-11-10T23:31:09 | 2019-11-10T23:31:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,458 | h | UIComponent.h | #pragma once
#include <memory>
#include <string>
#include "UIEvent.h"
#include "UIRect.h"
#include "InputManager.h"
#include "export.h"
class UIContext;
class UIComponent;
class UIRenderer;
class MouseMotionEventArgs
{
public:
glm::vec2 OldPosition;
glm::vec2 NewPosition;
};
class MouseButtonEventArgs
{
public:
MouseButton Button;
glm::vec2 MousePosition;
bool State;
bool Repeating;
bool Primary;
bool Secondary;
};
class KeyEventArgs
{
public:
Key Key;
unsigned ModifierFlag;
bool State;
bool Repeating;
};
class TextEventArgs
{
public:
char Character;
};
class ScrollEventArgs
{
public:
glm::vec2 OldPosition;
glm::vec2 NewPosition;
};
class FocusEventArgs
{
public:
UIComponent *OldFocused;
UIComponent *NewFocused;
};
class BoundsEventArgs
{
public:
UIRect OldBounds;
UIRect NewBounds;
};
class BoolEventArgs
{
public:
bool OldValue;
bool NewValue;
};
class RenderEventArgs
{
public:
UIRenderer *Renderer;
};
class UIComponent
{
public:
SNOWFALLENGINE_API UIComponent();
SNOWFALLENGINE_API ~UIComponent();
SNOWFALLENGINE_API void Focus();
SNOWFALLENGINE_API void Unfocus();
SNOWFALLENGINE_API bool IsFocused();
SNOWFALLENGINE_API void AddComponent(UIComponent *component);
SNOWFALLENGINE_API void RemoveComponent(UIComponent *component);
SNOWFALLENGINE_API std::vector<UIComponent *>& GetChildren();
SNOWFALLENGINE_API void SetContext(UIContext *context);
SNOWFALLENGINE_API UIContext *GetContext();
SNOWFALLENGINE_API void Render(UIRenderer *renderer);
SNOWFALLENGINE_API void RenderChildren(UIRenderer *renderer);
SNOWFALLENGINE_API void Resize(Quad2D oldParent, Quad2D newParent);
SNOWFALLENGINE_API void UpdateFocus(UIComponent *lostFocus, UIComponent *gainFocus);
SNOWFALLENGINE_API void SortByZOrder();
SNOWFALLENGINE_API UIComponent *FindTopmostIntersector(Quad2D quad);
template<class T>
std::vector<T *> FindComponentsByType()
{
std::vector<T *> typed;
for (UIComponent *child : m_components)
{
T *t = dynamic_cast<T *>(child);
if (t)
typed.push_back(t);
}
return typed;
}
SNOWFALLENGINE_API UIRect GetBounds();
SNOWFALLENGINE_API void SetBounds(UIRect rect);
SNOWFALLENGINE_API void SetZIndex(int index);
SNOWFALLENGINE_API int GetZIndex();
SNOWFALLENGINE_API void SetVisible(bool visible);
SNOWFALLENGINE_API bool IsVisible();
SNOWFALLENGINE_API void SetEnabled(bool enabled);
SNOWFALLENGINE_API bool IsEnabled();
SNOWFALLENGINE_API void SetDrawingChildren(bool drawing);
SNOWFALLENGINE_API bool IsDrawingChildren();
UIEvent<BoundsEventArgs> BoundsChanged;
UIEvent<BoolEventArgs> VisibleChanged;
UIEvent<BoolEventArgs> EnabledChanged;
UIEvent<RenderEventArgs> OnRender;
UIEvent<FocusEventArgs> GainFocus;
UIEvent<FocusEventArgs> LostFocus;
UIEvent<MouseMotionEventArgs> MouseMove;
UIEvent<MouseMotionEventArgs> MouseEnter;
UIEvent<MouseMotionEventArgs> MouseLeave;
UIEvent<MouseMotionEventArgs> MouseHover;
UIEvent<MouseButtonEventArgs> MouseDown;
UIEvent<MouseButtonEventArgs> MouseUp;
UIEvent<MouseButtonEventArgs> MouseClick;
UIEvent<MouseButtonEventArgs> MouseDoubleClick;
UIEvent<ScrollEventArgs> MouseScroll;
UIEvent<KeyEventArgs> KeyDown;
UIEvent<KeyEventArgs> KeyUp;
UIEvent<TextEventArgs> KeyPress;
UIComponent *Parent;
private:
std::vector<UIComponent *> m_components;
UIContext *m_context;
UIRect m_bounds;
int m_zIndex = -1;
bool m_focused;
bool m_visible;
bool m_enabled;
bool m_drawChildren;
};
|
eebcd68340586a4a1ae607ddf0501e57fcf9ec34 | 942382a44abed5445b113aae35368c4648e3d109 | /main.cpp | 36a41403aab60303a1d56f6f3002082361a6149e | [
"Apache-2.0"
] | permissive | lichang98/raft_demo | b97b7dc325a0e81117c1940e1872fbc50b675bdc | 337bc56d04a4ee24509be7eba02c26ef4e990b55 | refs/heads/master | 2022-09-29T16:45:57.559143 | 2020-06-02T10:41:38 | 2020-06-02T10:41:38 | 268,749,366 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 861 | cpp | main.cpp | #include "system.hpp"
#include "client.hpp"
int main(int argc, char const *argv[])
{
google::InitGoogleLogging(argv[0]);
google::SetLogDestination(google::INFO,"./log/log_info.txt");
google::SetLogDestination(google::ERROR,"./log/log_error.txt");
my_system::MySys sys;
sys.parse_json_config("./sys_config.json");
sys.sys_start();
std::this_thread::sleep_for(std::chrono::seconds(5));
client::MyClient usr_client((char*)"127.0.0.1",61000,my_system::opaque_router->ip_addr,my_system::opaque_router->port);
rpc::rpc_data* data = client::MyClient::file_parser((char*)"client_data.txt");
usr_client.send_msg(data);
std::this_thread::sleep_for(std::chrono::seconds(5));
sys.shutdown();
std::this_thread::sleep_for(std::chrono::seconds(5)); // wait for shutdown
google::ShutdownGoogleLogging();
return 0;
}
|
b0e2b7128873bd1fca595a9ce93907c03042c0f2 | 5ada21656945725ae9cfe1b37fa40907e75510ef | /include/Zygelman.hpp | 54fb0ce122fbdd469d9d6b0f08c61de517421196 | [] | no_license | claudejpschmit/21cmFisher | a2627ea727ccefc5090b146c3b3dff129651128b | 5fd86b2b02317d6b7e6ffd96a89e5b99455c4313 | refs/heads/master | 2021-09-16T07:20:49.423858 | 2018-06-18T12:50:48 | 2018-06-18T12:50:48 | 46,121,270 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 396 | hpp | Zygelman.hpp | #pragma once
#include "Helper.hpp"
/**
* Class that simplifies access to the kappa_10(Tgas) collision rates
* from Zygelman (2005).
*/
class CollisionRates {
public:
CollisionRates();
~CollisionRates();
double kappa10(double z);
double kappa10_T(double T);
private:
spline1dinterpolant kappa_interpolator, kappa_T_interpolator;
};
|
acc3b76067214141648205d5903ae615ef6d1597 | a051877fb2e52b5e10120e1d0556bbaecbe7d044 | /2018-05-09/complex.h | b3001934a16cc4ec8d58ddbda14cf4dcaf5eb8f1 | [] | no_license | kiangelm/Programacion | 93eef763ffee1fa04fd3109b5331f076e73f96d7 | a59553e49d6b63d24ae4075a97443eb13e1fd0f5 | refs/heads/master | 2021-04-15T12:06:27.212840 | 2018-05-25T13:19:37 | 2018-05-25T13:19:37 | 126,487,420 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 320 | h | complex.h | #include <iostream>
#include <cmath>
struct complex {
void print(void);
double real, imag;
complex operator+ (complex b);
complex operator- (complex b);
complex operator* (complex b);
complex & operator= (complex b);
double norm(void);
double ang(void);
double sin(void);
double cos(void);
};
|
d30609c43fd30f6da404d8c181f59f5697ab1f41 | 1002e349cffc6b72faaa69d3969c9c93d100d478 | /Greedy/Coprimme/main.cpp | a50d6092b790cb7e64f4ed32076c9bf0ef82a4da | [] | no_license | shreyansh2000rawat/Datastructure-and-Algorithm | ce1ff69df6e41c6e3e435fc3e533570bc1a7c574 | 335ecf722b646beb2d54ca84b57bd247318c86a9 | refs/heads/master | 2023-02-04T10:30:44.182714 | 2020-12-25T07:04:53 | 2020-12-25T07:04:53 | 291,649,799 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 278 | cpp | main.cpp | #include <iostream>
#include <algorithm>
using namespace std;
int main() {
long long int num = 0;
cin>>num;
for(long long int i = num-2;i>=1;i--){
if(__gcd(num, i)==1)
{
cout<<i<<endl;
break;
}
}
return 0;
}
|
a5855b9dc16068484ac0a08cef50c9ee773e6580 | eac71e4c7f960160887ab5ce675f8b2903ed51bb | /Sesion 3/X68173/Cjt_estudiants.hh | 966fb64271208b34b627dd1acaee6195264adf59 | [
"Apache-2.0"
] | permissive | go3212/FIB-PRO2 | 14947931a37e9f52b154904b2d229785d3a76fbb | 383cc7568583e164d740b87b9e7ad4eb06fee5d9 | refs/heads/main | 2023-06-02T02:34:23.503813 | 2021-06-14T10:20:48 | 2021-06-14T10:20:48 | 341,898,013 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,726 | hh | Cjt_estudiants.hh | #ifndef CONJ_EST_HH
#define CONJ_EST_HH
#include "Estudiant.hh"
#include <vector>
class Cjt_estudiants {
private:
// Tipus de modul: dades
// Descripcio del tipus: representa un conjunt ordenat per DNI d'estudiants
// Es poden consultar i modificar els seus elements (de tipus Estudiant)
// donat un DNI o per posicio en l'ordre
vector<Estudiant> vest;
int nest;
int imax;
static const int MAX_NEST = 20;
/*
Invariant de la representacio:
- vest[0..nest-1] esta ordenat de manera estrictament creixent
pels DNI dels estudiants
- 0 <= nest <= vest.size() = MAX_NEST
*/
void ordenar_cjt_estudiants();
/* Pre: cert */
/* Post: els elements rellevants del parametre implicit estan ordenats
creixentment pels seus DNI */
static int cerca_dicot(const vector<Estudiant>& vest, int left, int right, int x);
/* Pre: vest[left..right] esta ordenat creixentment per DNI,
0<=left, right<vest.size() */
/* Post: si a vest[left..right] hi ha un element amb DNI = x, el resultat es
una posicio que el conte; si no, el resultat es -1 */
public:
//Constructores
Cjt_estudiants();
/* Pre: cert */
/* Post: el resultat es un conjunt d'estudiants buit */
//Destructora
~Cjt_estudiants();
//Modificadores
void afegir_estudiant(const Estudiant& est);
/* Pre: el parametre implicit no conte cap estudiant amb el DNI d'est;
el nombre d'estudiants del p.i. es mes petit que la mida maxima permesa */
/* Post: s'ha afegit l'estudiant est al parametre implicit */
void modificar_estudiant(const Estudiant& est);
/* Pre: existeix un estudiant al parametre implicit amb el DNI d'est */
/* Post: l'estudiant del parametre implicit original amb el dni
d'est, ha quedat substituit per est */
void modificar_iessim(int i, const Estudiant& est);
/* Pre: 1 <= i <= nombre d'estudiants del parametre implicit,
l'element i-essim del conjunt en ordre creixent per DNI conte
un estudiant amb el mateix DNI que est */
/* Post: l'estudiant est ha substituit l'estudiant i-essim
del parametre implicit */
//Consultores
void recalcular_posicio_imax();
int mida() const;
/* Pre: cert */
/* Post: el resultat es el nombre d'estudiants del parametre implicit */
static int mida_maxima();
/* Pre: cert */
/* Post: el resultat es el nombre maxim d'estudiants que pot arribar
a tenir el parametre implicit */
bool existeix_estudiant(int dni) const;
/* Pre: dni >= 0 */
/* Post: el resultat indica si existeix un estudiant al par�metre implicit
amb DNI = dni */
Estudiant consultar_estudiant(int dni) const;
/* Pre: existeix un estudiant al parametre impl�cit amb DNI = dni */
/* Post: el resultat es l'estudiant amb DNI = dni que conte el
parametre implicit */
Estudiant consultar_iessim(int i) const;
/* Pre: 1 <= i <= nombre d'estudiants que conte el parametre implicit */
/* Post: el resultat es l'estudiant i-essim del parametre implicit
en ordre creixent per DNI */
void esborrar_estudiant(int dni);
Estudiant estudiant_nota_max( ) const;
// Lectura i escriptura
void llegir();
/* Pre: estan preparats al canal estandard d'entrada un enter (entre 0 i la
mida maxima permesa per a la classe), que representa el nombre d'elements
que llegirem, i les dades de tal nombre d'estudiants diferents */
/* Post: el parametre implicit conte el conjunt d'estudiants llegits
del canal estandard d'entrada */
void escriure() const;
/* Pre: cert */
/* Post: s'han escrit pel canal estandard de sortida els estudiants del
parametre implicit en ordre ascendent per DNI */
};
#endif
|
afa98ff32c6f118fead3ae51806bfc039e7d8bc9 | cc996d677644d7fcc02e306ecf4c15ec7460a211 | /6383/MiheevaEE/main.cpp | 164b6dc76af49cb881ea22e8627899e936d886a3 | [] | no_license | spasartyom/PiAA | 531f24f38a2010537dac83d09c6c67c960c2de0c | 0ae28c99dc1b899d9853a873252e2d99aef90378 | refs/heads/master | 2020-03-16T17:18:56.152302 | 2018-05-03T05:47:40 | 2018-05-03T05:47:40 | 132,826,411 | 1 | 0 | null | 2018-05-10T00:16:24 | 2018-05-10T00:16:23 | null | UTF-8 | C++ | false | false | 1,951 | cpp | main.cpp | #include <iostream>
#include <fstream>
using namespace std;
const int SIZE = 'z' - 'a'+1;
const double MAX =10000000;
double lable[SIZE];
double m[SIZE][SIZE];
bool isVisited[SIZE];
int prevV[SIZE];
int start,finish;
void read(istream& cin){
start=cin.get()-(int)'a';
cin.get();
finish=cin.get()-(int)'a';
cin.get();
while(true){
int v1=cin.get()-(int)'a';
cin.get();
int v2=cin.get()-(int)'a';
cin.get();
double cost;
cin>>cost;
m[v1][v2] = cost;
m[v2][v1] = cost;
if(cin.eof())return;
cin.get();
}
}
void print(int finish_v){
if (start==finish_v){
cout<<(char)(start+'a');
return;
}
print(prevV[finish_v]);
cout<<(char)(finish_v+'a');
}
int main() {
//ifstream ifs("../input6.txt");if(!ifs)exit(123);
//cin>>start;
//cin>>finish;
//start = 'a';
//finish = 'd';
int minIndex ;
double minL ;
for (int i = 0;i<SIZE;i++)
for (int j = 0;j<SIZE;j++) {
m[i][j] = 0;
}
//abgenmjl
//
//matrix input
//
read(cin);
for (int i = 0;i<SIZE;i++){
lable[i] = MAX;
isVisited[i] = false;
}
lable[start] = 0;
//prevV[start] = -1;
do{
minL = MAX;
minIndex = SIZE;
for (int i = 0;i<SIZE;i++)
if(lable[i]+((finish-i)) < minL+((finish-minIndex)) && !isVisited[i]) {
minL =lable[i];
minIndex = i;
}
if (minL!=MAX) {
for (int i = 0; i < SIZE; i++)
if (m[minIndex][i]!=0 && m[minIndex][i]+minL<lable[i]){
lable[i]=m[minIndex][i]+minL;
prevV[i]=minIndex;
}
}
isVisited[minIndex]= true;
} while (minIndex != SIZE);
print(finish);
//abgenmjl
//cout<<lable[(int)finish - (int)'a'];
//cout<<lable[finish];
}
|
f59fb91020ea8dfa324067722b711276d53f8267 | c82d4afeabb5247daf14045effea2dce06b82d54 | /PAT/Blevel/Q1049/Q1049/Q1049.cpp | 29db25f1a60097a233c1b026c0058ab7c061e97c | [] | no_license | lubolib/University_Code | d9bcfefde5c7e5fd5bf50676a9f957f20e049fd3 | 092752985de849385be39a6740befbde2deab4aa | refs/heads/master | 2022-03-22T23:13:27.702527 | 2019-09-26T23:47:06 | 2019-09-26T23:47:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 407 | cpp | Q1049.cpp | // Q1049.cpp: 1049. 数列的片段和
// 找规律
// 注意要用double,double的scanf是"%lf"
#include "stdafx.h"
#include <iostream>
using namespace std;
int main() {
int N;
double k, sum = 0.0;
scanf("%d", &N);
for (int i = 1; i <= N; i++) {
scanf("%lf", &k);
sum += k * i * (N - i + 1);
}
printf("%.2f", sum);
return 0;
}
/*
输入样例:
4
0.1 0.2 0.3 0.4
输出样例:
5.00
*/ |
cf46c3c94e946ce23aa48f82c9d90df99fa0759d | cc590bf63865c7634004ddeb479433a4cb104743 | /oommf/app/oxs/ext/scriptatlas.cc | c5d3905af40c622e8711d4d3845ca5ec74bf07b5 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | fangohr/oommf | 3980568c062a4ca32feb21a673bdebd1f4eed800 | 6dfaa8f744574c8e73679a42536d4c6ea3183ec8 | refs/heads/master | 2023-07-20T03:58:15.452974 | 2023-07-14T17:05:04 | 2023-07-14T17:05:04 | 43,062,791 | 23 | 11 | null | 2023-07-14T16:50:26 | 2015-09-24T11:27:36 | C++ | UTF-8 | C++ | false | false | 6,679 | cc | scriptatlas.cc | /* FILE: scriptatlas.cc -*-Mode: c++-*-
*
* Script atlas class, derived from OXS extension class.
*
*/
#include "oc.h"
#include "nb.h"
#include "director.h"
#include "scriptatlas.h"
// Oxs_Ext registration support
OXS_EXT_REGISTER(Oxs_ScriptAtlas);
/* End includes */
// Constructor
Oxs_ScriptAtlas::Oxs_ScriptAtlas
( const char* name, // Child instance id
Oxs_Director* newdtr, // App director
const char* argstr // MIF block argument string
) : Oxs_Atlas(name,newdtr,argstr)
{
// Process arguments.
vector<OC_REAL8m> xrange; GetRealVectorInitValue("xrange",2,xrange);
vector<OC_REAL8m> yrange; GetRealVectorInitValue("yrange",2,yrange);
vector<OC_REAL8m> zrange; GetRealVectorInitValue("zrange",2,zrange);
if(!bounding_box.CheckOrderSet(xrange[0],xrange[1],
yrange[0],yrange[1],
zrange[0],zrange[1])) {
throw Oxs_ExtError(this,"One of [xyz]range in Specify block"
" is improperly ordered.");
}
if(bounding_box.GetVolume()<=0.0) {
throw Oxs_ExtError(this,"Atlas bounding box has zero volume.");
}
vector<String> regionlist;
FindRequiredInitValue("regions",regionlist);
if(regionlist.empty()) {
throw Oxs_ExtError(this,"Empty region list");
}
// Copy regions list into region_name_list, setting special
// "universe" region at id 0;
region_name_list.push_back("universe");
vector<String>::const_iterator it = regionlist.begin();
while(it != regionlist.end()) {
if(it->compare("universe")==0) {
throw Oxs_ExtError(this,
"universe is a reserved region label, and"
" must not be included in user region list.");
}
region_name_list.push_back(*it);
++it;
}
DeleteInitValue("regions");
ThreeVector minpt(bounding_box.GetMinX(),bounding_box.GetMinY(),
bounding_box.GetMinZ());
ThreeVector maxpt(bounding_box.GetMaxX(),bounding_box.GetMaxY(),
bounding_box.GetMaxZ());
ThreeVector span = maxpt - minpt;
if(span.x<=0) scale.x = 1.0; // Safety
else scale.x = 1.0/span.x;
if(span.y<=0) scale.y = 1.0;
else scale.y = 1.0/span.y;
if(span.z<=0) scale.z = 1.0;
else scale.z = 1.0/span.z;
String cmdoptreq = GetStringInitValue("script_args","relpt");
command_options.push_back(Nb_TclCommandLineOption("minpt",3));
command_options.push_back(Nb_TclCommandLineOption("maxpt",3));
command_options.push_back(Nb_TclCommandLineOption("span",3));
command_options.push_back(Nb_TclCommandLineOption("rawpt",3));
command_options.push_back(Nb_TclCommandLineOption("relpt",3));
String runscript = GetStringInitValue("script");
VerifyAllInitArgsUsed();
// Run SetBaseCommand *after* VerifyAllInitArgsUsed(); this produces
// a more intelligible error message in case a command line argument
// error is really due to a misspelled parameter label.
cmd.SetBaseCommand(InstanceName(),
director->GetMifInterp(),
runscript,
Nb_ParseTclCommandLineRequest(InstanceName(),
command_options,
cmdoptreq));
// Fill fixed command line args
int index;
index = command_options[0].position; // minpt
if(index>=0) {
cmd.SetCommandArg(index,minpt.x);
cmd.SetCommandArg(index+1,minpt.y);
cmd.SetCommandArg(index+2,minpt.z);
}
index = command_options[1].position; // maxpt
if(index>=0) {
cmd.SetCommandArg(index,maxpt.x);
cmd.SetCommandArg(index+1,maxpt.y);
cmd.SetCommandArg(index+2,maxpt.z);
}
index = command_options[2].position; // span
if(index>=0) {
cmd.SetCommandArg(index,span.x);
cmd.SetCommandArg(index+1,span.y);
cmd.SetCommandArg(index+2,span.z);
}
}
Oxs_ScriptAtlas::~Oxs_ScriptAtlas()
{}
OC_BOOL Oxs_ScriptAtlas::GetRegionExtents(OC_INDEX id,Oxs_Box &mybox) const
{ // Fills mybox with bounding box for region with specified
// id number. Return value is 0 iff id is invalid. At present,
// given a valid id number, just returns the world bounding
// box. In the future, we might want to add support for refined
// region bounding boxes.
if(id>=GetRegionCount()) return 0;
mybox = bounding_box;
return 1;
}
OC_INDEX Oxs_ScriptAtlas::GetRegionId(const ThreeVector& point) const
{ // Appends point & bounding box to "script" from the Specify
// block, and evaluates the resulting command in the MIF
// interpreter. The script should return the 1-based index
// for the corresponding region, or 0 if none apply.
if(!bounding_box.IsIn(point)) return 0; // Don't claim point
/// if it doesn't lie within atlas bounding box.
cmd.SaveInterpResult();
// Fill variable command line args
int index;
index = command_options[3].position; // rawpt
if(index>=0) {
cmd.SetCommandArg(index,point.x);
cmd.SetCommandArg(index+1,point.y);
cmd.SetCommandArg(index+2,point.z);
}
index = command_options[4].position; // relpt
if(index>=0) {
OC_REAL8m x = (point.x - bounding_box.GetMinX())*scale.x;
cmd.SetCommandArg(index,x);
OC_REAL8m y = (point.y - bounding_box.GetMinY())*scale.y;
cmd.SetCommandArg(index+1,y);
OC_REAL8m z = (point.z - bounding_box.GetMinZ())*scale.z;
cmd.SetCommandArg(index+2,z);
}
cmd.Eval();
if(cmd.GetResultListSize()!=1) {
String msg
= String("Return script value is not a single integer: ")
+ cmd.GetWholeResult();
cmd.RestoreInterpResult();
throw Oxs_ExtError(this,msg.c_str());
}
OC_INT4m id; // GetResultListItem wants an OC_INT4m type
cmd.GetResultListItem(0,id);
cmd.RestoreInterpResult();
if(id < 0 || id >= GetRegionCount()) {
char buf[512];
Oc_Snprintf(buf,sizeof(buf),
"Region id value %d returned by script is out of range.",
id);
throw Oxs_ExtError(this,buf);
}
return id;
}
OC_INDEX Oxs_ScriptAtlas::GetRegionId(const String& name) const
{ // Given a region id string (name), returns
// the corresponding region id index. If
// "name" is not included in the atlas, then
// -1 is returned. Note: If name == "universe",
// then the return value will be 0.
OC_INDEX count = static_cast<OC_INDEX>(region_name_list.size());
for(OC_INDEX i=0;i<count;i++) {
if(region_name_list[i].compare(name)==0) return i;
}
return -1;
}
OC_BOOL Oxs_ScriptAtlas::GetRegionName(OC_INDEX id,String& name) const
{ // Given an id number, fills in "name" with
// the corresponding region id string. Returns
// 1 on success, 0 if id is invalid. If id is 0,
// then name is set to "universe", and the return
// value is 1.
if(id>=static_cast<OC_INDEX>(region_name_list.size())) return 0;
name = region_name_list[id];
return 1;
}
|
16f78c793a55179820d7d911a36bf9ee501fc42d | 7f159057e9f8eedff3a7b2509b396eb21b3de0a7 | /leifkruger/cpp-code/shape_list/Box.cpp | 17fe2b719d19da8f1e8803c933613014d035c9ae | [] | no_license | tombe691/ec2020 | 640eb023ef29882b665a52b2a927445be8a86d86 | 339d3a5220d9732c4145a31a33b08a3433536b14 | refs/heads/main | 2023-02-01T02:10:54.640015 | 2020-12-16T20:54:18 | 2020-12-16T20:54:18 | 301,317,534 | 2 | 6 | null | 2020-10-21T09:22:47 | 2020-10-05T06:49:25 | C | UTF-8 | C++ | false | false | 1,403 | cpp | Box.cpp | /*
*******************************************************************************
FILENAME Box.cpp
Encoding UTF-8
DESCRIPTION Calculate volume and area of different shapes.
FUNCTIONS
NOTES Menu language - English
Compiler g++ 9.3.0 amd64 running @ Ubuntu 20.04 LTS
Lang dialect ISO C++14 (g++ by default uses option '-std=gnu++14')
Copyright L.Krüger 2020. All rights reserved.
AUTHOR Leif Krüger, leif@leifkruger.se
CHANGES
REF NO VERSION DATE (YYMMDD) WHO DETAIL
-------------------------------------------------------------------------------
1 2020-11-21 LK Start date
*******************************************************************************
*/
#include <iostream>
#include "Box.h"
//Box::Box() {}
Box::Box(std::string _color, double _height, double _length, double _width)
: Shape(_color), height(_height), length(_length), width(_width) {}
double Box::getArea() {
return 2 * (length * height + length * width + width * height);
}
double Box::getVolume() {
return height * length * width;
}
void Box::setInput() {
std::cout << "Height: ? ";
std::cin >> height;
std::cout << "Length: ? ";
std::cin >> length;
std::cout << "Width: ? ";
std::cin >> width;
}
void Box::printArea() {
cout << "The Box area is: " << getArea() << endl;
}
void Box::printVolume() {
cout << "The Box volume is: " << getVolume() << endl;
} |
400b01124e4802031a10125b4cb58ac2100b2a44 | ea8183aaa5d85ee04adedcb59e7e245906bf9d39 | /adc_keyboard.cpp | e5eb8002f3cf0213a8fdec766821df1b4640c84a | [] | no_license | gergespenst/digi_new_year_led | 6b72e1297f365220559f4df02f9af3694bfca07f | 75cc038983abbc178bc668cb4c63c070c03d7289 | refs/heads/master | 2022-09-18T02:00:57.520516 | 2018-12-04T08:36:26 | 2018-12-04T08:36:26 | 111,893,138 | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 3,005 | cpp | adc_keyboard.cpp | /*
* adc_keyboard.cpp
*
* Created: 22.11.2017 15:10:54
* Author: USER
*/
#include "adc_keyboard.h"
static PCALLFUNC g_press_func,g_long_press_func = 0;
void InitAdcKeyboard(PCALLFUNC pressFunc,PCALLFUNC longPressFunc){
InitAdcKeyboard(pressFunc);
g_long_press_func = longPressFunc;
}
void InitAdcKeyboard(PCALLFUNC func){
//Init ADC
ADMUX =
(1 << ADLAR) | // left shift result
(0 << REFS1) | // Sets ref. voltage to VCC, bit 1
(0 << REFS0) | // Sets ref. voltage to VCC, bit 0
(0 << MUX3) | // use ADC0 for input (PB4), MUX bit 3
(0 << MUX2) | // use ADC0 for input (PB4), MUX bit 2
(0 << MUX1) | // use ADC0 for input (PB4), MUX bit 1
(0 << MUX0); // use ADC0 for input (PB4), MUX bit 0
ADCSRA =
(1 << ADEN) | // Enable ADC
(0 << ADPS2) | // set prescaler to 64, bit 2
(0 << ADPS1) | // set prescaler to 64, bit 1
(0 << ADPS0); // set prescaler to 64, bit 0
g_press_func = func;
}
#define MAX_ADC 0xFF
#define ANALOG_STEP (MAX_ADC/(NUM_OF_KEYS + 1))
#define ANALOG_DELTA (ANALOG_STEP/2)
void ScanKayboard(){
static uint8_t pressed_key = NOP,press_counter;
//запускаем АЦП
ADCSRA |= (1<<ADSC);
while (ADCSRA & (1 << ADSC));
//После преобразования получаем уровень на входе
uint8_t analogKeyVal = ADCH;
//Определяем номер нажатой кнопки, если проскочили все уровни возвращаем NOP
uint8_t temp_key = 0;
for (temp_key = 1; temp_key <= NUM_OF_KEYS + 1; temp_key++)
{
if ( (analogKeyVal > (ANALOG_STEP*temp_key - ANALOG_DELTA))
&& (analogKeyVal < (ANALOG_STEP*temp_key + ANALOG_DELTA)) )
{
break;
}
}
if (temp_key == (pressed_key & 0x0F))//если нажатая клавиша совпадает с нажатой ранее
{
if ((press_counter > LONG_PRESS) && ((pressed_key & 0x0F) != NOP))
{//если длительность нажатия больше чем длинное нажатие
if(g_long_press_func) (*g_long_press_func)(pressed_key & 0x0F); // выполняем функцию обработчик длительного нажатия
pressed_key |= 0x80; // ставим флаг длительного нажатия и сбрасываем счетчик
press_counter = 0;
}else//увеличиваем четчик длительности нажатия
{
press_counter++;
}
}else
{//если предыдущее и нынешнее значение клавиш не совпадают то в случае если не взведен флаг длительного нажатия выполняем обработчик
if (((pressed_key & 0x0F) != NOP) && ( (pressed_key & 0xF0) == 0))
{
(*g_press_func)(pressed_key & 0x0F);
}
// в любом случае сбрасываем длительность нажатия и предыдущую клавишу
press_counter = 0;
pressed_key = temp_key;
}
} |
c23956a2b2772d4f9cc2c4db1246c14385d67a89 | 7d36c569f0d5d24eede9287fdf3ab91c77f6016c | /DayofYear.hpp | fe21dbce70a9ad0845667fd022342901c8eaad12 | [] | no_license | muse-gabs/Calendar-Conversion-Program | a4de17f69f9768040b39df8ad7e054b3477fcd0a | cbfe3c262bb7a376c4c91e789df475c4a0232d16 | refs/heads/master | 2020-12-23T06:50:15.600734 | 2020-01-29T20:20:44 | 2020-01-29T20:20:44 | 237,073,720 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,242 | hpp | DayofYear.hpp | /********************************************************************
** Author: Gabrielle Pang
** Date: May 29, 2019
** Description: This is the class for DayOfYear, it initializes
** an array for the days in a normal year, and the
** months in a year.
** There are also 2 blank Exception classes for the
** main program to catch in the event that the user
** inputs are out of range.
********************************************************************/
#ifndef DAYOFYEAR_HPP
#define DAYOFYEAR_HPP
#include <iostream>
#include <string>
class DayOfYear
{
private:
int day;
std::string month;
int totNumOfDays;
public:
int daysPerMonth[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
std::string Month[12] = {"January", "February", "March", "April",
"May", "June", "July", "August", "September", "October",
"November", "December"};
int getTotDays();
void setDayOfYear(int);
void printday();
bool checkValid(std::string, int);
void calcDays(std::string, int);
DayOfYear(std::string, int);
DayOfYear operator++(int);
DayOfYear operator--(int);
class InvalidRange
{
};
class InvalidDayMonth
{
};
};
#endif
|
2ce02bcbcbdfc8c07870abbc50481775800c50ac | a6b8ad7d4536b10c4694377edf33bd3fcaa47c4f | /Semana 08/Find Pivot Index.cpp | 3e510781ea5eeba33c2163058513138fff9a13c7 | [] | no_license | GabrielSBotelho/Desafios-de-Programacao | 26000d8210afb817d16cbc98c06602f353afa750 | f6b405dbaa20b31f4e1492099a4a99074cc3ff54 | refs/heads/main | 2023-07-20T03:14:38.490245 | 2021-09-03T22:46:00 | 2021-09-03T22:46:00 | 368,923,749 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 389 | cpp | Find Pivot Index.cpp | class Solution {
public:
int pivotIndex(vector<int>& nums) {
int sum = 0;
int start = 0;
for(int x : nums){
sum += x;
}
for(int i = 0; i < nums.size(); i++){
sum -= nums[i];
if(start == sum){
return i;
}
start += nums[i];
}
return -1;
}
}; |
066f18471f000f1adc81f343767f06ce8b7e916b | 0ca952396ee2f57d6d4a4da01c713a872311bb85 | /MonopolyAssignmentV3 - Sehun Babatunde/MonopolyAssignmentV3 - Sehun Babatunde.cpp | 9090faa90364aa4252b3afc07f72a58cdb9ed2fc | [] | no_license | SehunBaba/Monopoly---Assignment | 61dca2866259b5ac7e10893954df35a5cc12d0dc | dc4579f684609ba11f6330607fa6e5779e84e47c | refs/heads/main | 2023-01-04T11:21:26.185120 | 2020-11-02T18:27:16 | 2020-11-02T18:27:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,503 | cpp | MonopolyAssignmentV3 - Sehun Babatunde.cpp | // MonopolyAssignmentV3 - Sehun Babatunde.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include "pch.h"
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <ctime>
#include <vector>
using namespace std;
const char POUND = 156;
//Handles Square Data
class CSquares
{
protected:
int mSqaureID;
string mSquareName;
public:
CSquares() {};
~CSquares() {};
//Setters
void SetSquare(int squareID, string sqaureName)
{
mSqaureID = squareID;
mSquareName = sqaureName;
}
//Getters
int getSquareID() { return mSqaureID;}
string GetName();
};
string CSquares::GetName()
{
return mSquareName;
}
//Handles Property Data
class CProperties
{
protected:
int mPropertyCodeID;
int mPropertyCost;
int mPropetryRent;
int mPropertyGroupID;
string mPropetryName;
public:
CProperties() {};
~CProperties() {};
//Getters
int GetPropertyCost() { return mPropertyCodeID; }
int GetPropertyRent() { return mPropetryRent; }
string GetPropertyName() { return mPropetryName; }
int GetPropertyGroupID() { return mPropertyGroupID; }
int GetPropertyID() { return mPropertyCodeID; }
//Setters
void SetPropertyID(int propertyID) { mPropertyCodeID = propertyID;}
void SetPropertyCost(int propertyCost) { mPropertyCost = propertyCost; }
void SetPropetryRent(int propetryRent) { mPropetryRent = propetryRent; }
void SetPropertyGroupID(int groupID) { mPropertyGroupID = groupID; }
void SetPropetryName(int propetryName) { mPropetryName = propetryName; }
};
//Handles Players
class CPlayer : public CProperties
{
private:
int mCurrentFunds;
public:
CPlayer() { mCurrentFunds = 1500; };
~CPlayer() {};
void AddFunds(int amount);
void ReduceFunds(int cost);
int GetFunds();
};
void CPlayer::AddFunds(int amount)
{
mCurrentFunds += amount;
}
int CPlayer::GetFunds()
{
return mCurrentFunds;
}
void CPlayer::ReduceFunds(int cost)
{
mCurrentFunds = mCurrentFunds - cost;
}
//Monopoly Game
class CManager : public CProperties
{
public:
CManager() {};
~CManager() {};
void ReadtxtFile();
void Game();
int NumGen(string playerName);
};
typedef vector<CSquares*> VectorSquare;
VectorSquare pSquare;
typedef vector<CPlayer*> VectorPlayer;
VectorPlayer pPlayer;
typedef vector <CProperties*> vectorProperties;
vectorProperties pProperty;
//Reads in Monopoly txt file and puts them into seprate respective vectors with error check
void CManager::ReadtxtFile()
{
string arrayr[10];
string line;
ifstream infile;
string sqaureName;
int squareID;
int squareCost;
int squareRent;
int squareGroup;
int count = 0;
int count2 = 0;
infile.open("Monopoly.txt");
if (!infile)
{
cout << "Error reading file!" << endl;
}
if (infile.is_open())
{
while (getline (infile, line))
{
stringstream w(line);
int i = 0;
while (w.good() && i < 10)
{
w >> arrayr[i];
i++;
}
squareID = stoi(arrayr[0]);
switch (squareID)
{
case 1:
sqaureName = arrayr[1] + " " + arrayr[2];
squareCost = stoi(arrayr[3]);
squareRent = stoi(arrayr[4]);
squareGroup = stoi(arrayr[5]);
pSquare.push_back(new CSquares);
pSquare[count]->SetSquare(squareID, sqaureName);
pProperty.push_back(new CProperties);
pProperty[count2]->SetPropertyCost(squareCost);
pProperty[count2]->SetPropetryRent(squareRent);
pProperty[count2]->SetPropertyGroupID(squareGroup);
count++;
count2++;
break;
case 2:
sqaureName = arrayr[1];
pSquare.push_back(new CSquares);
pSquare[count]->SetSquare(squareID, sqaureName);
count++;
break;
case 3:
sqaureName = arrayr[1] + " " + arrayr[2];
squareCost = 200;
squareRent = 10;
squareGroup = -1;
pSquare.push_back(new CSquares);
pSquare[count]->SetSquare(squareID, sqaureName);
pProperty.push_back(new CProperties);
pProperty[count2]->SetPropertyCost(squareCost);
pProperty[count2]->SetPropetryRent(squareRent);
pProperty[count2]->SetPropertyGroupID(squareGroup);
count++;
count2++;
break;
case 4:
sqaureName = arrayr[1];
pSquare.push_back(new CSquares);
pSquare[count]->SetSquare(squareID, sqaureName);
count++;
break;
case 5:
sqaureName = arrayr[1];
pSquare.push_back(new CSquares);
pSquare[count]->SetSquare(squareID, sqaureName);
count++;
break;
case 6:
sqaureName = arrayr[1];
pSquare.push_back(new CSquares);
pSquare[count]->SetSquare(squareID, sqaureName);
count++;
break;
case 7:
sqaureName = arrayr[1] + " " + arrayr[2] + " " + arrayr[3];
pSquare.push_back(new CSquares);
pSquare[count]->SetSquare(squareID, sqaureName);
count++;
break;
case 8:
sqaureName = arrayr[1];
pSquare.push_back(new CSquares);
pSquare[count]->SetSquare(squareID, sqaureName);
count++;
break;
}
}
}
}
//Play out the game
void CManager::Game()
{
int rollCount = 0;
int moveSpaces = 0;
int playerLocation = 0;
int player2Location = 0;
int playerNum = 0;
pPlayer.push_back(new CPlayer);
pPlayer.push_back(new CPlayer);
srand(5);
cout << " " << endl;
cout << "Monopoly Assignment - Sehun Babatunde" << endl;
cout << " " << endl;
cout << " " << endl;
cout << "Welcome to Monopoly" << endl;
cout << " " << endl;
cout << " " << endl;
while (rollCount < 40)
{
if (playerNum == 0)
{
moveSpaces = NumGen("dog");
playerLocation += moveSpaces;
if (playerLocation > 25)
{
playerLocation %= 26;
pPlayer[playerNum]->AddFunds(200);
cout << "Passed GO." << endl;
}
cout << "dog lands on " << pSquare[playerLocation]->GetName() << endl;
cout << "dog has " << POUND << pPlayer[playerNum]->GetFunds() << endl;
for (int i = 0; i < pProperty.size(); i++)
{
if (pSquare[playerLocation]->getSquareID() == 1 || pSquare[playerLocation]->getSquareID() == 3)
{
int cost = pPlayer[playerNum]->GetPropertyCost();
pPlayer[playerNum]->ReduceFunds(GetProperty;
//if (pSquare[playerNum]->getSquareID() == 1 || pSquare[playerNum]->getSquareID() == 2)
//{
// pPlayer[playerNum]->ReduceFunds(GetPropertyCost());
//// pPlayer[playerNum]->SetPropertyID(playerNum);
// //pPlayer[playerNum]->SetPropertyID(player);
//
//}
}
}
playerNum = 1;
}
else if (playerNum == 1)
{
moveSpaces = NumGen("car");
player2Location += moveSpaces;
if (player2Location > 25)
{
player2Location %= 26;
pPlayer[playerNum]->AddFunds(200);
cout << "Passed GO." << endl;
}
cout << "car lands on " << pSquare[player2Location]->GetName() << endl;
cout << "car has " << POUND << pPlayer[playerNum]->GetFunds() << endl;
playerNum = 0;
}
rollCount++;
}
}
// Generates a list of random numbers based on seed
int CManager::NumGen(string playerName)
{
int diceRoll;
diceRoll = static_cast<int>(static_cast<double> (rand()) / (RAND_MAX + 1) * 6.0f + 1);
cout << playerName << " rolls " << diceRoll << endl;
return diceRoll;
}
int main()
{
CManager* Manager = new CManager;
Manager->ReadtxtFile();
Manager->Game();
system("pause");
} |
6fd40220e17fa8a96c2d6978dbf996ff5b905498 | ec9fc0233dc167ba397c8d15494faf9b20629a76 | /reachingDef/program.h | 6e265226d04fe0f0043e87589cab71eef4c31b1e | [] | no_license | bhushan23/compiler | 3cd307cbbf5f449a3065a367da52409811039a8e | a0d6e981a91ee29403a610f7966ff6761ac8d5f6 | refs/heads/master | 2021-01-23T14:03:43.257224 | 2014-09-03T12:29:05 | 2014-09-03T12:29:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 619 | h | program.h | #ifndef PROGRAM_H
#define PROGRAM_H
#include "basicblock.h"
#include "irclass.h"
class Program{
list<BasicBlock*> basicBlock;
map<string,BasicBlock*> mapBB;
public:
list <BasicBlock*>::iterator get_begin();
list <BasicBlock*>::iterator get_end();
void print_program();
void create_dot_file();
void addNewBb(BasicBlock* bb);
Program(){
}
Program(BasicBlock* bb){
basicBlock.push_back(bb);
}
BasicBlock* GetBasicBlockFromLabel(string&);
void add_instruction(instruction* ,instruction*);
void add_instruction(instruction* , BasicBlock*);
};
#endif
|
6cae79e1f17dac1049e4d24bd5c0dc5b82efbd42 | f13ae317b6db8f4ce1e540f98cd35897f334fa5c | /cAssignmentNode.h | ac75ad6f910222697788947cfc2c90545dcbc4d4 | [] | no_license | chadgreene/CST320_ChadGreene | 3579da28e2d0fb1b4c5b28571045049d8a85268c | 1ceb4747592a103eae20c205a6e5d9deea002827 | refs/heads/master | 2021-01-01T18:23:32.660864 | 2015-03-14T18:16:22 | 2015-03-14T18:16:22 | 28,837,280 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 866 | h | cAssignmentNode.h | /*******************************************************************************
* Author: Chad Greene
* Lab: Lab 7 Generate Code
* Date: 3/14/15
*
* Purpose: Build an abstract syntax tree by using Bison/Lex to parse a source
* file into appropriate nodes
*******************************************************************************/
#pragma once
#include "cStmtNode.h"
#include "ExprNode.h"
#include "cVarRef.h"
#include "IntExpr.h"
#include "cFuncCall.h"
class cAssignmentNode : public cStmtNode
{
public:
cAssignmentNode(cVarRef* lhs = nullptr, ExprNode* rhs = nullptr);
string toString();
bool CanAssign();
bool CharInRange(ExprNode* node = nullptr);
int CalculateSize(int offset);
void GenerateCode();
string GetType();
private:
cVarRef* m_lhs;
ExprNode* m_rhs;
}; |
6c43a9bb3b7791453a7583e8cef0d86b7a0e673c | 077ba712c73feb4d1bbe66518338e98d5c1e040d | /cpp/robot/payload.h | ed597febce14cc88d5425960c861aa55ef1540ae | [] | no_license | devmanner/devmanner | eec4a83b1c35bbf67aecbb4860358cab7c823822 | 37f6bd1d0f7301045284cc94e37b8cb4b9005142 | refs/heads/master | 2021-01-10T19:09:19.251055 | 2019-09-20T18:46:22 | 2019-09-20T18:46:22 | 32,351,152 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 749 | h | payload.h | #ifndef _PAYLOAD_H_
#define _PAYLOAD_H_
typedef int payload_t;
typedef int pos_t;
class Mission {
private:
pos_t m_dest;
public:
pos_t toWhere() { return m_dest; }
};
class Movement : public Mission {
};
class Payload : public Mission {
private:
payload_t m_type;
public:
Payload(payload_t t=0) : m_type(t) {}
payload_t getType() { return m_type; }
};
/*
class PayloadFactory {
private:
static PayloadFactory* m_instance;
PayloadFactory() {};
public:
Payload* createPayload(payload_t t=0) {return new Payload(t);}
PayloadFactory* getInstance() { return ((m_instance) ? m_instance : m_instance = new PayloadFactory()); }
void kill() { delete m_instance; }
};
*/
#endif
|
78a78d60da90e390fd237a938780d778db76e44f | 815acb61ac2a8566c5e59c9fcc6ac2836d14e0f5 | /programmation/Projet_X/Projet_X/Shaders/GeomPassShader.h | 6ce2de3bbba2312b8885edd513bafa842e1dc573 | [] | no_license | joblo13/projetx | 8211de3066784aec770fe37b01ccb37c0104e347 | 718bd8d3f2d8818159c704564cabc64f5de7f053 | refs/heads/master | 2021-01-13T15:00:49.132697 | 2017-01-18T20:33:32 | 2017-01-18T20:33:32 | 79,375,333 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 381 | h | GeomPassShader.h | #ifndef GEOM_PASS_SHADER_H
#define GEOM_PASS_SHADER_H
//Includes interne
#include "Shader.h"
class GeomPassShader : public Shader
{
public:
GeomPassShader();
private:
//Fonction permettant de trouver la localisation des variables des shaders
void bindAttribLocation();
void bindUniformLocation();
protected:
//Singleton
~GeomPassShader();
};
#endif //GEOM_PASS_SHADER_H |
415450c3f3054904b92b07d4108717e7e64d535a | 86bfae94def1ca36bec20ab0ecadd72c1f97272e | /src/post/irllvm-wpds-xml/tests/ActionTest.cpp | 6f5cadc3a78e2a6b6464e617ca7f687b24f67e46 | [
"BSD-3-Clause"
] | permissive | ucd-plse/mpi-error-prop | 22b947ff5a51c86817b973e55c68e4a2cf19e664 | 4367df88bcdc4d82c9a65b181d0e639d04962503 | refs/heads/master | 2020-09-17T06:24:19.740006 | 2020-01-31T21:48:35 | 2020-01-31T21:48:35 | 224,017,672 | 6 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,092 | cpp | ActionTest.cpp | #include "ActionTest.hpp"
#include "../VarName.hpp"
#include "../Traces.hpp"
#include "../TraceVisitors.hpp"
using namespace std;
using namespace ep;
using ::testing::_;
using ::testing::Return;
using ::testing::ContainerEq;
TEST_F(ActionTest, PreActions) {
MockNames names;
MockActionMapper mapper(&names);
// 1 is dummy instruction pointer for a vertex
EXPECT_CALL(mapper, map((llvm::Instruction*) 1, Location()))
.WillOnce(Return(actions_a));
EXPECT_CALL(mapper, map((llvm::Instruction*) 2, Location()))
.WillOnce(Return(actions_b));
EXPECT_CALL(mapper, map((llvm::Instruction*) 3, Location()));
EXPECT_CALL(mapper, map((llvm::Instruction*) 5, Location()))
.WillOnce(Return(actions_e));
PreActionTrace trace("PreActionsTest.0");
PreActionVisitor pav(mapper, trace.items);
DepthFirstVisitor<_FlowGraph> visitor(pav);
visitor.visit(entry_vtx, handler_vtx, FG.G);
vector<Item> expected = { action_a, action_b, action_e } ;
ASSERT_THAT(trace.items, ContainerEq(expected));
};
TEST_F(ActionTest, PostActions) {
// PostActionVisitor requires pre-actions to be marked already
MockNames names;
MockActionMapper pre_mapper(&names);
EXPECT_CALL(pre_mapper, map((llvm::Instruction*) 1, Location()))
.WillOnce(Return(actions_a));
EXPECT_CALL(pre_mapper, map((llvm::Instruction*) 2, Location()))
.WillOnce(Return(actions_b));
EXPECT_CALL(pre_mapper, map((llvm::Instruction*) 3, Location()));
EXPECT_CALL(pre_mapper, map((llvm::Instruction*) 5, Location()))
.WillOnce(Return(actions_e));
PreActionTrace pre_trace("PostActionsTest.0");
PreActionVisitor pre_vis(pre_mapper, pre_trace.items);
DepthFirstVisitor<_FlowGraph> pre_dfs(pre_vis);
pre_dfs.visit(entry_vtx, handler_vtx, FG.G);
MockActionMapper post_mapper(&names);
EXPECT_CALL(post_mapper, map((llvm::Instruction *) 5, Location()))
.WillRepeatedly(Return(actions_e));
EXPECT_CALL(post_mapper, map((llvm::Instruction *) 4, Location()));
EXPECT_CALL(post_mapper, map((llvm::Instruction *) 6, Location()))
.WillRepeatedly(Return(actions_f));
PostActionTrace post_trace("PostActionsTest.0");
PostActionVisitor post_vis(post_mapper, post_trace.items, pre_vis.get_discovered());
DepthFirstVisitor<_FlowGraph> post_dfs(post_vis);
post_dfs.visit(handler_vtx, FG.G);
vector<Item> expected = { action_e, action_f };
ASSERT_THAT(post_trace.items, ContainerEq(expected));
};
TEST_F(ActionTest, HandlerActions) {
MockNames names;
MockActionMapper mapper(&names);
EXPECT_CALL(mapper, map((llvm::Instruction*) 5, Location()))
.WillOnce(Return(actions_e));
Trace trace("HandlerActionsTest.0");
unordered_set<string> dummy_handler_set;
vector<pair<string, string>> dummy_nesting_pairs;
HandlerActionsVisitor handle_vis(mapper, trace.items, "d", dummy_handler_set, dummy_nesting_pairs);
DepthFirstVisitor<_FlowGraph> dfs_visitor(handle_vis);
dfs_visitor.visit(handler_vtx, FG.G);
vector<Item> expected = { action_e };
ASSERT_THAT(trace.items, ContainerEq(expected));
};
// TODO: Prevent double-discovers in simple DFS
|
cb71404b782b65a39e5d10e423a4fb3f85c458c1 | 5673f2625023822b749d798da31b9ec2a3401fea | /Filters.cpp | 1a9a1f97fdc5f301bfc00fd188583917105b893f | [] | no_license | andreyV512/mufta | f9c0c915096e86c8fc7236f410b22a65299505bb | 8c11c6f3fa238d5e97e9cd3f6ace44ce1b2c385b | refs/heads/master | 2020-03-21T22:02:44.493619 | 2018-06-29T10:11:52 | 2018-06-29T10:11:52 | 139,100,296 | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 3,382 | cpp | Filters.cpp | // ---------------------------------------------------------------------------
#pragma hdrstop
#ifdef BERLIN_10
#include <VCLTee.Chart.hpp>
#include <VCLTee.Series.hpp>
#else
#include "Series.hpp"
#endif
#include "Filters.h"
#include "TProtocol.h"
#include "unSQLDbModule.h"
#include "unTExtFunction.h"
// ------------------------------------------------------------------------------
Filters *SGFilter;
Filters::Filters(AnsiString _type) {
try {
type = _type;
dllInstance = LoadLibrary(L"filters.dll");
if (!dllInstance) {
String strError = L"Не удалось загрузить библиотеку фильтров";
MessageBox(NULL, strError.w_str(), L"Ошибка", MB_ICONERROR | MB_OK);
}
else {
filter_chebyshev = (_ChebyshevI) GetProcAddress(dllInstance,
"ChebyshevI");
filter_butterworth = (_Butterworth) GetProcAddress(dllInstance,
"Butterworth");
filter_elliptic = (_Elliptic) GetProcAddress(dllInstance,
"Elliptic");
setSettingsFromDB();
}
}
catch (Exception *ex) {
// err = -2;
// TLog::ErrFullSaveLog(ex);
// MessageDlg(ex->Message, mtError, TMsgDlgButtons() << mbOK, NULL);
TExtFunction::FATAL(ex->Message);
}
}
void Filters::toFilter(double *data, int N) {
switch (settings.CurrentType) {
case 0: {
filter_butterworth(data, N, settings.order, settings.sampleRate,
settings.cutoffFrequency, settings.centerFrequency,
settings.widthFrequency, settings.CurrentSubType);
break;
}
case 1: {
filter_chebyshev(data, N, settings.order, settings.sampleRate,
settings.cutoffFrequency, settings.centerFrequency,
settings.widthFrequency, settings.rippleDb,
settings.CurrentSubType);
break;
}
case 2: {
filter_elliptic(data, N, settings.order, settings.sampleRate,
settings.cutoffFrequency, settings.centerFrequency,
settings.widthFrequency, settings.rippleDb, settings.rolloff,
settings.CurrentSubType);
break;
}
}
}
void Filters::setSettingsFromDB() {
SqlDBModule->ADOQueryDB->Close();
AnsiString sql =
"SELECT filterCurrentType,filterCurrentSubType,filterOrder,filterCutoffFrequency,filterWidthFrequency,";
sql += " filterCenterFrequency,filterRippleDb,filterRolloff,filterSampleRate,isFilter FROM SettingsGlobal";
SqlDBModule->ADOQueryDB->SQL->Text = sql;
SqlDBModule->ADOQueryDB->Open();
settings.CurrentType = (filterTypes)SqlDBModule->ADOQueryDB->FieldByName("filterCurrentType")->AsInteger;
settings.CurrentSubType =(filterSubTypes)SqlDBModule->ADOQueryDB->FieldByName("filterCurrentSubType")->AsInteger;
settings.order = SqlDBModule->ADOQueryDB->FieldByName("filterOrder")
->AsInteger;
settings.cutoffFrequency = SqlDBModule->ADOQueryDB->FieldByName
("filterCutoffFrequency")->AsFloat;
settings.widthFrequency = SqlDBModule->ADOQueryDB->FieldByName
("filterWidthFrequency")->AsFloat;
settings.centerFrequency = SqlDBModule->ADOQueryDB->FieldByName
("filterCenterFrequency")->AsFloat;
settings.rippleDb = SqlDBModule->ADOQueryDB->FieldByName("filterRippleDb")
->AsFloat;
settings.rolloff = SqlDBModule->ADOQueryDB->FieldByName("filterRolloff")
->AsFloat;
settings.sampleRate = SqlDBModule->ADOQueryDB->FieldByName("filterSampleRate")
->AsFloat;
SqlDBModule->ADOQueryDB->Close();
}
#pragma package(smart_init)
|
fd6b1532c598f370cca9888822df1f462423297d | 17d36145fd41e8ec3e7f0908dc64cde5bc26e361 | /Motor/Source.cpp | 15b2e77562d56a234a2cfb8be023e17c9b67a6f6 | [] | no_license | Ploxie/CppMotor | 9262595e74253af98d84481c5112545dd151974d | 85f719ebe63d0c7cf2a6e270da91b94fdf6e65dc | refs/heads/master | 2021-09-20T14:22:52.726961 | 2018-08-10T18:52:13 | 2018-08-10T18:52:13 | 140,103,371 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 276 | cpp | Source.cpp | #pragma once
#include <iostream>
#include "GLFWWindow.h"
#include <GLFW/glfw3.h>
#include <GLFW/glfw3native.h>
using namespace Engine;
int main()
{
glfwInit();
Window* window = new GLFWWindow(50, 50 , "ASD", WINDOWED);
window->Create();
system("pause");
return 0;
} |
e1b5e1e644652128e333e155f92e7b12317368cd | 761d2729914160aa8d86a4067a5a85ef7ba8cf78 | /baekjoon/12865.cpp | c961b51ef58222a8d17182be7eb3de55919f327f | [] | no_license | leebohee/problem-solving | 152ec5abb7fcafd3006dbc2ccc7152724658fb53 | 08d77878b09b763c735ba55fc779eb4386b74d33 | refs/heads/master | 2021-07-05T11:56:40.623793 | 2020-09-10T11:21:41 | 2020-09-10T11:21:41 | 170,067,865 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,270 | cpp | 12865.cpp | #include <iostream>
#include <vector>
#include <algorithm>
#include <climits>
#define MAX_K 100000
using namespace std;
struct thing{
int w;
int v;
thing(int w_, int v_): w(w_), v(v_) {};
bool operator<(const thing& th){
if(this->v == th.v) return this->w > th.w;
else return this->v > th.v;
}
};
int measure(vector<thing>& things, int weight, int value, int idx, int K){
if(weight > K) return INT_MIN;
if(idx >= things.size()) return value;
int contain = measure(things, weight+things[idx].w, value+things[idx].v, idx+1, K);
int not_contain = measure(things, weight, value, idx+1, K);
int ret = max(contain, not_contain);
return ret;
}
int max_value_bf(vector<thing>& things, int K){
// sort by value
sort(things.begin(), things.end());
return measure(things, 0, 0, 0, K);
}
int max_value(vector<thing>& things, int K){
int n = things.size();
int dp[MAX_K+1] = {0, };
for(int i=0; i<n; i++){
for(int k=K; k>=1; k--){ // for(int k=1; k<=K; k++)
if(things[i].w <= k){
dp[k] = max(dp[k], dp[k-things[i].w]+things[i].v);
}
}
}
return dp[K];
}
int main(){
int N, K, W, V;
vector<thing> things;
cin >> N >> K;
for(int i=0; i<N; i++){
cin >> W >> V;
things.emplace_back(W, V);
}
cout << max_value(things, K);
return 0;
}
|
c713a4c0c49b5dff7639dc931375f97f100894bf | 2a15f38a625871b82906f5f7ccd024aae37c26a6 | /epoch_tracker_main.cc | 6511decea61d74662d9f949d86eecc6e10c0137d | [
"Apache-2.0"
] | permissive | xavigonzalvo/REAPER | 95e4d74e9ffd84b5647b80623f420834ba263043 | 932bf8823eda11bb71df764b7e70d2cb3ea9184c | refs/heads/master | 2021-01-18T11:54:05.614373 | 2015-02-03T06:54:57 | 2015-02-03T06:54:57 | 30,229,125 | 0 | 0 | null | 2015-02-03T06:40:14 | 2015-02-03T06:40:14 | null | UTF-8 | C++ | false | false | 3,919 | cc | epoch_tracker_main.cc | /*
Copyright 2014 Google Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include <memory>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include "core/file_resource.h"
#include "core/track.h"
#include "epoch_tracker/epoch_tracker.h"
#include "wave/wave.h"
const char* kHelp = "Usage: <bin> -i <input_file> "
"[-f <f0_output> -p <pitchmarks_output> "
"-t "
"-s "
"-e <float> "
"-x <float> "
"-m <float> "
"-u <float> "
"-a "
"-d <debug_output_basename>] "
"\n\n Help:\n"
"-t enables a Hilbert transform that may reduce phase distortion\n"
"-s suppress applying high pass filter at 80Hz "
"(rumble-removal highpass filter)\n"
"-e specifies the output frame interval for F0\n"
"-x maximum f0 to look for\n"
"-m minimum f0 to look for\n"
"-u regular inter-pulse interval to use in unvoiced regions\n"
"-a saves F0 and PM output in ascii mode\n"
"-d write diagnostic output to this file pattern\n";
int main(int argc, char* argv[]) {
int opt = 0;
std::string filename;
std::string f0_output;
std::string pm_output;
bool do_hilbert_transform = kDoHilbertTransform;
bool do_high_pass = kDoHighpass;
float external_frame_interval = kExternalFrameInterval;
float max_f0 = kMaxF0Search;
float min_f0 = kMinF0Search;
float inter_pulse = kUnvoicedPulseInterval;
bool ascii = false;
std::string debug_output;
while ((opt = getopt(argc, argv, "i:f:p:htse:x:m:u:ad:")) != -1) {
switch(opt) {
case 'i':
filename = optarg;
break;
case 'f':
f0_output = optarg;
break;
case 'p':
pm_output = optarg;
break;
case 't':
do_hilbert_transform = true;
break;
case 's':
do_high_pass = false;
break;
case 'e':
external_frame_interval = atof(optarg);
break;
case 'x':
max_f0 = atof(optarg);
break;
case 'm':
min_f0 = atof(optarg);
break;
case 'u':
inter_pulse = atof(optarg);
break;
case 'a':
ascii = true;
break;
case 'd':
debug_output = optarg;
break;
case 'h':
fprintf(stdout, "\n%s\n", kHelp);
return 0;
}
}
// Load input.
Wave wav;
if (!wav.Load(filename)) {
fprintf(stderr, "Failed to load waveform '%s'\n", filename.c_str());
return 1;
}
// Compute f0 and pitchmarks.
EpochTracker et;
if (!et.Init()) {
return 1;
}
if (!debug_output.empty()) {
et.set_debug_name(debug_output);
}
et.set_do_hilbert_transform(do_hilbert_transform);
et.set_do_highpass(do_high_pass);
et.set_external_frame_interval(external_frame_interval);
et.set_max_f0_search(max_f0);
et.set_min_f0_search(min_f0);
et.set_unvoiced_pulse_interval(inter_pulse);
Track *f0 = NULL;
Track *pm = NULL;
if (!et.ComputeEpochs(wav, &pm, &f0)) {
fprintf(stderr, "Failed to compute epochs\n");
return 1;
}
// Save outputs.
if (!f0_output.empty() && !f0->Save(f0_output, ascii)) {
delete f0;
fprintf(stderr, "Failed to save f0 to '%s'\n", f0_output.c_str());
return 1;
}
if (!pm_output.empty() && !pm->Save(pm_output, ascii)) {
delete pm;
fprintf(stderr, "Failed to save pitchmarks to '%s'\n", pm_output.c_str());
return 1;
}
delete f0;
delete pm;
return 0;
}
|
209b333f431e26ab146f3c04cef643c7ffcb23c0 | 02df46b70d7755cbb54bf716823941366a03e138 | /src/client/src/CellCounter.cpp | df130f6cacf21f0c3ee4586daee4b496b1aaad21 | [] | no_license | abbyAlbum/reversi | 49eb49d2eba99d16b116c383aefcd06c54a7aec9 | 495896af38594cab24550474b0d89ee7e923a8de | refs/heads/master | 2022-11-10T22:22:21.833685 | 2018-01-21T11:25:24 | 2018-01-21T11:25:24 | 275,802,832 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,048 | cpp | CellCounter.cpp | //
// Created by eyal moskowitz 314074303 on 13/11/17.
//
#include "../include/CellCounter.h"
/**
* constructor for CellCounter
* @param board
*/
CellCounter::CellCounter(Board *board) {
board_ = board;
xCounter_ = 0;
oCounter_ = 0;
spaceCounter_ = 0;
}
/**
* counts the num of cells of each type in each turn
*/
void CellCounter::count() {
Point p;
xCounter_ = 0;
oCounter_ = 0;
spaceCounter_ = 0;
for (int i = 0; i < board_->getSize(); ++i) {
for (int j = 0; j < board_->getSize(); ++j) {
p = Point(i, j);
if (board_->getStatus(p) == 'X') xCounter_++;
if (board_->getStatus(p) == 'O') oCounter_++;
if (board_->getStatus(p) == ' ') spaceCounter_++;
}
}
}
/**
* gives a specific counter according to the given symbol
* @param symbol
* @return counter
*/
int CellCounter::getCounter(char symbol) const {
if (symbol == 'X') return xCounter_;
if (symbol == 'O') return oCounter_;
if (symbol == ' ') return spaceCounter_;
} |
71f34dbc58acf00f3f1680f448a4b27b9d80cf4a | 048fddf3e02996a50163d014987d2a1e0f852b05 | /20130604/j.cpp | df14300e708d617cee4df5e9913d86d85b081d91 | [] | no_license | muhammadali493/Competitive-coding | 2a226d4214ea2a9c39dcd078d449d8791d80a033 | 0a6bb332fb2d05a4e647360a4c933e912107e581 | refs/heads/master | 2023-07-17T08:40:06.201930 | 2020-06-07T07:41:39 | 2020-06-07T07:41:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 687 | cpp | j.cpp | #include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
int mod = 2011;
int a[20010];
int sum[20010];
int cal(int n)
{
int x = n / 2010;
if(n % 2010 == 0) return x * sum[2009] % mod;
int y = n % 2010;
y --;
return (x * sum[2009] + sum[y]) % mod;
}
int main()
{
int n;
a[0] = 1;
sum[0] = 1;
for(int i = 1; i <= 2011; i ++) {
a[i] = a[i - 1] * 6 % mod;
sum[i] = (sum[i - 1] + a[i]) % mod;
}
while(scanf("%d",&n) != EOF) {
if(!n) break;
int ans1 = 1;
int ans2 = cal(n);
if(n > 1) ans1 = cal(n - 1) + 1;
else ans1 = 1;
printf("%d %d\n",ans1 % mod,ans2);
}
return 0;
}
|
6b4927d96478919504f95deaf7545fce28e36dc0 | 4589727948e83fc35a9a84b863fe415362632a77 | /toanroirac/Source1.cpp | 200e1ec35c018cd72e5105952bf6c72a6c5f0274 | [] | no_license | tamnk74/C-CplusplusSamples | 71174264832acc7502b4facb33b6f551414381c8 | ff4031926a5cafc251357afac94df076fbdb163e | refs/heads/master | 2023-02-06T08:08:44.554382 | 2020-12-26T16:55:08 | 2020-12-26T16:55:08 | 324,590,896 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 741 | cpp | Source1.cpp | ?#?include?<conio.h>
#include<stdio.h>
#include<string.h>
int count=1,n;
void nhap(int *a)
{
int i;
for(i=1;i<=n;i++) a[i]=i;
}
void xuat(int a[])
{
int i;
printf("\n %2d \t",count);
count++;
for(i=1;i<=n;i++)
printf("%d",a[i]);
}
int kt(int a[])
{
int i;
for(i=1;i<=n-1;i++) if(a[i]>a[i+1]) return 0;
return 1;
}
void next(int a[])
{
int i,j,l,k,t;
i=n-1;
j=n;
while(i>=1&&(a[i]>a[i+1]))i--;
while(a[j]<a[i])j--;
t=a[i];
a[i]=a[j];
a[j]=t;
l=i+1;
k=n;
while(l<k)
{
t=a[l];
a[l]=a[k];
a[n]=t;
l++;k--;
}
}
int main ()
{
int a[20],c;
printf("nhap n:");
scanf("%d",&n);
nhap(a);
printf("hoan vi la:");
xuat(a);
c=kt(a);
while(c==1)
{
next(a);
xuat(a);
c=kt(a);
}
getch();
return 1;
} |
caeca71f8eecafcd4042db4194f40d69b05f0d3c | 84c89092e056d5823ad63c157f4bb00babcc339d | /src/ListWindowBase.hpp | 5260e4a5a403ac65cf36019363c49b6daab2b0e9 | [] | no_license | kamilpe/investigator | f5efc17be05c95e96b8696e7610a460c367a1ae8 | 8ea51369d69f5d7dc1c0fad29db573ac5b1723d2 | refs/heads/master | 2020-03-29T07:12:01.313071 | 2020-02-04T19:11:34 | 2020-02-04T19:11:34 | 149,656,760 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,549 | hpp | ListWindowBase.hpp | #pragma once
#include "IAppContext.hpp"
#include "Toolkit/Window.hpp"
#include <memory>
template<typename ItemType>
class ListWindowBase : public Window
{
public:
using Items = std::vector<ItemType>;
ListWindowBase(IAppContext &context,
const Items &items,
const typename Items::const_iterator selected) :
Window(context.display(), 0, 0, 0, 0),
items_(items),
selected_(selected)
{
}
~ListWindowBase()
{
}
void select(const typename Items::const_iterator selected)
{
selected_ = selected;
}
void up()
{
if (selected_ == items_.cend())
return;
if (selected_ > items_.cbegin())
selected_--;
}
void down()
{
if (selected_ == items_.cend())
return;
if (selected_ < items_.end() - 1)
selected_++;
}
const Items& items() const
{
return items_;
}
const typename Items::const_iterator selected() const {
return selected_;
}
protected:
virtual void printLine(int x, int y, bool selected, typename Items::const_iterator &line) const = 0;
void drawList(int x, int y, int count) const
{
for (auto it = items_.begin();
it != items_.end() && count > 0;
++it)
{
printLine(x, y, (it == selected_), it);
y++;
}
}
private:
const Items& items_;
typename Items::const_iterator selected_;
};
|
41ff152cb5e26df697c0cb5ec5fd8d114b8f2d9e | 8da9d3c3e769ead17f5ad4a4cba6fb3e84a9e340 | /src/chila/connectionTools/designer/app/impl/connection/Logger.hpp | 480f3d89db60109a2b778f2b83e9c9b68ca299f4 | [] | no_license | blockspacer/chila | 6884a540fafa73db37f2bf0117410c33044adbcf | b95290725b54696f7cefc1c430582f90542b1dec | refs/heads/master | 2021-06-05T10:22:53.536352 | 2016-08-24T15:07:49 | 2016-08-24T15:07:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,011 | hpp | Logger.hpp | /* Copyright 2011-2015 Roberto Daniel Gimenez Gamarra (chilabot@gmail.com)
* (C.I.: 1.439.390 - Paraguay)
*/
#ifndef CHILA_CONNECTIONTOOLS_DESIGNER_APP_IMPL_CONNECTION__LOGGER_HPP
#define CHILA_CONNECTIONTOOLS_DESIGNER_APP_IMPL_CONNECTION__LOGGER_HPP
#include "fwd.hpp"
#include "../fwd.hpp"
#include <chila/lib/misc/Path.hpp>
#include "../../connectors/gen/Logger.hpp"
#include "../../../lib/actions.hpp"
#define FWDEC_SPTR CHILA_LIB_MISC__FWDEC_SPTR
#include "macros.fgen.hpp"
MY_NSP_START
{
struct Logger
{
struct ArgTypes
{
using moduleName = std::string;
using cToolsPath = chila::lib::misc::Path;
};
using Connector = connectors::gen::Logger<ArgTypes>;
struct CProvider: public connection::CProvider
{
virtual Connector &getConnector() = 0;
};
FWDEC_SPTR(CProvider);
static CProviderSPtr create();
};
}
MY_NSP_END
#include "macros.fgen.hpp"
#undef FWDEC_SPTR
#endif
|
b10331ee3b3b26b68cbd22a9c6b03edc355ff983 | d5d0a7d1da7c63ff3d20f9501a9b32e4678c044b | /test2/Funk.cpp | 0c4efbe37f5774d92839f5da0e607f9b66eb1bf5 | [] | no_license | anastasia94/nastya | 3fc0c8ee4d25e143b23d5fe606608b025228120e | 8d209d0925a4ef60dee301f2ca0c34bb3722322c | refs/heads/master | 2021-01-25T07:28:29.061566 | 2012-11-26T21:04:10 | 2012-11-26T21:04:10 | null | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 1,520 | cpp | Funk.cpp | //trolo
#include <iostream>
#include <Windows.h>
#include <math.h>
using namespace std;
bool funk_c(float ,float );
bool funk_a(float ,float );
bool funk_b(float ,float );
int input (int&);
int main()
{
float x,y;
int pr;
int k;
SetConsoleOutputCP(1251);
do
{
cout<<"Введите x---> ";
while (input (k));
cout<<"Ввод произведен правильно, повторите ввод"<<endl;
cout<<"Введите x---> ";
cin>>x;
cout<<"Введите y---> ";
while (input (k));
cout<<"Ввод произведен правильно, повторите ввод"<<endl;
cout<<"Введите y---> ";
cin>>y;
if(funk_c(x,y)==true||funk_b(x,y)==true||funk_a(x,y)==true)
cout<<"Входит"<<endl;
else cout<<"Не входит"<<endl;
pr=true;
cout<<"Повтроить ещё раз? 0-нет, 1-да"<<endl;
cin>>pr;
}
while(pr==1);
return 0;
}
bool funk_c(float x,float y)
{
if((y<=3*x+3)&&(y<=-3*x+3)&&(y>=-1)&&(x*x+y*y>=1))
return true;
else return false;
}
bool funk_a(float x,float y)
{
if((y<=-1)&&(y>=-3*x+3))
return true;
else return false;
}
bool funk_b(float x,float y)
{
if((y<=-1)&&(y>=3*x+3))
return true;
else return false;
}
int input (int&k)
{
cin>>k;
if(cin.fail()||cin.bad())
{
cout<<"Ошибка ввода, только числовые значения!!!"<<endl;
cin.clear();
while (cin.get()!='\n')continue;
cout<<"Попробуйте ещё раз!--->";
return 1;
}
return 0;
} |
bc0143c9f0560d26d668a0d0d367b53fc6b32a3f | 7cedb19cd799cb16a201b4390dc1da01d3391a4c | /IAOINode.h | 8a8f89d0ca68894bac6122383a3cbf149c4cf436 | [] | no_license | apheros/AOIService | 1ff9b1305091c0257d86fb416d06ba11cb5fb20c | b152abbf3ab9ccb0a6d0bad22aaf787c759a27ff | refs/heads/master | 2021-01-21T17:10:14.096463 | 2017-05-21T07:38:53 | 2017-05-21T07:38:53 | 91,938,371 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,025 | h | IAOINode.h | #pragma once
#include <vector>
#include <set>
namespace AOIService
{
class AOIService;
class IAOINode
{
public:
IAOINode() {}
virtual ~IAOINode() {}
public:
virtual void setService(AOIService* service) = 0;
virtual int positionX() = 0;
virtual int positionY() = 0;
virtual IAOINode* getXForwardNode() = 0;
virtual IAOINode* getYForwardNode() = 0;
virtual IAOINode* getXBackwardNode() = 0;
virtual IAOINode* getYBackwardNode() = 0;
virtual void setXForwardNode(IAOINode* node) = 0;
virtual void setYForwardNode(IAOINode* node) = 0;
virtual void setXBackwardNode(IAOINode* node) = 0;
virtual void setYBackwardNode(IAOINode* node) = 0;
virtual int getWatchRange() = 0;
virtual void onMove() = 0;
virtual bool isInRange(IAOINode* node, int range) = 0;
virtual void onEnterAOI(IAOINode* node) = 0;
virtual void onLeaveAOI(IAOINode* node) = 0;
};
typedef std::vector<IAOINode*> AOINodeVector;
typedef std::set<IAOINode*> AOINodeSet;
}
|
a445b667a14083b156c2de7272ba8763bee20753 | fb5b25b4fbe66c532672c14dacc520b96ff90a04 | /export/release/macos/obj/src/lime/graphics/opengl/ext/KHR_debug.cpp | 8e1d1910e7f22a21d06129bf03ca7e538a67608e | [
"Apache-2.0"
] | permissive | Tyrcnex/tai-mod | c3849f817fe871004ed171245d63c5e447c4a9c3 | b83152693bb3139ee2ae73002623934f07d35baf | refs/heads/main | 2023-08-15T07:15:43.884068 | 2021-09-29T23:39:23 | 2021-09-29T23:39:23 | 383,313,424 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | true | 21,333 | cpp | KHR_debug.cpp | // Generated by Haxe 4.1.5
#include <hxcpp.h>
#ifndef INCLUDED_lime_graphics_opengl_ext_KHR_debug
#include <lime/graphics/opengl/ext/KHR_debug.h>
#endif
HX_DEFINE_STACK_FRAME(_hx_pos_e7ead9e1a8712dad_4_new,"lime.graphics.opengl.ext.KHR_debug","new",0xa09f74f9,"lime.graphics.opengl.ext.KHR_debug.new","lime/graphics/opengl/ext/KHR_debug.hx",4,0x748ce039)
namespace lime{
namespace graphics{
namespace opengl{
namespace ext{
void KHR_debug_obj::__construct(){
HX_STACKFRAME(&_hx_pos_e7ead9e1a8712dad_4_new)
HXLINE( 43) this->STACK_UNDERFLOW = 1284;
HXLINE( 42) this->STACK_OVERFLOW = 1283;
HXLINE( 41) this->CONTEXT_FLAG_DEBUG_BIT = 2;
HXLINE( 40) this->DEBUG_OUTPUT = 37600;
HXLINE( 39) this->DEBUG_SEVERITY_LOW = 37192;
HXLINE( 38) this->DEBUG_SEVERITY_MEDIUM = 37191;
HXLINE( 37) this->DEBUG_SEVERITY_HIGH = 37190;
HXLINE( 36) this->DEBUG_LOGGED_MESSAGES = 37189;
HXLINE( 35) this->MAX_DEBUG_LOGGED_MESSAGES = 37188;
HXLINE( 34) this->MAX_DEBUG_MESSAGE_LENGTH = 37187;
HXLINE( 33) this->MAX_LABEL_LENGTH = 33512;
HXLINE( 32) this->SAMPLER = 33510;
HXLINE( 31) this->QUERY = 33507;
HXLINE( 30) this->PROGRAM = 33506;
HXLINE( 29) this->SHADER = 33505;
HXLINE( 28) this->BUFFER = 33504;
HXLINE( 27) this->DEBUG_GROUP_STACK_DEPTH = 33389;
HXLINE( 26) this->MAX_DEBUG_GROUP_STACK_DEPTH = 33388;
HXLINE( 25) this->DEBUG_SEVERITY_NOTIFICATION = 33387;
HXLINE( 24) this->DEBUG_TYPE_POP_GROUP = 33386;
HXLINE( 23) this->DEBUG_TYPE_PUSH_GROUP = 33385;
HXLINE( 22) this->DEBUG_TYPE_MARKER = 33384;
HXLINE( 21) this->DEBUG_TYPE_OTHER = 33361;
HXLINE( 20) this->DEBUG_TYPE_PERFORMANCE = 33360;
HXLINE( 19) this->DEBUG_TYPE_PORTABILITY = 33359;
HXLINE( 18) this->DEBUG_TYPE_UNDEFINED_BEHAVIOR = 33358;
HXLINE( 17) this->DEBUG_TYPE_DEPRECATED_BEHAVIOR = 33357;
HXLINE( 16) this->DEBUG_TYPE_ERROR = 33356;
HXLINE( 15) this->DEBUG_SOURCE_OTHER = 33355;
HXLINE( 14) this->DEBUG_SOURCE_APPLICATION = 33354;
HXLINE( 13) this->DEBUG_SOURCE_THIRD_PARTY = 33353;
HXLINE( 12) this->DEBUG_SOURCE_SHADER_COMPILER = 33352;
HXLINE( 11) this->DEBUG_SOURCE_WINDOW_SYSTEM = 33351;
HXLINE( 10) this->DEBUG_SOURCE_API = 33350;
HXLINE( 9) this->DEBUG_CALLBACK_USER_PARAM = 33349;
HXLINE( 8) this->DEBUG_CALLBACK_FUNCTION = 33348;
HXLINE( 7) this->DEBUG_NEXT_LOGGED_MESSAGE_LENGTH = 33347;
HXLINE( 6) this->DEBUG_OUTPUT_SYNCHRONOUS = 33346;
}
Dynamic KHR_debug_obj::__CreateEmpty() { return new KHR_debug_obj; }
void *KHR_debug_obj::_hx_vtable = 0;
Dynamic KHR_debug_obj::__Create(::hx::DynamicArray inArgs)
{
::hx::ObjectPtr< KHR_debug_obj > _hx_result = new KHR_debug_obj();
_hx_result->__construct();
return _hx_result;
}
bool KHR_debug_obj::_hx_isInstanceOf(int inClassId) {
return inClassId==(int)0x00000001 || inClassId==(int)0x2275abff;
}
KHR_debug_obj::KHR_debug_obj()
{
}
::hx::Val KHR_debug_obj::__Field(const ::String &inName,::hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 5:
if (HX_FIELD_EQ(inName,"QUERY") ) { return ::hx::Val( QUERY ); }
break;
case 6:
if (HX_FIELD_EQ(inName,"BUFFER") ) { return ::hx::Val( BUFFER ); }
if (HX_FIELD_EQ(inName,"SHADER") ) { return ::hx::Val( SHADER ); }
break;
case 7:
if (HX_FIELD_EQ(inName,"PROGRAM") ) { return ::hx::Val( PROGRAM ); }
if (HX_FIELD_EQ(inName,"SAMPLER") ) { return ::hx::Val( SAMPLER ); }
break;
case 12:
if (HX_FIELD_EQ(inName,"DEBUG_OUTPUT") ) { return ::hx::Val( DEBUG_OUTPUT ); }
break;
case 14:
if (HX_FIELD_EQ(inName,"STACK_OVERFLOW") ) { return ::hx::Val( STACK_OVERFLOW ); }
break;
case 15:
if (HX_FIELD_EQ(inName,"STACK_UNDERFLOW") ) { return ::hx::Val( STACK_UNDERFLOW ); }
break;
case 16:
if (HX_FIELD_EQ(inName,"DEBUG_SOURCE_API") ) { return ::hx::Val( DEBUG_SOURCE_API ); }
if (HX_FIELD_EQ(inName,"DEBUG_TYPE_ERROR") ) { return ::hx::Val( DEBUG_TYPE_ERROR ); }
if (HX_FIELD_EQ(inName,"DEBUG_TYPE_OTHER") ) { return ::hx::Val( DEBUG_TYPE_OTHER ); }
if (HX_FIELD_EQ(inName,"MAX_LABEL_LENGTH") ) { return ::hx::Val( MAX_LABEL_LENGTH ); }
break;
case 17:
if (HX_FIELD_EQ(inName,"DEBUG_TYPE_MARKER") ) { return ::hx::Val( DEBUG_TYPE_MARKER ); }
break;
case 18:
if (HX_FIELD_EQ(inName,"DEBUG_SOURCE_OTHER") ) { return ::hx::Val( DEBUG_SOURCE_OTHER ); }
if (HX_FIELD_EQ(inName,"DEBUG_SEVERITY_LOW") ) { return ::hx::Val( DEBUG_SEVERITY_LOW ); }
break;
case 19:
if (HX_FIELD_EQ(inName,"DEBUG_SEVERITY_HIGH") ) { return ::hx::Val( DEBUG_SEVERITY_HIGH ); }
break;
case 20:
if (HX_FIELD_EQ(inName,"DEBUG_TYPE_POP_GROUP") ) { return ::hx::Val( DEBUG_TYPE_POP_GROUP ); }
break;
case 21:
if (HX_FIELD_EQ(inName,"DEBUG_TYPE_PUSH_GROUP") ) { return ::hx::Val( DEBUG_TYPE_PUSH_GROUP ); }
if (HX_FIELD_EQ(inName,"DEBUG_LOGGED_MESSAGES") ) { return ::hx::Val( DEBUG_LOGGED_MESSAGES ); }
if (HX_FIELD_EQ(inName,"DEBUG_SEVERITY_MEDIUM") ) { return ::hx::Val( DEBUG_SEVERITY_MEDIUM ); }
break;
case 22:
if (HX_FIELD_EQ(inName,"DEBUG_TYPE_PORTABILITY") ) { return ::hx::Val( DEBUG_TYPE_PORTABILITY ); }
if (HX_FIELD_EQ(inName,"DEBUG_TYPE_PERFORMANCE") ) { return ::hx::Val( DEBUG_TYPE_PERFORMANCE ); }
if (HX_FIELD_EQ(inName,"CONTEXT_FLAG_DEBUG_BIT") ) { return ::hx::Val( CONTEXT_FLAG_DEBUG_BIT ); }
break;
case 23:
if (HX_FIELD_EQ(inName,"DEBUG_CALLBACK_FUNCTION") ) { return ::hx::Val( DEBUG_CALLBACK_FUNCTION ); }
if (HX_FIELD_EQ(inName,"DEBUG_GROUP_STACK_DEPTH") ) { return ::hx::Val( DEBUG_GROUP_STACK_DEPTH ); }
break;
case 24:
if (HX_FIELD_EQ(inName,"DEBUG_OUTPUT_SYNCHRONOUS") ) { return ::hx::Val( DEBUG_OUTPUT_SYNCHRONOUS ); }
if (HX_FIELD_EQ(inName,"DEBUG_SOURCE_THIRD_PARTY") ) { return ::hx::Val( DEBUG_SOURCE_THIRD_PARTY ); }
if (HX_FIELD_EQ(inName,"DEBUG_SOURCE_APPLICATION") ) { return ::hx::Val( DEBUG_SOURCE_APPLICATION ); }
if (HX_FIELD_EQ(inName,"MAX_DEBUG_MESSAGE_LENGTH") ) { return ::hx::Val( MAX_DEBUG_MESSAGE_LENGTH ); }
break;
case 25:
if (HX_FIELD_EQ(inName,"DEBUG_CALLBACK_USER_PARAM") ) { return ::hx::Val( DEBUG_CALLBACK_USER_PARAM ); }
if (HX_FIELD_EQ(inName,"MAX_DEBUG_LOGGED_MESSAGES") ) { return ::hx::Val( MAX_DEBUG_LOGGED_MESSAGES ); }
break;
case 26:
if (HX_FIELD_EQ(inName,"DEBUG_SOURCE_WINDOW_SYSTEM") ) { return ::hx::Val( DEBUG_SOURCE_WINDOW_SYSTEM ); }
break;
case 27:
if (HX_FIELD_EQ(inName,"DEBUG_SEVERITY_NOTIFICATION") ) { return ::hx::Val( DEBUG_SEVERITY_NOTIFICATION ); }
if (HX_FIELD_EQ(inName,"MAX_DEBUG_GROUP_STACK_DEPTH") ) { return ::hx::Val( MAX_DEBUG_GROUP_STACK_DEPTH ); }
break;
case 28:
if (HX_FIELD_EQ(inName,"DEBUG_SOURCE_SHADER_COMPILER") ) { return ::hx::Val( DEBUG_SOURCE_SHADER_COMPILER ); }
break;
case 29:
if (HX_FIELD_EQ(inName,"DEBUG_TYPE_UNDEFINED_BEHAVIOR") ) { return ::hx::Val( DEBUG_TYPE_UNDEFINED_BEHAVIOR ); }
break;
case 30:
if (HX_FIELD_EQ(inName,"DEBUG_TYPE_DEPRECATED_BEHAVIOR") ) { return ::hx::Val( DEBUG_TYPE_DEPRECATED_BEHAVIOR ); }
break;
case 32:
if (HX_FIELD_EQ(inName,"DEBUG_NEXT_LOGGED_MESSAGE_LENGTH") ) { return ::hx::Val( DEBUG_NEXT_LOGGED_MESSAGE_LENGTH ); }
}
return super::__Field(inName,inCallProp);
}
::hx::Val KHR_debug_obj::__SetField(const ::String &inName,const ::hx::Val &inValue,::hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 5:
if (HX_FIELD_EQ(inName,"QUERY") ) { QUERY=inValue.Cast< int >(); return inValue; }
break;
case 6:
if (HX_FIELD_EQ(inName,"BUFFER") ) { BUFFER=inValue.Cast< int >(); return inValue; }
if (HX_FIELD_EQ(inName,"SHADER") ) { SHADER=inValue.Cast< int >(); return inValue; }
break;
case 7:
if (HX_FIELD_EQ(inName,"PROGRAM") ) { PROGRAM=inValue.Cast< int >(); return inValue; }
if (HX_FIELD_EQ(inName,"SAMPLER") ) { SAMPLER=inValue.Cast< int >(); return inValue; }
break;
case 12:
if (HX_FIELD_EQ(inName,"DEBUG_OUTPUT") ) { DEBUG_OUTPUT=inValue.Cast< int >(); return inValue; }
break;
case 14:
if (HX_FIELD_EQ(inName,"STACK_OVERFLOW") ) { STACK_OVERFLOW=inValue.Cast< int >(); return inValue; }
break;
case 15:
if (HX_FIELD_EQ(inName,"STACK_UNDERFLOW") ) { STACK_UNDERFLOW=inValue.Cast< int >(); return inValue; }
break;
case 16:
if (HX_FIELD_EQ(inName,"DEBUG_SOURCE_API") ) { DEBUG_SOURCE_API=inValue.Cast< int >(); return inValue; }
if (HX_FIELD_EQ(inName,"DEBUG_TYPE_ERROR") ) { DEBUG_TYPE_ERROR=inValue.Cast< int >(); return inValue; }
if (HX_FIELD_EQ(inName,"DEBUG_TYPE_OTHER") ) { DEBUG_TYPE_OTHER=inValue.Cast< int >(); return inValue; }
if (HX_FIELD_EQ(inName,"MAX_LABEL_LENGTH") ) { MAX_LABEL_LENGTH=inValue.Cast< int >(); return inValue; }
break;
case 17:
if (HX_FIELD_EQ(inName,"DEBUG_TYPE_MARKER") ) { DEBUG_TYPE_MARKER=inValue.Cast< int >(); return inValue; }
break;
case 18:
if (HX_FIELD_EQ(inName,"DEBUG_SOURCE_OTHER") ) { DEBUG_SOURCE_OTHER=inValue.Cast< int >(); return inValue; }
if (HX_FIELD_EQ(inName,"DEBUG_SEVERITY_LOW") ) { DEBUG_SEVERITY_LOW=inValue.Cast< int >(); return inValue; }
break;
case 19:
if (HX_FIELD_EQ(inName,"DEBUG_SEVERITY_HIGH") ) { DEBUG_SEVERITY_HIGH=inValue.Cast< int >(); return inValue; }
break;
case 20:
if (HX_FIELD_EQ(inName,"DEBUG_TYPE_POP_GROUP") ) { DEBUG_TYPE_POP_GROUP=inValue.Cast< int >(); return inValue; }
break;
case 21:
if (HX_FIELD_EQ(inName,"DEBUG_TYPE_PUSH_GROUP") ) { DEBUG_TYPE_PUSH_GROUP=inValue.Cast< int >(); return inValue; }
if (HX_FIELD_EQ(inName,"DEBUG_LOGGED_MESSAGES") ) { DEBUG_LOGGED_MESSAGES=inValue.Cast< int >(); return inValue; }
if (HX_FIELD_EQ(inName,"DEBUG_SEVERITY_MEDIUM") ) { DEBUG_SEVERITY_MEDIUM=inValue.Cast< int >(); return inValue; }
break;
case 22:
if (HX_FIELD_EQ(inName,"DEBUG_TYPE_PORTABILITY") ) { DEBUG_TYPE_PORTABILITY=inValue.Cast< int >(); return inValue; }
if (HX_FIELD_EQ(inName,"DEBUG_TYPE_PERFORMANCE") ) { DEBUG_TYPE_PERFORMANCE=inValue.Cast< int >(); return inValue; }
if (HX_FIELD_EQ(inName,"CONTEXT_FLAG_DEBUG_BIT") ) { CONTEXT_FLAG_DEBUG_BIT=inValue.Cast< int >(); return inValue; }
break;
case 23:
if (HX_FIELD_EQ(inName,"DEBUG_CALLBACK_FUNCTION") ) { DEBUG_CALLBACK_FUNCTION=inValue.Cast< int >(); return inValue; }
if (HX_FIELD_EQ(inName,"DEBUG_GROUP_STACK_DEPTH") ) { DEBUG_GROUP_STACK_DEPTH=inValue.Cast< int >(); return inValue; }
break;
case 24:
if (HX_FIELD_EQ(inName,"DEBUG_OUTPUT_SYNCHRONOUS") ) { DEBUG_OUTPUT_SYNCHRONOUS=inValue.Cast< int >(); return inValue; }
if (HX_FIELD_EQ(inName,"DEBUG_SOURCE_THIRD_PARTY") ) { DEBUG_SOURCE_THIRD_PARTY=inValue.Cast< int >(); return inValue; }
if (HX_FIELD_EQ(inName,"DEBUG_SOURCE_APPLICATION") ) { DEBUG_SOURCE_APPLICATION=inValue.Cast< int >(); return inValue; }
if (HX_FIELD_EQ(inName,"MAX_DEBUG_MESSAGE_LENGTH") ) { MAX_DEBUG_MESSAGE_LENGTH=inValue.Cast< int >(); return inValue; }
break;
case 25:
if (HX_FIELD_EQ(inName,"DEBUG_CALLBACK_USER_PARAM") ) { DEBUG_CALLBACK_USER_PARAM=inValue.Cast< int >(); return inValue; }
if (HX_FIELD_EQ(inName,"MAX_DEBUG_LOGGED_MESSAGES") ) { MAX_DEBUG_LOGGED_MESSAGES=inValue.Cast< int >(); return inValue; }
break;
case 26:
if (HX_FIELD_EQ(inName,"DEBUG_SOURCE_WINDOW_SYSTEM") ) { DEBUG_SOURCE_WINDOW_SYSTEM=inValue.Cast< int >(); return inValue; }
break;
case 27:
if (HX_FIELD_EQ(inName,"DEBUG_SEVERITY_NOTIFICATION") ) { DEBUG_SEVERITY_NOTIFICATION=inValue.Cast< int >(); return inValue; }
if (HX_FIELD_EQ(inName,"MAX_DEBUG_GROUP_STACK_DEPTH") ) { MAX_DEBUG_GROUP_STACK_DEPTH=inValue.Cast< int >(); return inValue; }
break;
case 28:
if (HX_FIELD_EQ(inName,"DEBUG_SOURCE_SHADER_COMPILER") ) { DEBUG_SOURCE_SHADER_COMPILER=inValue.Cast< int >(); return inValue; }
break;
case 29:
if (HX_FIELD_EQ(inName,"DEBUG_TYPE_UNDEFINED_BEHAVIOR") ) { DEBUG_TYPE_UNDEFINED_BEHAVIOR=inValue.Cast< int >(); return inValue; }
break;
case 30:
if (HX_FIELD_EQ(inName,"DEBUG_TYPE_DEPRECATED_BEHAVIOR") ) { DEBUG_TYPE_DEPRECATED_BEHAVIOR=inValue.Cast< int >(); return inValue; }
break;
case 32:
if (HX_FIELD_EQ(inName,"DEBUG_NEXT_LOGGED_MESSAGE_LENGTH") ) { DEBUG_NEXT_LOGGED_MESSAGE_LENGTH=inValue.Cast< int >(); return inValue; }
}
return super::__SetField(inName,inValue,inCallProp);
}
void KHR_debug_obj::__GetFields(Array< ::String> &outFields)
{
outFields->push(HX_("DEBUG_OUTPUT_SYNCHRONOUS",b7,6c,34,b8));
outFields->push(HX_("DEBUG_NEXT_LOGGED_MESSAGE_LENGTH",5b,ea,d6,b8));
outFields->push(HX_("DEBUG_CALLBACK_FUNCTION",c6,df,cb,cf));
outFields->push(HX_("DEBUG_CALLBACK_USER_PARAM",67,50,4b,b2));
outFields->push(HX_("DEBUG_SOURCE_API",a2,9d,a7,fc));
outFields->push(HX_("DEBUG_SOURCE_WINDOW_SYSTEM",c6,f9,dc,4e));
outFields->push(HX_("DEBUG_SOURCE_SHADER_COMPILER",61,d0,c4,2b));
outFields->push(HX_("DEBUG_SOURCE_THIRD_PARTY",f6,6f,06,29));
outFields->push(HX_("DEBUG_SOURCE_APPLICATION",58,24,b6,0f));
outFields->push(HX_("DEBUG_SOURCE_OTHER",d8,3d,44,3e));
outFields->push(HX_("DEBUG_TYPE_ERROR",ef,26,40,e9));
outFields->push(HX_("DEBUG_TYPE_DEPRECATED_BEHAVIOR",a5,cf,17,8c));
outFields->push(HX_("DEBUG_TYPE_UNDEFINED_BEHAVIOR",da,37,6a,74));
outFields->push(HX_("DEBUG_TYPE_PORTABILITY",b0,1e,6b,9d));
outFields->push(HX_("DEBUG_TYPE_PERFORMANCE",57,2c,fb,eb));
outFields->push(HX_("DEBUG_TYPE_OTHER",f7,c1,8c,ac));
outFields->push(HX_("DEBUG_TYPE_MARKER",93,dc,e9,97));
outFields->push(HX_("DEBUG_TYPE_PUSH_GROUP",13,87,6b,ca));
outFields->push(HX_("DEBUG_TYPE_POP_GROUP",58,29,6a,b8));
outFields->push(HX_("DEBUG_SEVERITY_NOTIFICATION",a1,b3,a6,11));
outFields->push(HX_("MAX_DEBUG_GROUP_STACK_DEPTH",a5,1e,fc,f4));
outFields->push(HX_("DEBUG_GROUP_STACK_DEPTH",a0,e0,2d,54));
outFields->push(HX_("BUFFER",00,69,17,83));
outFields->push(HX_("SHADER",25,6b,a3,cf));
outFields->push(HX_("PROGRAM",64,1e,cd,73));
outFields->push(HX_("QUERY",e8,c2,d8,db));
outFields->push(HX_("SAMPLER",e8,98,9d,03));
outFields->push(HX_("MAX_LABEL_LENGTH",0c,59,f0,f1));
outFields->push(HX_("MAX_DEBUG_MESSAGE_LENGTH",65,08,17,87));
outFields->push(HX_("MAX_DEBUG_LOGGED_MESSAGES",e2,62,56,d5));
outFields->push(HX_("DEBUG_LOGGED_MESSAGES",1d,20,32,f8));
outFields->push(HX_("DEBUG_SEVERITY_HIGH",18,be,8d,35));
outFields->push(HX_("DEBUG_SEVERITY_MEDIUM",ab,58,3f,b3));
outFields->push(HX_("DEBUG_SEVERITY_LOW",7e,fa,43,a3));
outFields->push(HX_("DEBUG_OUTPUT",cd,3e,9f,da));
outFields->push(HX_("CONTEXT_FLAG_DEBUG_BIT",7e,17,c3,b0));
outFields->push(HX_("STACK_OVERFLOW",79,a6,54,a5));
outFields->push(HX_("STACK_UNDERFLOW",cf,21,6e,b5));
super::__GetFields(outFields);
};
#ifdef HXCPP_SCRIPTABLE
static ::hx::StorageInfo KHR_debug_obj_sMemberStorageInfo[] = {
{::hx::fsInt,(int)offsetof(KHR_debug_obj,DEBUG_OUTPUT_SYNCHRONOUS),HX_("DEBUG_OUTPUT_SYNCHRONOUS",b7,6c,34,b8)},
{::hx::fsInt,(int)offsetof(KHR_debug_obj,DEBUG_NEXT_LOGGED_MESSAGE_LENGTH),HX_("DEBUG_NEXT_LOGGED_MESSAGE_LENGTH",5b,ea,d6,b8)},
{::hx::fsInt,(int)offsetof(KHR_debug_obj,DEBUG_CALLBACK_FUNCTION),HX_("DEBUG_CALLBACK_FUNCTION",c6,df,cb,cf)},
{::hx::fsInt,(int)offsetof(KHR_debug_obj,DEBUG_CALLBACK_USER_PARAM),HX_("DEBUG_CALLBACK_USER_PARAM",67,50,4b,b2)},
{::hx::fsInt,(int)offsetof(KHR_debug_obj,DEBUG_SOURCE_API),HX_("DEBUG_SOURCE_API",a2,9d,a7,fc)},
{::hx::fsInt,(int)offsetof(KHR_debug_obj,DEBUG_SOURCE_WINDOW_SYSTEM),HX_("DEBUG_SOURCE_WINDOW_SYSTEM",c6,f9,dc,4e)},
{::hx::fsInt,(int)offsetof(KHR_debug_obj,DEBUG_SOURCE_SHADER_COMPILER),HX_("DEBUG_SOURCE_SHADER_COMPILER",61,d0,c4,2b)},
{::hx::fsInt,(int)offsetof(KHR_debug_obj,DEBUG_SOURCE_THIRD_PARTY),HX_("DEBUG_SOURCE_THIRD_PARTY",f6,6f,06,29)},
{::hx::fsInt,(int)offsetof(KHR_debug_obj,DEBUG_SOURCE_APPLICATION),HX_("DEBUG_SOURCE_APPLICATION",58,24,b6,0f)},
{::hx::fsInt,(int)offsetof(KHR_debug_obj,DEBUG_SOURCE_OTHER),HX_("DEBUG_SOURCE_OTHER",d8,3d,44,3e)},
{::hx::fsInt,(int)offsetof(KHR_debug_obj,DEBUG_TYPE_ERROR),HX_("DEBUG_TYPE_ERROR",ef,26,40,e9)},
{::hx::fsInt,(int)offsetof(KHR_debug_obj,DEBUG_TYPE_DEPRECATED_BEHAVIOR),HX_("DEBUG_TYPE_DEPRECATED_BEHAVIOR",a5,cf,17,8c)},
{::hx::fsInt,(int)offsetof(KHR_debug_obj,DEBUG_TYPE_UNDEFINED_BEHAVIOR),HX_("DEBUG_TYPE_UNDEFINED_BEHAVIOR",da,37,6a,74)},
{::hx::fsInt,(int)offsetof(KHR_debug_obj,DEBUG_TYPE_PORTABILITY),HX_("DEBUG_TYPE_PORTABILITY",b0,1e,6b,9d)},
{::hx::fsInt,(int)offsetof(KHR_debug_obj,DEBUG_TYPE_PERFORMANCE),HX_("DEBUG_TYPE_PERFORMANCE",57,2c,fb,eb)},
{::hx::fsInt,(int)offsetof(KHR_debug_obj,DEBUG_TYPE_OTHER),HX_("DEBUG_TYPE_OTHER",f7,c1,8c,ac)},
{::hx::fsInt,(int)offsetof(KHR_debug_obj,DEBUG_TYPE_MARKER),HX_("DEBUG_TYPE_MARKER",93,dc,e9,97)},
{::hx::fsInt,(int)offsetof(KHR_debug_obj,DEBUG_TYPE_PUSH_GROUP),HX_("DEBUG_TYPE_PUSH_GROUP",13,87,6b,ca)},
{::hx::fsInt,(int)offsetof(KHR_debug_obj,DEBUG_TYPE_POP_GROUP),HX_("DEBUG_TYPE_POP_GROUP",58,29,6a,b8)},
{::hx::fsInt,(int)offsetof(KHR_debug_obj,DEBUG_SEVERITY_NOTIFICATION),HX_("DEBUG_SEVERITY_NOTIFICATION",a1,b3,a6,11)},
{::hx::fsInt,(int)offsetof(KHR_debug_obj,MAX_DEBUG_GROUP_STACK_DEPTH),HX_("MAX_DEBUG_GROUP_STACK_DEPTH",a5,1e,fc,f4)},
{::hx::fsInt,(int)offsetof(KHR_debug_obj,DEBUG_GROUP_STACK_DEPTH),HX_("DEBUG_GROUP_STACK_DEPTH",a0,e0,2d,54)},
{::hx::fsInt,(int)offsetof(KHR_debug_obj,BUFFER),HX_("BUFFER",00,69,17,83)},
{::hx::fsInt,(int)offsetof(KHR_debug_obj,SHADER),HX_("SHADER",25,6b,a3,cf)},
{::hx::fsInt,(int)offsetof(KHR_debug_obj,PROGRAM),HX_("PROGRAM",64,1e,cd,73)},
{::hx::fsInt,(int)offsetof(KHR_debug_obj,QUERY),HX_("QUERY",e8,c2,d8,db)},
{::hx::fsInt,(int)offsetof(KHR_debug_obj,SAMPLER),HX_("SAMPLER",e8,98,9d,03)},
{::hx::fsInt,(int)offsetof(KHR_debug_obj,MAX_LABEL_LENGTH),HX_("MAX_LABEL_LENGTH",0c,59,f0,f1)},
{::hx::fsInt,(int)offsetof(KHR_debug_obj,MAX_DEBUG_MESSAGE_LENGTH),HX_("MAX_DEBUG_MESSAGE_LENGTH",65,08,17,87)},
{::hx::fsInt,(int)offsetof(KHR_debug_obj,MAX_DEBUG_LOGGED_MESSAGES),HX_("MAX_DEBUG_LOGGED_MESSAGES",e2,62,56,d5)},
{::hx::fsInt,(int)offsetof(KHR_debug_obj,DEBUG_LOGGED_MESSAGES),HX_("DEBUG_LOGGED_MESSAGES",1d,20,32,f8)},
{::hx::fsInt,(int)offsetof(KHR_debug_obj,DEBUG_SEVERITY_HIGH),HX_("DEBUG_SEVERITY_HIGH",18,be,8d,35)},
{::hx::fsInt,(int)offsetof(KHR_debug_obj,DEBUG_SEVERITY_MEDIUM),HX_("DEBUG_SEVERITY_MEDIUM",ab,58,3f,b3)},
{::hx::fsInt,(int)offsetof(KHR_debug_obj,DEBUG_SEVERITY_LOW),HX_("DEBUG_SEVERITY_LOW",7e,fa,43,a3)},
{::hx::fsInt,(int)offsetof(KHR_debug_obj,DEBUG_OUTPUT),HX_("DEBUG_OUTPUT",cd,3e,9f,da)},
{::hx::fsInt,(int)offsetof(KHR_debug_obj,CONTEXT_FLAG_DEBUG_BIT),HX_("CONTEXT_FLAG_DEBUG_BIT",7e,17,c3,b0)},
{::hx::fsInt,(int)offsetof(KHR_debug_obj,STACK_OVERFLOW),HX_("STACK_OVERFLOW",79,a6,54,a5)},
{::hx::fsInt,(int)offsetof(KHR_debug_obj,STACK_UNDERFLOW),HX_("STACK_UNDERFLOW",cf,21,6e,b5)},
{ ::hx::fsUnknown, 0, null()}
};
static ::hx::StaticInfo *KHR_debug_obj_sStaticStorageInfo = 0;
#endif
static ::String KHR_debug_obj_sMemberFields[] = {
HX_("DEBUG_OUTPUT_SYNCHRONOUS",b7,6c,34,b8),
HX_("DEBUG_NEXT_LOGGED_MESSAGE_LENGTH",5b,ea,d6,b8),
HX_("DEBUG_CALLBACK_FUNCTION",c6,df,cb,cf),
HX_("DEBUG_CALLBACK_USER_PARAM",67,50,4b,b2),
HX_("DEBUG_SOURCE_API",a2,9d,a7,fc),
HX_("DEBUG_SOURCE_WINDOW_SYSTEM",c6,f9,dc,4e),
HX_("DEBUG_SOURCE_SHADER_COMPILER",61,d0,c4,2b),
HX_("DEBUG_SOURCE_THIRD_PARTY",f6,6f,06,29),
HX_("DEBUG_SOURCE_APPLICATION",58,24,b6,0f),
HX_("DEBUG_SOURCE_OTHER",d8,3d,44,3e),
HX_("DEBUG_TYPE_ERROR",ef,26,40,e9),
HX_("DEBUG_TYPE_DEPRECATED_BEHAVIOR",a5,cf,17,8c),
HX_("DEBUG_TYPE_UNDEFINED_BEHAVIOR",da,37,6a,74),
HX_("DEBUG_TYPE_PORTABILITY",b0,1e,6b,9d),
HX_("DEBUG_TYPE_PERFORMANCE",57,2c,fb,eb),
HX_("DEBUG_TYPE_OTHER",f7,c1,8c,ac),
HX_("DEBUG_TYPE_MARKER",93,dc,e9,97),
HX_("DEBUG_TYPE_PUSH_GROUP",13,87,6b,ca),
HX_("DEBUG_TYPE_POP_GROUP",58,29,6a,b8),
HX_("DEBUG_SEVERITY_NOTIFICATION",a1,b3,a6,11),
HX_("MAX_DEBUG_GROUP_STACK_DEPTH",a5,1e,fc,f4),
HX_("DEBUG_GROUP_STACK_DEPTH",a0,e0,2d,54),
HX_("BUFFER",00,69,17,83),
HX_("SHADER",25,6b,a3,cf),
HX_("PROGRAM",64,1e,cd,73),
HX_("QUERY",e8,c2,d8,db),
HX_("SAMPLER",e8,98,9d,03),
HX_("MAX_LABEL_LENGTH",0c,59,f0,f1),
HX_("MAX_DEBUG_MESSAGE_LENGTH",65,08,17,87),
HX_("MAX_DEBUG_LOGGED_MESSAGES",e2,62,56,d5),
HX_("DEBUG_LOGGED_MESSAGES",1d,20,32,f8),
HX_("DEBUG_SEVERITY_HIGH",18,be,8d,35),
HX_("DEBUG_SEVERITY_MEDIUM",ab,58,3f,b3),
HX_("DEBUG_SEVERITY_LOW",7e,fa,43,a3),
HX_("DEBUG_OUTPUT",cd,3e,9f,da),
HX_("CONTEXT_FLAG_DEBUG_BIT",7e,17,c3,b0),
HX_("STACK_OVERFLOW",79,a6,54,a5),
HX_("STACK_UNDERFLOW",cf,21,6e,b5),
::String(null()) };
::hx::Class KHR_debug_obj::__mClass;
void KHR_debug_obj::__register()
{
KHR_debug_obj _hx_dummy;
KHR_debug_obj::_hx_vtable = *(void **)&_hx_dummy;
::hx::Static(__mClass) = new ::hx::Class_obj();
__mClass->mName = HX_("lime.graphics.opengl.ext.KHR_debug",87,84,b9,11);
__mClass->mSuper = &super::__SGetClass();
__mClass->mConstructEmpty = &__CreateEmpty;
__mClass->mConstructArgs = &__Create;
__mClass->mGetStaticField = &::hx::Class_obj::GetNoStaticField;
__mClass->mSetStaticField = &::hx::Class_obj::SetNoStaticField;
__mClass->mStatics = ::hx::Class_obj::dupFunctions(0 /* sStaticFields */);
__mClass->mMembers = ::hx::Class_obj::dupFunctions(KHR_debug_obj_sMemberFields);
__mClass->mCanCast = ::hx::TCanCast< KHR_debug_obj >;
#ifdef HXCPP_SCRIPTABLE
__mClass->mMemberStorageInfo = KHR_debug_obj_sMemberStorageInfo;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mStaticStorageInfo = KHR_debug_obj_sStaticStorageInfo;
#endif
::hx::_hx_RegisterClass(__mClass->mName, __mClass);
}
} // end namespace lime
} // end namespace graphics
} // end namespace opengl
} // end namespace ext
|
d89c4c921eafc4657484d01d67552f137751d254 | 1dc745955b069813e7cc11ef614dda8acdff4787 | /CodechefMayLong/Covid19.cpp | aff5fd59974dfc1c5fec49c62bcf04ef38568197 | [] | no_license | PiyushRajmsit/Coding-Competitions-Solutions | 7a00b38344d2ef018f72781578cf9a0ba84478fc | ebd61cd90d6f44db6f60cbd701df102fc60705df | refs/heads/master | 2022-09-25T18:50:24.179655 | 2020-06-06T12:46:35 | 2020-06-06T12:46:35 | 269,978,812 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 663 | cpp | Covid19.cpp | #include<bits/stdc++.h>
using namespace std;
#define ll long long
#define mod 1000000007
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t;
cin>>t;
int n;
int *arr = new int[100];
while(t--)
{
cin>>n;
for(int i=0;i<n;i++)
cin>>arr[i];
sort(arr,arr+n);
int high = 0;
int low = n+1;
int last = arr[0];
int curr = 0;
for(int i=0;i<n;i++)
{
if(arr[i] - last <= 2 )
curr++;
else{
low = min(low,curr);
curr = 1;
}
last = arr[i];
high = max(high,curr);
}
low = min(low,curr);
if(high == n)
low = high;
cout<<low<<" "<<high<<endl;
}
delete[] arr;
return 0;
}
|
0673672fe7d7f49492a3bc63225074673a3357ba | 4121fb55110bd4329cf27cfb897f9b7855b8f596 | /src/server/net/net_server.cpp | 04dc1b5e338fbd9e530b4c181a53a7321188ac4b | [] | no_license | starand/notifier | 28c1baf9a98cf8479942bbb76dfc146d0f871348 | e42f1f132d7a2cd0cf65e1305e1979cbf6baecf2 | refs/heads/master | 2021-01-13T16:19:23.306765 | 2017-01-31T11:27:59 | 2017-01-31T11:27:59 | 80,013,776 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,966 | cpp | net_server.cpp | #include <common/StdAfx.h>
#include <common/config.h>
#include <net/client_handler.h>
#include <net/net_server.h>
#include <common/asserts.h>
#include <net/xsocket.h>
#include <json/value.h>
//--------------------------------------------------------------------------------------------------
net_server_t::net_server_t( const config_t& config, client_handler_t& handler )
: m_socket( new socket_t( ) )
, m_config( config )
, m_handler( handler )
{
ASSERT( m_socket.get( ) != nullptr );
}
//--------------------------------------------------------------------------------------------------
net_server_t::~net_server_t( )
{
}
//--------------------------------------------------------------------------------------------------
bool net_server_t::init( )
{
auto password_node = m_config[ "net" ][ "password" ];
if ( password_node.isNull( ) )
{
LOG_ERROR( "net::password node not set" );
return false;
}
auto port_node = m_config[ "net" ][ "port" ];
if ( port_node.isNull( ) )
{
LOG_ERROR( "net::port node not set" );
return false;
}
ushort port = static_cast< ushort >( port_node.asUInt( ) );
LOG_INFO( "Listen on %u port", port );
return m_socket->listen( port );
}
//--------------------------------------------------------------------------------------------------
void net_server_t::do_run( )
{
if ( !init( ) )
{
return;
}
while ( true )
{
std::unique_ptr< socket_t > client( m_socket->accept( ) );
if ( is_stopping( ) )
{
break;
}
m_handler.process_client( *client );
}
}
//--------------------------------------------------------------------------------------------------
void net_server_t::do_stop( )
{
m_socket->shutdown( SD_BOTH );
m_socket->close( );
}
//--------------------------------------------------------------------------------------------------
|
6c8818f149cdb5d5772803d6917965edfe937049 | af6e37f97fb64d1b124a69245d19eb75153ba8f3 | /DirectX11_Starter/Mesh.h | 811da50dda10255a04b62560df1926b5403d059a | [] | no_license | Eniripsa96/EnginesClass | 52ea862722c6c227d62091ff38a4452f4286c62c | 9d47ad943257c7d38581cc7743c68379e1c6243b | refs/heads/master | 2021-01-19T07:47:02.895872 | 2015-05-19T13:35:47 | 2015-05-19T13:35:47 | 31,019,155 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,852 | h | Mesh.h | #ifndef MESH_H
#define MESH_H
#include <vector>
#include <time.h>
#include "Material.h"
using namespace std;
using namespace DirectX;
enum SHAPE
{
NONE = 0,
TRIANGLE = 1,
QUAD = 2,
PARTICLE = 50
};
// Vertex struct for triangles
struct Vertex
{
XMFLOAT3 Position;
XMFLOAT3 Normal;
XMFLOAT2 UV;
};
// Vertex struct for particles
struct Particle
{
XMFLOAT3 initialPos;
XMFLOAT3 initialVel;
XMFLOAT2 size;
XMFLOAT3 color;
};
// Struct to match vertex shader's constant buffer
// You update one of these locally, then push it to the corresponding
// constant buffer on the device when it needs to be updated
struct VertexShaderConstantBufferLayout
{
XMFLOAT4X4 world;
XMFLOAT4X4 view;
XMFLOAT4X4 projection;
XMFLOAT4X4 lightView;
XMFLOAT4X4 lightProjection;
XMFLOAT4 lightDirection;
XMFLOAT4 color;
XMFLOAT4 camPos;
};
// Struct to match particle geometry shader's constant buffer
// Update locally then push to corresponding buffer
struct GeometryShaderConstantBufferLayout
{
XMFLOAT4X4 world;
XMFLOAT4X4 view;
XMFLOAT4X4 projection;
XMFLOAT4 camPos;
XMFLOAT4 spawnPos;
XMFLOAT4 misc;
};
class Mesh
{
public:
Mesh(ID3D11Device*, ID3D11DeviceContext*, SHAPE);
Mesh(ID3D11Device*, ID3D11DeviceContext*, ID3D11Buffer*, ID3D11Buffer*, UINT);
virtual ~Mesh();
void CreateTrianglePoints();
void CreateQuadPoints();
virtual void CreateGeometryBuffers(Vertex[]);
virtual void Draw();
// Buffers to hold actual geometry
ID3D11Buffer* drawVB;
ID3D11Buffer* indexBuffer;
SHAPE shapeType;
const XMFLOAT4 RED = XMFLOAT4(1.0f, 0.0f, 0.0f, 1.0f);
const XMFLOAT4 GREEN = XMFLOAT4(0.0f, 1.0f, 0.0f, 1.0f);
const XMFLOAT4 BLUE = XMFLOAT4(0.0f, 0.0f, 1.0f, 1.0f);
const XMFLOAT3 NORMALS_2D = XMFLOAT3(0.0f, 0.0f, 1.0f);
ID3D11Device* device;
ID3D11DeviceContext* deviceContext;
private:
UINT iBufferSize;
};
#endif |
0acd9c1aa7337c44e1510472beae2211eb658093 | 39fef4617567a908ac096fa7445c51ec2e72d08c | /Arduino/ArduHaaga/ArduHaaga.ino | 0b4da4eb49d47f730c8b8324f7e40634e7b0c3e4 | [] | no_license | HukoOo/HaagaRobot | db8545f612a4f71ee2b49d619fa35c1b9064e656 | b72f35f24f319cea97d4cf58c0995264a50ccd26 | refs/heads/master | 2020-05-22T04:04:04.853669 | 2017-01-05T16:35:26 | 2017-01-05T16:35:26 | 57,010,865 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 24,471 | ino | ArduHaaga.ino | #include <SoftwareSerial.h>
#include <TinyGPS.h>
#include <Wire.h>
#include <HMC5883L.h>
// ROS
#include <ros.h>
#include <std_msgs/String.h>
#include <rosserial_arduino/Test.h>
//pin settings
#define EN1 4 // ENABLE pin motor1
#define PWM1 5 // PWM pin motor1
#define EN2 6 // ENABLE pin motor2
#define PWM2 7 // PWM pin motor2
#define encodePinA1 18 // encoder1 A pin int4
#define encodePinB1 19 // encoder1 B pin int5
#define encodePinA2 3 // encoder2 A pin int1
#define encodePinB2 2 // encoder2 B pin int0
#define GPSTX 10
#define GPSRX 11
#define GYROSDA 20
#define GYROSCL 21
// for PID controll
#define Gearratio1 12 //motor1 gear ratio
#define Encoderpulse1 48*4 //motor1 encoder pulse
#define Gearratio2 12 //motor2 gear ratio
#define Encoderpulse2 48*4 //motor2 encoder pulse
#define LOOPTIME 50 // PID loop time
#define NUMREADINGS 10 // samples for Amp average
#define LOOPTIMEVEL 10
#define LOOPTIMEGPS 2000 //GPS refresh time
#define pi 3.141592
int motor1_rpm_cmd = 0;
int motor2_rpm_cmd = 0;
unsigned long lastMilli = 0; // loop timing
unsigned long lastMillimonitor = 0;
unsigned long lastMilliPrint = 0;
unsigned long dtMilli = 0; // Communication period
unsigned long dtMillimonitor = 50;
unsigned long dtMillispeed = 0;
unsigned long lastMillispeed = 0;
float speed_term = 5.0; //RPM
float accel = 2.5;
float speed_req1 = 0; // motor1 speed (Set Point)
float speed_profile1 = 0;
float speed_act1 = 0; // motor1 speed (actual value)
float speed_act1_rad = 0;
float speed_act1_rpm = 0;
float speed_act1_rps = 0;
float speed_act1_filtered = 0;
float speed_req2 = 0; // motor1 speed (Set Point)
float speed_profile2 = 0;
float speed_act2 = 0; // motor1 speed (actual value)
float speed_act2_rad = 0;
float speed_act2_rpm = 0;
float speed_act2_rps = 0;
float speed_act2_filtered = 0;
int PWM_val1 = 0; // motor1 PWM (25% = 64; 50% = 127; 75% = 191; 100% = 255)
int PWM_val1_prev = 0;
int PWM_val1_desired = 0;
int PWM_val2 = 0; // motor2 PWM (25% = 64; 50% = 127; 75% = 191; 100% = 255)
int PWM_val2_prev = 0;
int PWM_val2_desired = 0;
int voltage = 0; // in mV
int current1 = 0; // motor 1 current in mA
int current2 = 0; // motor 2 current in mA
volatile long count1 = 0; // motor 1 rev counter
volatile long count2 = 0; // motor 2 rev counter
long inc_enc_pos1 = 0;
long inc_enc_pos2 = 0;
float abs_enc_pos1 = 0;
float abs_enc_pos2 = 0;
int Precount1[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; // motor 1 last count
int Precount2[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; // motor 2 last count
long newpre1 = 0;
long newpre2 = 0;
float Kp1 = 0.57; // motor1 PID proportional control Gain
float Ki1 = 2.77; // motor1 PID Integral control Gain
float Kd1 = 0.88; // motor1 PID Derivitave control Gain
float Ka1 = 3.25;
float Kp2 = 0.57; // motor2 PID proportional control Gain
float Ki2 = 2.77;// 7.5; // motor2 PID Derivitave control Gain
float Kd2 = 0.88;//4.05; // motor2 PID Integral control Gain
float Ka2 = 3.25;//0.2;
float controll_inc = 1;
float controll_inc_i = 0.01;
float pid_i1 = .0;
float pid_d1 = .0;
float pid_a1 = 0;
float pidTerm_err1 = 0;
float pid_i2 = .0;
float pid_d2 = .0;
float pid_a2 = 0;
float pidTerm_err2 = 0;
int lastspeed1 = 0;
int lastspeed2 = 0;
int manual = 0;
float beta = 1.0;
float error1 = 0.0;
float error2 = 0.0;
float last_error1 = 0;
float last_error2 = 0;
float pwm_prev1 = 0;
float pwm_prev2 = 0;
float enc_prev1 = 0;
float enc_prev2 = 0;
String inputString = "";
int stringComplete = 0;
//for GPS data
SoftwareSerial mySerial(GPSTX, GPSRX); // TX, RX //GPS functions
TinyGPS gps;
int gpsdata = 0;
float flat, flon;
unsigned long lastMilliGPS = 0; // loop timing
unsigned long dtMilliGPS = 0;
uint8_t gps_config_change[63] = {
0xB5, 0x62, 0x06, 0x08, 0x06, 0x00, 0xFA, 0x00, 0x01, 0x00, 0x01, 0x00,
0x10, 0x96,
//Baud change
0xB5, 0x62, 0x06, 0x00, 0x14, 0x00, 0x01, 0x00, 0x00, 0x00, 0xD0, 0x08,
0x00, 0x00, 0x00, 0xC2, 0x01, 0x00, 0x07, 0x00, 0x02, 0x00, 0x00, 0x00,
0x00, 0x00, 0xBF, 0x78,
//Save config
0xB5, 0x62, 0x06, 0x09, 0x0D, 0x00, 0x00, 0x00,
0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x1D, 0xAB
};
void gpsdump(TinyGPS &gps);
void printFloat(double f, int digits = 2);
//for GYRO data
HMC5883L compass;
int compassdata = 0;
float headingDegrees = 0.0;
//ROS
ros::NodeHandle nh;
using rosserial_arduino::Test;
std_msgs::String status_msg;
ros::Publisher chatter("motor_status", &status_msg); // arduino -> ros
void callback(const Test::Request & req, Test::Response & res)
{
inputString = req.input; // ros -> arduino
res.output = req.input;
stringComplete = true;
}
ros::ServiceServer<Test::Request, Test::Response> server("motor_cmd", &callback);
char message[256] = "";
char tempBuffer[256];
void setup()
{
analogReference(DEFAULT); //Reference 5V (Mega condition)
Serial.begin(57600); // Monitoring & command port
//mySerial.begin(57600);
// set the data rate for the SoftwareSerial port
mySerial.begin(9600); // Set GPS baudrate 115200 from 9600
mySerial.write(gps_config_change, sizeof(gps_config_change));
mySerial.end();
mySerial.begin(115200);
pinMode(EN1, OUTPUT); //OUTPUT Pinmodes
pinMode(EN2, OUTPUT);
pinMode(PWM1, OUTPUT);
pinMode(PWM2, OUTPUT);
pinMode(encodePinA1, INPUT); //Encoder Pinmodes
pinMode(encodePinB1, INPUT);
pinMode(encodePinA2, INPUT);
pinMode(encodePinB2, INPUT);
digitalWrite(encodePinA1, HIGH); // turn on Endocer pin pullup resistor
digitalWrite(encodePinB1, HIGH);
digitalWrite(encodePinA2, HIGH);
digitalWrite(encodePinB2, HIGH);
attachInterrupt(5, rencoder1, CHANGE); //Encoder pin interrupt setting
attachInterrupt(4, rencoder1, CHANGE);
attachInterrupt(1, rencoder2, CHANGE);
attachInterrupt(0, rencoder2, CHANGE);
analogWrite(PWM1, PWM_val1);
analogWrite(PWM2, PWM_val2);
digitalWrite(EN1, LOW);
digitalWrite(EN2, LOW);
if (compass.begin())
{
compassdata = 1;
compass.setRange(HMC5883L_RANGE_1_3GA); // Set measurement range
compass.setMeasurementMode(HMC5883L_CONTINOUS); // Set measurement mode
compass.setDataRate(HMC5883L_DATARATE_30HZ); // Set data rate
compass.setSamples(HMC5883L_SAMPLES_8); // Set number of samples averaged
compass.setOffset(0, 0); // Set calibration offset. See HMC5883L_calibration.ino
}
else
compassdata = 0;
nh.initNode();
nh.advertise(chatter);
nh.advertiseService(server);
}
// LPF filter setup
float LPFVAR = 0.08;
float lpFilter(float value, float prev_value, float beta)
{
float lpf = 0;
lpf = (beta * value) + (1 - beta) * prev_value;
return lpf;
}
// Kalman filter setup
float Pk = 1.0;
float varP = pow(0.01, 2); // pow(0.01, 2)
float R = pow(0.5, 2);
float Kk = 1.0;
float Xk = 20.0;
float kalmanFilter(float value)
{
Pk = Pk + varP;
Kk = Pk / (Pk + R);
Xk = (Kk * value) + (1 - Kk) * Xk;
Pk = (1 - Kk) * Pk;
return Xk;
}
int term = 0;
void loop()
{
Vector norm = compass.readNormalize();
checkEvent();
dtMilli = millis() - lastMilli; // calculate dt
dtMillispeed = millis() - lastMillispeed;
dtMilliGPS = millis() - lastMilliGPS;
// check command
if (stringComplete)
{
calculateRPM(inputString);
inputString = "";
stringComplete = 0;
if ( motor1_rpm_cmd > 320)
speed_req1 = 320;
else if ( motor1_rpm_cmd < -320)
speed_req1 = -320;
else
speed_req1 = motor1_rpm_cmd;
if ( motor2_rpm_cmd > 320)
speed_req2 = 320;
else if ( motor2_rpm_cmd < -320)
speed_req2 = -320;
else
speed_req2 = motor2_rpm_cmd;
}
if (dtMillispeed >= LOOPTIMEVEL)
{
speedcalculation(dtMillispeed); // calculate speed, volts and Amps
speed_act1_filtered = lpFilter(speed_act1_rpm, enc_prev1, LPFVAR);
enc_prev1 = speed_act1_filtered;
newpre1 = count1;
speed_act2_filtered = lpFilter(speed_act2_rpm, enc_prev2, LPFVAR);
enc_prev2 = speed_act2_filtered;
newpre2 = count2;
lastMillispeed = millis();
}
if (dtMilli >= LOOPTIME) // time loop check, soft real time
{
buildVelProfile(speed_req1, speed_act1_filtered, &speed_profile1);
buildVelProfile(speed_req2, speed_act2_filtered, &speed_profile2);
PWM_val1 = updatePid1(speed_profile1, speed_act1_filtered, dtMilli, Kp1, Ki1, Kd1);
PWM_val2 = updatePid2(speed_profile2, speed_act2_filtered, dtMilli, Kp2, Ki2, Kd2); // Motor 2 PWM calculation
if (PWM_val1 > 0)
{
digitalWrite(EN1, HIGH);
}
else
{
digitalWrite(EN1, LOW);
}
if (PWM_val2 < 0)
{
digitalWrite(EN2, HIGH);
}
else
{
digitalWrite(EN2, LOW);
}
if (speed_req1 == 0 && abs(error1) == 0)
PWM_val1 = 0;
if (speed_req2 == 0 && abs(error2) == 0)
PWM_val2 = 0;
analogWrite(PWM1, abs(PWM_val1)); // send PWM to motor
analogWrite(PWM2, abs(PWM_val2)); // send PWM to motor
// if (manual == 0)
// printMotorInfo();
// else if (manual == 1)
// {
//
// }
//printMotorInfo();
//countpush(Precount1,count1,Precount1);
//countpush(Precount2,count2,Precount2);
lastMilli = millis();
}
// GPS update
bool newdata = false;
unsigned long start = millis();
while (millis() - start < 10) {
if (Serial3.available())
{
char c = Serial3.read();
//Serial.print(c); // uncomment to see raw GPS data
if (gps.encode(c))
{
newdata = true;
gpsdata = 1;
// break; // uncomment to print new data immediately!
}
}
}
if (newdata)
{
gpsdump(gps);
}
else
gpsdata = 0;
//Calculate heading
float heading = atan2(norm.YAxis, norm.XAxis);
float declinationAngle = (11.0 + (49.0 / 60.0)) / (180 / M_PI);
// Formula: (deg + (min / 60.0)) / (180 / M_PI);
heading += declinationAngle;
// Correct for heading < 0deg and heading > 360deg
if (heading < 0)
{
heading += 2 * PI;
}
if (heading > 2 * PI)
{
heading -= 2 * PI;
}
headingDegrees = heading * 180 / M_PI; // Convert to degrees
publishStatus();
nh.spinOnce();
}
// Publish message to ROS
void publishStatus()
{
if ((millis() - lastMilliPrint) >= dtMillimonitor)
{
lastMilliPrint = millis();
dtostrf(speed_act1_filtered , 4, 0, tempBuffer);
strcat(message, tempBuffer); strcat(message, ",");
dtostrf(speed_act2_filtered , 4, 0, tempBuffer);
strcat(message, tempBuffer); strcat(message, ",");
dtostrf(count1 , 10, 0, tempBuffer);
strcat(message, tempBuffer); strcat(message, ",");
dtostrf(count2 , 10, 0, tempBuffer);
strcat(message, tempBuffer); strcat(message, ",");
dtostrf(gpsdata , 1, 0, tempBuffer);
strcat(message, tempBuffer); strcat(message, ",");
dtostrf(flat , 5, 5, tempBuffer);
strcat(message, tempBuffer); strcat(message, ",");
dtostrf(flon , 5, 5, tempBuffer);
strcat(message, tempBuffer); strcat(message, ",");
dtostrf(headingDegrees , 5, 2, tempBuffer);
strcat(message, tempBuffer); strcat(message, ",");
status_msg.data = message;
chatter.publish( &status_msg );
message[0] = '\0';
}
}
void speedcalculation(unsigned long dt) // calculate speed, volts and Amps
{
//speed_act1 = (((float)count1 - (float)newpre1) * 1000) / dt / (Encoderpulse1) / Gearratio1 *3.141592*2; // ((count difference) / (dt) / 1000) / (pulses * gear ratio) * 2* 3.141592 = rad/sec
//speed_act2 = (((float)count2 - (float)newpre2) * 1000) / dt / (Encoderpulse2) / Gearratio2 *3.141592*2; // ((count difference) / (dt) / 1000) / (pulses * gear ratio) * 2* 3.141592 = rad/sec
speed_act1_rps = (((float)count1 - (float)newpre1) * 1000) / dt / (Encoderpulse1) / Gearratio1 ;
speed_act1_rpm = (((float)count1 - (float)newpre1) * 1000) / dt / (Encoderpulse1) / Gearratio1 * 60;
speed_act1_rad = (((float)count1 - (float)newpre1) * 1000) / dt / (Encoderpulse1) / Gearratio1 * 3.141592 * 2;
inc_enc_pos1 = count1 / ((float)Encoderpulse1 * (float)Gearratio1) * 360.0;
speed_act1 = speed_act1_rpm;
speed_act2_rps = (((float)count2 - (float)newpre2) * 1000) / dt / (Encoderpulse2) / Gearratio2 ;
speed_act2_rpm = (((float)count2 - (float)newpre2) * 1000) / dt / (Encoderpulse2) / Gearratio2 * 60;
speed_act2_rad = (((float)count2 - (float)newpre2) * 1000) / dt / (Encoderpulse2) / Gearratio2 * 3.141592 * 2;
speed_act2 = speed_act2_rpm;
inc_enc_pos2 = count2 / ((float)Encoderpulse2 * (float)Gearratio2) * 360.0;
}
void buildVelProfile(float desired_vel, float current_vel, float *speed_profile)
{
float accel = 5.0;
float vel_diff = desired_vel - current_vel;
float time_interval = 100; //ms
if (abs(desired_vel - *speed_profile) < 10)
accel = abs(desired_vel - *speed_profile);
if (desired_vel > *speed_profile)
*speed_profile = *speed_profile + accel;
else if (desired_vel < *speed_profile)
*speed_profile = *speed_profile - accel;
}
float updatePid1( float targetValue, float currentValue, unsigned long dt, float Kp, float Ki, float Kd) // compute PWM value
{
float pidTerm = 0; // PID correction
float pidTerm_sat = 0;
//float error=0; // error initiallization
//static float last_error=0; // For D control, static last_error
error1 = targetValue - currentValue; // error calculation
pid_a1 = pidTerm_err1 * Ka1;
pid_i1 = pid_i1 + (error1 + pid_a1) * dt / 1000; // Error Integral
pid_d1 = (error1 - last_error1) ;
pidTerm = (Kp * error1) + Ki * pid_i1 + (Kd * (pid_d1));
last_error1 = error1; //for D control
if (pidTerm > 250)
pidTerm_sat = 250;
else if (pidTerm < -250)
pidTerm_sat = -250;
else
pidTerm_sat = pidTerm;
pidTerm_err1 = pidTerm_sat - pidTerm;
return pidTerm_sat;
}
float updatePid2( float targetValue, float currentValue, unsigned long dt, float Kp, float Ki, float Kd) // compute PWM value
{
float pidTerm = 0; // PID correction
float pidTerm_sat = 0;
//float error=0; // error initiallization
//static float last_error=0; // For D control, static last_error
error2 = targetValue - currentValue; // error calculation
pid_a1 = pidTerm_err2 * Ka2;
pid_i2 = pid_i2 + (error2 + pid_a1) * dt / 1000; // Error Integral
pid_d2 = (error2 - last_error2);
pidTerm = (Kp * error2) + Ki * pid_i2 + (Kd * (pid_d2)) ;
last_error2 = error2; //for D control
if (pidTerm > 250)
pidTerm_sat = 250;
else if (pidTerm < -250)
pidTerm_sat = -250;
else
pidTerm_sat = pidTerm;
pidTerm_err2 = pidTerm_sat - pidTerm;
return pidTerm_sat;
}
/*
void printMotorInfo() // display data
{
if ((millis() - lastMilliPrint) >= dtMillimonitor) {
lastMilliPrint = millis();
Serial.print(speed_act1_rpm); Serial.print(",");
Serial.print(speed_act1_filtered); Serial.print(",");
Serial.print(speed_req1); Serial.print(",");
Serial.print(PWM_val1); Serial.print(",");
Serial.print(count1); Serial.print(",");
Serial.print(error1); Serial.print(",");
Serial.print(pid_i1); Serial.print(",");
Serial.print(pid_d1); Serial.print(",");
Serial.print(Kp1); Serial.print(",");
Serial.print(Ki1); Serial.print(",");
Serial.print(Kd1); Serial.print(",");
Serial.print(Ka1); Serial.print(",");
Serial.print(inc_enc_pos1); Serial.print(",");
Serial.print(speed_profile1); Serial.print(",");
Serial.print(speed_act2_rpm); Serial.print(",");
Serial.print(speed_act2_filtered); Serial.print(",");
Serial.print(speed_req2); Serial.print(",");
Serial.print(PWM_val2); Serial.print(",");
Serial.print(count2); Serial.print(",");
Serial.print(error2); Serial.print(",");
Serial.print(pid_i2); Serial.print(",");
Serial.print(pid_d2); Serial.print(",");
Serial.print(Kp2); Serial.print(",");
Serial.print(Ki2); Serial.print(",");
Serial.print(Kd2); Serial.print(",");
Serial.print(Ka2); Serial.print(",");
Serial.print(inc_enc_pos2); Serial.print(",");
Serial.print(speed_profile2); Serial.print(",");
Serial.print(LPFVAR); Serial.print(",");
Serial.print(gpsdata); Serial.print(",");
printFloat(flat, 6); Serial.print(","); //Serial.print(flat); Serial.print(",");
printFloat(flon, 6); Serial.print(","); //Serial.print(flon); Serial.print(",");
Serial.print(compassdata); Serial.print(",");
Serial.print(headingDegrees); Serial.print(",");
Serial.print(stringComplete); Serial.print(",");
Serial.print("\n");
}
}
*/
//countpush for speed calculation
int countpush(int stack[10], int item, int tempstack[10])
{
for (int i = 0; i < 9 ; i++)
{
tempstack[i] = stack[i + 1];
}
tempstack[9] = item;
}
void calculateRPM(String command)
{
char charInput[255];
String motor1_cmd, motor2_cmd;
String motor1_distance;
int pos_R, pos_L, pos_E, pos_D;
sprintf(charInput, "%s", command.c_str());
if (strchr(charInput, 'b') - charInput == 0)
{
if (strchr(charInput, '+') - charInput == 1)
{
LPFVAR = LPFVAR + 0.001;
}
else if (strchr(charInput, '-') - charInput == 1)
{
LPFVAR = LPFVAR - 0.001;
}
}
else if (strchr(charInput, 'p') - charInput == 0)
{
if (strchr(charInput, '+') - charInput == 1)
{
Kp1 = Kp1 + controll_inc_i;
}
else if (strchr(charInput, '-') - charInput == 1)
{
Kp1 = Kp1 - controll_inc_i;
}
}
else if (strchr(charInput, 'o') - charInput == 0)
{
if (strchr(charInput, '+') - charInput == 1)
{
Ki1 += controll_inc_i;
}
else if (strchr(charInput, '-') - charInput == 1)
{
Ki1 -= controll_inc_i;
}
}
else if (strchr(charInput, 'i') - charInput == 0)
{
if (strchr(charInput, '+') - charInput == 1)
{
Kd1 += controll_inc_i;
}
else if (strchr(charInput, '-') - charInput == 1)
{
Kd1 -= controll_inc_i;
}
}
else if (strchr(charInput, 'l') - charInput == 0)
{
if (strchr(charInput, '+') - charInput == 1)
{
Kp2 += controll_inc_i;
}
else if (strchr(charInput, '-') - charInput == 1)
{
Kp2 -= controll_inc_i;
}
}
else if (strchr(charInput, 'k') - charInput == 0)
{
if (strchr(charInput, '+') - charInput == 1)
{
Ki2 += controll_inc_i;
}
else if (strchr(charInput, '-') - charInput == 1)
{
Ki2 -= controll_inc_i;
}
}
else if (strchr(charInput, 'j') - charInput == 0)
{
if (strchr(charInput, '+') - charInput == 1)
{
Kd2 += controll_inc_i;
}
else if (strchr(charInput, '-') - charInput == 1)
{
Kd2 -= controll_inc_i;
}
}
else if (strchr(charInput, 'u') - charInput == 0)
{
if (strchr(charInput, '+') - charInput == 1)
{
Ka1 += controll_inc_i;
}
else if (strchr(charInput, '-') - charInput == 1)
{
Ka1 -= controll_inc_i;
}
}
else if (strchr(charInput, 'h') - charInput == 0)
{
if (strchr(charInput, '+') - charInput == 1)
{
Ka2 += controll_inc_i;
}
else if (strchr(charInput, '-') - charInput == 1)
{
Ka2 -= controll_inc_i;
}
}
else if (strchr(charInput, 'w') - charInput == 0)
{
if (strchr(charInput, '+') - charInput == 1)
{
motor1_rpm_cmd += speed_term;
motor2_rpm_cmd += speed_term;
}
}
else if (strchr(charInput, 's') - charInput == 0)
{
if (strchr(charInput, '-') - charInput == 1)
{
motor1_rpm_cmd -= speed_term;
motor2_rpm_cmd -= speed_term;
}
}
else if (strchr(charInput, 'm') - charInput == 0)
{
if (strchr(charInput, '*') - charInput == 1)
{
PWM_val1 = 0;
speed_req1 = 0;
PWM_val2 = 0;
speed_req2 = 0;
error1 = 0;
error2 = 0;
Kp1 = 0; Ki1 = 0; Kd1 = 0;
Kp2 = 0; Ki2 = 0; Kd2 = 0;
}
else if (strchr(charInput, '+') - charInput == 1)
{
inc_enc_pos1 = 0;
}
}
else if (strchr(charInput, 'M') - charInput == 0)
{
if (strchr(charInput, '+') - charInput == 1) //Set bluetooth
{
manual = 1;
}
else if (strchr(charInput, '-') - charInput == 1) //Set automatic
{
manual = 0;
}
}
else
{
pos_R = (strchr(charInput, 'R') - charInput);
pos_L = (strchr(charInput, 'L') - charInput);
pos_E = (strchr(charInput, 'E') - charInput);
for (int i = pos_R + 1; i < pos_L; i++)
{
motor1_cmd += charInput[i];
}
for (int i = pos_L + 1; i < pos_E; i++)
{
motor2_cmd += charInput[i];
}
motor1_rpm_cmd = atoi(motor1_cmd.c_str());
motor2_rpm_cmd = atoi(motor2_cmd.c_str());
}
}
void checkEvent() {
while (Serial.available())
{
char inChar = (char)Serial.read();
inputString += inChar;
if (inChar == 'E')
{
stringComplete = 1;
if (manual == 1)
Serial.print(inputString);
}
}
}
void gpsdump(TinyGPS & gps)
{
long lat, lon;
// float flat, flon;
unsigned long age, date, time, chars;
int year;
byte month, day, hour, minute, second, hundredths;
unsigned short sentences, failed;
gps.f_get_position(&flat, &flon, &age);
}
//count from quad encoder
void rencoder1() // pulse and direction, direct port reading to save cycles
{
static long oldencodePinB1 = 0;
if (digitalRead(encodePinA1) ^ oldencodePinB1)
{
count1++;
}
else
{
count1--;
}
oldencodePinB1 = digitalRead(encodePinB1);
}
void rencoder2() // pulse and direction, direct port reading to save cycles
{
static long oldencodePinB2 = 0;
if (digitalRead(encodePinA2) ^ oldencodePinB2)
{
count2++;
}
else
{
count2--;
}
oldencodePinB2 = digitalRead(encodePinB2);
}
void printFloat(double number, int digits)
{
// Handle negative numbers
if (number < 0.0) {
Serial.print('-');
number = -number;
}
// Round correctly so that print(1.999, 2) prints as "2.00"
double rounding = 0.5;
for (uint8_t i = 0; i < digits; ++i)
rounding /= 10.0;
number += rounding;
// Extract the integer part of the number and print it
unsigned long int_part = (unsigned long)number;
double remainder = number - (double)int_part;
Serial.print(int_part);
// Print the decimal point, but only if there are digits beyond
if (digits > 0)
Serial.print(".");
// Extract digits from the remainder one at a time
while (digits-- > 0) {
remainder *= 10.0;
int toPrint = int(remainder);
Serial.print(toPrint);
remainder -= toPrint;
}
}
|
9648d842d7c9cb1aedaaab12803ba9919dd89321 | 3009edfc1058865cd3873f6791503137d238dbfc | /结果/第五次在线测评结果/source/1614/circle.cpp | accbb9d72160626179976d6820e8d14705481c8f | [] | no_license | Ynjxsjmh/DataStructureAssignment | 1477faf125aea02f5ac01b504a712127fe0b7bc4 | 92a4964c73fbcadd320d9cbfbd522204a6b32be8 | refs/heads/master | 2020-04-16T23:31:46.021240 | 2019-01-16T09:47:44 | 2019-01-16T09:47:44 | 166,014,833 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,457 | cpp | circle.cpp | #include <stdio.h>
#include <stdlib.h>
struct queue{
int front, rear, num, el[7000];
queue(){front = 0; rear = 0; num = 0;}
void in(int e){el[front++] = e; num++; return;}
int out(void){num--; return el[rear++];}
};
struct circle{
int x, y, r;
};
struct plane{
int num; circle* ci; int now, *visit;
} p;
void getdata(void){
FILE *in = fopen("circle.in", "r");
fscanf(in, "%d", &p.num);
p.ci = (circle*)malloc(sizeof(circle) * p.num);
p.now = 0; p.visit = (int*)malloc(sizeof(int) * p.num);
for (int i = 0; i < p.num; i++){
fscanf(in, "%d%d%d", &p.ci[i].x, &p.ci[i].y, &p.ci[i].r);
p.visit[i] = 0;
}
fclose(in); return;
}
int check(int i, int k){
if ((p.ci[i].x - p.ci[k].x) * (p.ci[i].x - p.ci[k].x) + (p.ci[i].y - p.ci[k].y) * (p.ci[i].y - p.ci[k].y) <= (p.ci[i].r + p.ci[k].r) * (p.ci[i].r + p.ci[k].r)) return 1;
return 0;
}
int checkb(int blockn){
int i;
for (i = p.now; p.visit[i] == 1 && i < p.num; i++);
if (i == p.num) return 0 - blockn;
queue q; q.in(i); p.visit[i] = 1;
p.now = i + 1;
while (q.num){
int k = q.out();
for (i = p.now; i < p.num; i++)
if (p.visit[i] == 0 && check(i, k) == 1)
{q.in(i); p.visit[i] = 1;}
}
return blockn - 1;
}
void outputdata(int n){
FILE *out = fopen("circle.out", "w");
fprintf(out, "%d", n);
fclose(out); return;
}
int main()
{
getdata();
int blockn = 0;
while (blockn <= 0){blockn = checkb(blockn);}
free(p.ci); free(p.visit);
outputdata(blockn);
return 0;
}
|
f3a14539ec2948324a4432f2ccfc45f44c188613 | 8c7ad5ba8506455d817ea63b4f77022d4d41e655 | /lab2/xorcypherbreaker/main.cpp | 41c9a8b00215e1fd65cd93ed69ecb9361589930d | [] | no_license | michaljasica/JiMP-II | b880faeaa0265a3c72d6935d3fbcc850637aeacf | c6d242c1005818d456c295a1c78c88c46ce8e5b7 | refs/heads/master | 2021-01-25T13:36:16.614926 | 2018-06-05T22:13:01 | 2018-06-05T22:13:01 | 123,595,171 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 84 | cpp | main.cpp | //
// Created by malikmontana on 11.03.18.
//
int main(){
return 0;
} |
eebe083fcaa20d07a6d7c29b5cdf8427cafe5091 | 814fd0bea5bc063a4e34ebdd0a5597c9ff67532b | /components/timers/alarm_timer.h | d2f93335d61c518c4516b523b94058df949a1577 | [
"BSD-3-Clause"
] | permissive | rzr/chromium-crosswalk | 1b22208ff556d69c009ad292bc17dca3fe15c493 | d391344809adf7b4f39764ac0e15c378169b805f | refs/heads/master | 2021-01-21T09:11:07.316526 | 2015-02-16T11:52:21 | 2015-02-16T11:52:21 | 38,887,985 | 0 | 0 | NOASSERTION | 2019-08-07T21:59:20 | 2015-07-10T15:35:50 | C++ | UTF-8 | C++ | false | false | 3,626 | h | alarm_timer.h | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef COMPONENTS_TIMER_ALARM_TIMER_H_
#define COMPONENTS_TIMER_ALARM_TIMER_H_
#include "base/callback.h"
#include "base/macros.h"
#include "base/memory/ref_counted.h"
#include "base/memory/weak_ptr.h"
#include "base/message_loop/message_loop.h"
#include "base/time/time.h"
#include "base/timer/timer.h"
namespace base {
struct PendingTask;
}
namespace timers {
// The class implements a timer that is capable of waking the system up from a
// suspended state. For example, this is useful for running tasks that are
// needed for maintaining network connectivity, like sending heartbeat messages.
// Currently, this feature is only available on Chrome OS systems running linux
// version 3.11 or higher. On all other platforms, the AlarmTimer behaves
// exactly the same way as a regular Timer.
class AlarmTimer : public base::Timer,
public base::MessageLoop::DestructionObserver {
public:
// The delegate is responsible for managing the system level details for
// actually setting up and monitoring a timer that is capable of waking the
// system from suspend. This class is reference counted because it may need
// to outlive the timer in order to clean up after itself.
class Delegate : public base::RefCountedThreadSafe<Delegate> {
public:
// Initializes the timer. Should return true iff the system has timers that
// can wake it up from suspend. Will only be called once.
virtual bool Init(base::WeakPtr<AlarmTimer> timer) = 0;
// Stops the currently running timer. It should be safe to call this more
// than once.
virtual void Stop() = 0;
// Resets the timer to fire after |delay| has passed. Cancels any
// pre-existing delay.
virtual void Reset(base::TimeDelta delay) = 0;
protected:
virtual ~Delegate() {}
private:
friend class base::RefCountedThreadSafe<Delegate>;
};
AlarmTimer(bool retain_user_task, bool is_repeating);
AlarmTimer(const tracked_objects::Location& posted_from,
base::TimeDelta delay,
const base::Closure& user_task,
bool is_repeating);
~AlarmTimer() override;
bool can_wake_from_suspend() const { return can_wake_from_suspend_; }
// Must be called by the delegate to indicate that the timer has fired and
// that the user task should be run.
void OnTimerFired();
// Timer overrides.
void Stop() override;
void Reset() override;
// MessageLoop::DestructionObserver overrides.
void WillDestroyCurrentMessageLoop() override;
private:
// Initializes the timer with the appropriate delegate.
void Init();
// Delegate that will manage actually setting the timer.
scoped_refptr<Delegate> delegate_;
// Keeps track of the user task we want to run. A new one is constructed
// every time Reset() is called.
scoped_ptr<base::PendingTask> pending_task_;
// Tracks whether the timer has the ability to wake the system up from
// suspend. This is a runtime check because we won't know if the system
// supports being woken up from suspend until the delegate actually tries to
// set it up.
bool can_wake_from_suspend_;
// Pointer to the message loop that started the timer. Used to track the
// destruction of that message loop.
base::MessageLoop* origin_message_loop_;
base::WeakPtrFactory<AlarmTimer> weak_factory_;
DISALLOW_COPY_AND_ASSIGN(AlarmTimer);
};
} // namespace timers
#endif // COMPONENTS_TIMER_ALARM_TIMER_H_
|
cbcc1312c1f9323876eca2d8cf8bb20a762fe414 | ff800ee04c560b2644374c71d8fbda9859b41be0 | /LeetCode/24.swap-nodes-in-pairs.cpp | ddb9a0c11e2bd4f7351cdca99fa810fda1615ab5 | [] | no_license | TWANG006/Programming_Exercise | efc994034f225b95fadcaa056b2982184b34ef25 | 48cf5ff91a26db0ddf6ab67e7d2a7118891f366f | refs/heads/master | 2021-07-06T07:44:04.042132 | 2020-09-14T12:24:38 | 2020-09-14T12:24:38 | 176,791,763 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 927 | cpp | 24.swap-nodes-in-pairs.cpp | /*
* @lc app=leetcode id=24 lang=cpp
*
* [24] Swap Nodes in Pairs
*/
// @lc code=start
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution
{
public:
ListNode *swapPairs(ListNode *head)
{
if (head == nullptr || head->next == nullptr)
return head;
ListNode dummy(0);
ListNode *p = &dummy;
dummy.next = head;
while (p->next != nullptr && p->next->next != nullptr)
{
ListNode* n = p->next;
ListNode* nn = p->next->next;
p->next = nn;
n->next = nn->next;
nn->next = n;
p = p->next->next;
}
return dummy.next;
}
};
// @lc code=end
|
7ebe3da4bd46b0d02d73b63d7867dcfaa6681191 | 04fc82b422131353a113a567e157ac87962546c9 | /src/Shader.h | 221c30103661fdbaa0f20bd42fae6f7498ecbf5f | [] | no_license | DanyFids/Glade-iators | b369e88a45611fe0566e1c29749219452ca6b99a | fef2a985eb859474877da11aa405e54f7fbea1ae | refs/heads/master | 2020-08-26T17:22:47.823003 | 2020-02-10T21:35:33 | 2020-02-10T21:35:33 | 217,085,775 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 719 | h | Shader.h | #pragma once
#include<string>
#include<GLM/glm.hpp>
#include<glad/glad.h>
class Shader {
int LoadShaderCode(const char* filename, GLchar** SourceCode);
public:
//typedef std::shared_ptr<Shader> Sptr;
unsigned int ID;
Shader(const char* vertShaderPath, const char* fragShaderPath, const char* geoShaderPath = "");
~Shader();
void Use();
void SetB(const std::string name, bool value);
void SetI(const std::string name, int value);
void SetF(const std::string name, float value);
void SetMat3(const std::string name, glm::mat3 value);
void SetMat4(const std::string name, glm::mat4 value);
void SetVec3(const std::string name, glm::vec3 value);
void SetVec2(const std::string name, glm::vec2 value);
}; |
51e44d78c339a097229881a3b4257ca0bcea2ae1 | d347554c4bc24b7e159551007f5683cac8fa97d0 | /aftn/aftnws/src/telegram/atsmessages/NotamMessage.cpp | e1f82bfe9561133978c4be191a17dd0e8e5c5e0d | [] | no_license | ansartnl/ALPHA | 892065b1476ec9c35e834a3158592332cda4c5f5 | 138ddd981ed5bac882c29f28a065171e51d680cf | refs/heads/main | 2022-12-27T16:15:28.721053 | 2020-10-16T08:58:41 | 2020-10-16T08:58:41 | 304,633,537 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 490 | cpp | NotamMessage.cpp | #include "NotamMessage.h"
#include "LamMessage.h"
NotamMessage::NotamMessage()
{
mInfo.type = Ats::NOTAM;
}
NotamMessage::NotamMessage(const NotamStruct ¬am)
{
mNotam = notam;
mInfo.type = Ats::NOTAM;
}
QByteArray NotamMessage::toAftn() const
{
QByteArray ret;
return ret;
}
QByteArray NotamMessage::toJson() const
{
QByteArray ret;
return ret;
}
LamMessage * NotamMessage::lam() const
{
LamStruct lamStruct;
return new LamMessage(lamStruct);
}
|
4ec421145d25ae59c722dd9b27e46736b6db91ee | 81ed424b05260a70167c8293f71a00cc1496ee59 | /LIBS/u3dLib/sources/Bsp.cpp | 4062af8e867c59523fa5fe4e21a3e1ac96490986 | [] | no_license | aramadia/android-popsy-vip2 | 0422f8ae1f45bb9a706147724daa46233e3a53c0 | de62b2df311134e664b1457f7860b5159ed4769b | refs/heads/master | 2020-07-04T16:05:42.536084 | 2014-06-12T00:32:23 | 2014-06-12T00:33:29 | 4,014,322 | 1 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 22,395 | cpp | Bsp.cpp | /*-----------------------------------------------------+
| BSP.cpp |
| |
| la définition de l'arbre BSP mais ici pour le |
| moteur temps réel! |
| |
| U2^PoPsy TeAm 1999 |
+-----------------------------------------------------*/
#include "U3D3.h"
//-------------------------------------------------------------------------
// +---------------------+
// | Les Fonctions |
// +---------------------+
//-------------------------------------------------------------------------
//----------------------------------------------------------------------------
// BoundingBox
//----------------------------------------------------------------------------
/*BoundingBox::BoundingBox()
{
vec3_set( pts[0], +1e+19f, -1e+19f, -1e+19f );
vec3_set( pts[1], -1e+19f, -1e+19f, -1e+19f );
vec3_set( pts[2], +1e+19f, -1e+19f, +1e+19f );
vec3_set( pts[3], -1e+19f, -1e+19f, +1e+19f );
vec3_set( pts[4], +1e+19f, +1e+19f, -1e+19f );
vec3_set( pts[5], -1e+19f, +1e+19f, -1e+19f );
vec3_set( pts[6], +1e+19f, +1e+19f, +1e+19f );
vec3_set( pts[7], -1e+19f, +1e+19f, +1e+19f );
}
//----------------------------------------------------------------------------
// actualise la Bounding en fct du point si necessaire
void BoundingBox::TestEtActua( Ufloat *pt )
{
if( pt[0] > pts[1][0] )
{
pts[1][0] = pt[0];
pts[3][0] = pt[0];
pts[5][0] = pt[0];
pts[7][0] = pt[0];
}
if( pt[0] < pts[0][0] )
{
pts[0][0] = pt[0];
pts[2][0] = pt[0];
pts[4][0] = pt[0];
pts[6][0] = pt[0];
}
if( pt[1] > pts[0][1] )
{
pts[0][1] = pt[1];
pts[1][1] = pt[1];
pts[2][1] = pt[1];
pts[3][1] = pt[1];
}
if( pt[1] < pts[4][1] )
{
pts[4][1] = pt[1];
pts[5][1] = pt[1];
pts[6][1] = pt[1];
pts[7][1] = pt[1];
}
if( pt[2] > pts[0][2] )
{
pts[0][2] = pt[2];
pts[1][2] = pt[2];
pts[4][2] = pt[2];
pts[5][2] = pt[2];
}
if( pt[2] < pts[2][2] )
{
pts[2][2] = pt[2];
pts[3][2] = pt[2];
pts[6][2] = pt[2];
pts[7][2] = pt[2];
}
}
//----------------------------------------------------------------------------
// renvoie TRUE si &b est contune dans la bounding box !
bool BoundingBox::Contenu( BoundingBox &b )
{
if( pts[1][0] < b.pts[1][0] ) return FALSE;
if( pts[0][0] > b.pts[0][0] ) return FALSE;
if( pts[0][1] < b.pts[0][1] ) return FALSE;
if( pts[4][1] > b.pts[1][1] ) return FALSE;
if( pts[0][2] < b.pts[0][2] ) return FALSE;
if( pts[2][2] > b.pts[2][2] ) return FALSE;
return FALSE;
}*/
//----------------------------------------------------------------------------
// BoundingSphere
//----------------------------------------------------------------------------
/*BoundingSphere::BoundingSphere()
{
vec3_set( centre, 0.f, 0.f, 0.f );
rayon = 0.f;
rayonFake = 0.f;
}*/
//----------------------------------------------------------------------------
// Uplan_BSP
//----------------------------------------------------------------------------
// recalcul le plan à partie des 3 points
/*void Uplan_BSP::Calc( const Ufloat pt0[3], const Ufloat pt1[3], const Ufloat pt2[3] )
{
Ufloat v1[3],v2[3];
vec3_sub( v1, pt1, pt0 );
vec3_sub( v2, pt2, pt0 );
vec3_xprd( normal, v1, v2 );
vec3_normalize( normal );
dist = vec3_dot( pt0, normal );
}
//----------------------------------------------------------------------------
//renvoie position d'une Bounding box par rapport au plan
BoundPlace Uplan_BSP::GetPos( BoundingBox &b )
{
bool derriere=FALSE,devant=FALSE;
for(U32 a=0; a<8; a++)
{
if( distance( b.pts[a] )< 0 ) derriere = TRUE;
else devant = TRUE;
}
if( derriere && devant ) return ENTRE_DEUX;
if( derriere ) return DERRIERE;
else return DEVANT;
}
//----------------------------------------------------------------------------
// renvoie la matrice de transformation associée au plan
void Uplan_BSP::GetTransMatrix( Ufloat m[4][4] )
{
Ufloat r,rx,ry;
Ufloat t[4][4];
Ufloat v1[3];
r = sqrt( normal[2]*normal[2] + normal[0]*normal[0] );
if( r==0.0f ) // cas particulier
{
m44_identite( m );
vec3_set( m[1], 0.f, 0.f, 1.f );
vec3_set( m[2], 0.f, 1.f, 0.f );
return;
}
ry= acos( normal[2]/r );
if( normal[0]<0 ) ry=-ry;
m44_identite( t );
t[0][0]=cos(ry); t[0][2]=-sin(ry);
t[2][0]=sin(ry); t[2][2]=cos(ry);
v1[0] = vec3_dot( normal, t[0] );
v1[1] = vec3_dot( normal, t[1] );
v1[2] = vec3_dot( normal, t[2] );
r = sqrt( v1[2]*v1[2] + v1[1]*v1[1] );
rx= acos( v1[2]/r );
if( normal[1]>0 ) rx=-rx;
m44_identite( m );
m[1][1]=cos(rx); m[1][2]=sin(rx);
m[2][1]=-sin(rx); m[2][2]=cos(rx);
m44_multiply(m,t,m);
}*/
//----------------------------------------------------------------------------
// PolygonU3D
//----------------------------------------------------------------------------
/*PolygonU3D::PolygonU3D()
{
nbVertex = 0;
Vtab = NULL;
arrete = 0;
flag = PolyFLAG_NORM;
m = NULL;
suiv = NULL;
lmapTex = NULL;
vec3_set( RVB, 1.f, 1.f, 1.f );
}
//----------------------------------------------------------------------------
PolygonU3D::~PolygonU3D()
{
if( Vtab ) delete [] Vtab;
}
//----------------------------------------------------------------------------
// calcul normale d'origine
void PolygonU3D::CalcPlan()
{
plan.Calc( Vtab[0]->c->origine, Vtab[1]->c->origine, Vtab[2]->c->origine );
}
//----------------------------------------------------------------------------
// créé un new poly si nécessaire en fonction du clipping !
PolygonU3D *PolygonU3D::ClipToPlan(Uplan_BSP *plan)
{
PolygonU3D *ret;
VertexU3D *V[20],**V1;
VertexU3D **Vtab1;
VertexU3D *debut, *fin;
Ufloat dist1,dist2,distp;
U32 i,nbV,arreteF=0;
bool Fnew=FALSE;
nbV = 0;
V1 = V;
Vtab1 = Vtab;
distp = dist2 = plan->distance( Vtab[0]->c->trans );
for(i=0; i<nbVertex-1; i++,Vtab1++)
{
debut = *Vtab1;
fin = Vtab1[1];
dist1 = dist2;
dist2 = plan->distance( fin->c->trans );
if( (dist1>=0) && (dist2>=0) )
{
*V1 = debut;
V1++;
arreteF |= ( (arrete>>i)&0x1 )<<nbV;
nbV++;
}
// cas ou les 2 points sont hors de champ
else if( (dist1<0) && (dist2<0) )
{
Fnew = 1;
continue;
}
// ca où l'on créé un nouveau vertex car le segment est
// coupé
else
{
Ufloat scale;
VertexU3D *nouvo;
CoordU3D *co;
if( dist1>=0 )
{
*V1 = debut;
V1++;
arreteF |= ( (arrete>>i)&0x1 )<<nbV;
nbV++;
}
else
arreteF |= ( (arrete>>i)&0x1 )<<nbV;
scale = -dist1 / (dist2 - dist1 );
nouvo = U3D3Manager->NewVertex();
nouvo->c = U3D3Manager->NewCoord();
co = nouvo->c;
// ---> interpole les données attachées au vertex !
nouvo->Interpole3D( debut, fin, scale );
// insere new point
*V1 = nouvo;
V1++;
nbV++;
Fnew = 1;
}
}
{
debut = *Vtab1;
fin = Vtab[0];
dist1 = dist2;
dist2 = distp;
if( (dist1>=0) && (dist2>=0) )
{
*V1 = debut;
V1++;
arreteF |= ( (arrete>>i)&0x1 )<<nbV;
nbV++;
}
// cas ou les 2 points sont hors de champ
else if( (dist1<0) && (dist2<0) )
{
Fnew = 1;
}
// ca où l'on créé un nouveau vertex car le segment est
// coupé
else
{
Ufloat scale;
VertexU3D *nouvo;
CoordU3D *co;
if( dist1>=0 )
{
*V1 = debut;
V1++;
arreteF |= ( (arrete>>i)&0x1 )<<nbV;
nbV++;
}
else
arreteF |= ( (arrete>>i)&0x1 )<<nbV;
scale = -dist1 / (dist2 - dist1 );
nouvo = U3D3Manager->NewVertex();
nouvo->c = U3D3Manager->NewCoord();
co = nouvo->c;
// ---> interpole les données attachées au vertex !
nouvo->Interpole3D( debut, fin, scale );
// insere new point
*V1 = nouvo;
V1++;
nbV++;
Fnew = 1;
}
}
if( !Fnew ) return this; // pas de clipping alors rien de nouvo
else
{
if( nbV<3 ) return NULL; // moins de 3 sommets alors zou rien
ret = U3D3Manager->NewPoly( nbV ); // créé un poly
ret->flag = this->flag|PolyFLAG_TEMP; // on indique que c'est un poly temporaire
ret->arrete = arreteF;
ret->lmapTex = lmapTex;
vec3_eg( ret->RVB, RVB );
ret->m = this->m;
V1 = V;
Vtab1 = ret->Vtab;
for(i=0; i<nbV; i++,V1++,Vtab1++)
{
*Vtab1 = *V1;
(*V1)->utilisateurs++; // indique utilisation
(*V1)->c->utilisateurs++; // indique utilisation
}
}
return ret;
}
//----------------------------------------------------------------------------
PolygonU3D* PolygonU3D::GetClipped2DPoly(U32 flag,Ufloat val)
{
U32 a,nbV=0;
bool Fnew=FALSE;
VertexU3D *dst[20],**V1,**Vtab1;
PolygonU3D *ret;
for( a=0; a<nbVertex; a++ )
{
CoordU3D *src1 = Vtab[a]->c;
CoordU3D *src2 = Vtab[(a+1)%nbVertex]->c;
if( (src1->ClipInfo&flag) == 0 )
{
dst[nbV++] = Vtab[a];
if( (src2->ClipInfo&flag) ==0 )
continue;
}
else
{
if( src2->ClipInfo&flag )
continue;
}
Fnew = TRUE;
// alloue new vertex
VertexU3D *nouvo;
nouvo = U3D3Manager->NewVertex();
nouvo->c = U3D3Manager->NewCoord();
// met flag de clipping a jour
Camera *cam = U3D3Monde3D->GetActualCamera();
if( flag==ClipGauche || flag==ClipDroit )
{
Ufloat scale = (val - src1->ecran[0]) / (src2->ecran[0] - src1->ecran[0]);
// ---> interpole les données attachées au vertex !
nouvo->Interpole2D( Vtab[a], Vtab[(a+1)%nbVertex], scale );
nouvo->c->ecran[0] = val;
nouvo->c->ecran[1] = scale*( src2->ecran[1] - src1->ecran[1] ) + src1->ecran[1];
// remet flag de clipping a jour pour ce vertex
if( nouvo->c->ecran[1] < cam->GetHaut2DClip() )
nouvo->c->ClipInfo = ClipHaut;
else if(nouvo->c->ecran[1] > cam->GetBas2DClip() )
nouvo->c->ClipInfo = ClipBas;
}
else
{
Ufloat scale = (val - src1->ecran[1]) / (src2->ecran[1] - src1->ecran[1]);
// ---> interpole les données attachées au vertex !
nouvo->Interpole2D( Vtab[a], Vtab[(a+1)%nbVertex], scale );
nouvo->c->ecran[1] = val;
nouvo->c->ecran[0] = scale*( src2->ecran[0] - src1->ecran[0] ) + src1->ecran[0];
// remet flag de clipping a jour pour ce vertex
if( nouvo->c->ecran[0] < cam->GetGauche2DClip() )
nouvo->c->ClipInfo = ClipGauche;
else if(nouvo->c->ecran[0] > cam->GetDroite2DClip() )
nouvo->c->ClipInfo = ClipDroit;
}
dst[nbV++] = nouvo;
}
if( nbV<3 ) return NULL; // moins de 3 sommet alors on se casse
if( !Fnew ) return this; // pas de clipping alors rien de nouvo
else
{
ret = U3D3Manager->NewPoly( nbV ); // créé un poly
ret->flag = this->flag|PolyFLAG_TEMP; // on indique que c'est un poly temporaire
// ret->arrete = arreteF; // PAS Géré POUR l'INSTANT !
ret->lmapTex = lmapTex;
vec3_eg( ret->RVB, RVB );
ret->m = this->m;
V1 = dst;
Vtab1 = ret->Vtab;
for(U32 i=0; i<nbV; i++,V1++,Vtab1++)
{
*Vtab1 = *V1;
(*V1)->utilisateurs++; // indique utilisation
(*V1)->c->utilisateurs++; // indique utilisation
}
}
return ret;
}
//----------------------------------------------------------------------------
PolygonU3D* PolygonU3D::GetClipped2DPoly()
{
PolygonU3D *draw1,*draw2;
VertexU3D *V[20],*V1[20];
VertexU3D ** src = V;
VertexU3D ** dst = V1;
U32 a;
bool BesGauche,BesDroit,BesHaut,BesBas;
Camera *cam = U3D3Monde3D->GetActualCamera();
draw1 = this;
//-------------------------> realise e clipping proche si besoin est
if( BesoinClip(ClipProche) )
{
bool ret=TRUE;
for( a=0; a<nbVertex; a++)
{
if( (Vtab[a]->c->ClipInfo&ClipProche) == 0 )
{
ret = FALSE;
break;
}
}
if( ret ) return NULL;
draw2 = draw1->ClipToPlan( cam->GetPlanProche() );
if( !draw2 ) return NULL;
draw1 = draw2;
U32 num = U3D3Monde3D->GetTick();
for( a=0; a<draw1->nbVertex; a++)
cam->Projet( draw1->Vtab[a], num ); // calcul coords 2D si il le fo
BesGauche = draw1->BesoinClip( ClipGauche );
BesDroit = draw1->BesoinClip( ClipDroit );
BesHaut = draw1->BesoinClip( ClipHaut );
BesBas = draw1->BesoinClip( ClipBas );;
}
else
{
BesGauche = BesoinClip( ClipGauche );
BesDroit = BesoinClip( ClipDroit );
BesHaut = BesoinClip( ClipHaut );
BesBas = BesoinClip( ClipBas );;
}
if( BesGauche )
{
// draw2 = draw1->GetClipped2DPoly( ClipGauche, cam->GetGauche2DClip() );
draw2 = draw1->ClipToPlan( cam->GetPlanGauche() );
if( !draw2 )
{
if( draw1!=this ) U3D3Manager->FreePoly( draw1 );
return NULL;
}
if( (draw2!=draw1) && (draw1!=this) )
U3D3Manager->FreePoly( draw1 );
draw1 = draw2;
}
if( BesDroit )
{
// draw2 = draw1->GetClipped2DPoly( ClipDroit, cam->GetDroite2DClip() );
draw2 = draw1->ClipToPlan( cam->GetPlanDroit() );
if( !draw2 )
{
if( draw1!=this ) U3D3Manager->FreePoly( draw1 );
return NULL;
}
if( (draw2!=draw1) && (draw1!=this) )
U3D3Manager->FreePoly( draw1 );
draw1 = draw2;
}
if( BesBas )
{
// draw2 = draw1->GetClipped2DPoly( ClipBas, cam->GetBas2DClip() );
draw2 = draw1->ClipToPlan( cam->GetPlanHaut() );
if( !draw2 )
{
if( draw1!=this ) U3D3Manager->FreePoly( draw1 );
return NULL;
}
if( (draw2!=draw1) && (draw1!=this) )
U3D3Manager->FreePoly( draw1 );
draw1 = draw2;
}
if( BesHaut )
{
// draw2 = draw1->GetClipped2DPoly( ClipHaut, cam->GetHaut2DClip() );
draw2 = draw1->ClipToPlan( cam->GetPlanBas() );
if( !draw2 )
{
if( draw1!=this ) U3D3Manager->FreePoly( draw1 );
return NULL;
}
if( (draw2!=draw1) && (draw1!=this) )
U3D3Manager->FreePoly( draw1 );
draw1 = draw2;
}
// calcul coords 2D si il le fo
U32 num = U3D3Monde3D->GetTick();
for( a=0; a<draw1->nbVertex; a++)
{
cam->Projet( draw1->Vtab[a], num );
if( draw1->Vtab[a]->c->ClipInfo != ClipNo )
a=a;
}
return draw1;
}
//----------------------------------------------------------------------------
// renvoie TRUE si le segment coupe le poly
#define EPSILON 0.01f
bool PolygonU3D::Intersection( Ufloat debut[3], Ufloat fin[3] )
{
Uplan_BSP planCote;
// fait dabord backface culling!
if( BackFaceCull( debut ) )
return FALSE;
// si les 2 pts sont du même coté du plan de la face alors
// cette que le segment ne coupe pas cette face !
bool res1, res2;
Ufloat dist = plan.distance(debut);
if( dist < -EPSILON ) res1 = 0;
else if( dist > EPSILON ) res1 = 1;
else return FALSE; // cas ou pt dans le plan du poly -> yaura forcement pas de coupe !
dist = plan.distance(fin);
if( dist < -EPSILON ) res2 = FALSE;
else if( dist > EPSILON ) res2 = TRUE;
else return FALSE; // pareil qu'en haut
if( res1 == res2 ) return FALSE;
planCote.Calc( debut, Vtab[nbVertex-1]->c->origine, Vtab[0]->c->origine );
bool preced = TRUE,actua;
if( planCote.distance( fin ) < -EPSILON ) preced = FALSE;
for( U32 a=0; a<nbVertex-1; a++ )
{
planCote.Calc( debut, Vtab[a]->c->origine, Vtab[a+1]->c->origine );
if( planCote.distance( fin ) < -EPSILON ) actua = FALSE;
else actua = TRUE;
if( actua != preced ) return FALSE;
preced = actua;
}
return TRUE;
}*/
//----------------------------------------------------------------------------
// Unoeud_BSP
//----------------------------------------------------------------------------
/*Unoeud_BSP::Unoeud_BSP(U32 nbf)
{
devant = NULL;
derriere = NULL;
nbfaces = nbf;
Ptab = new PolygonU3D*[nbf];
if( nbf ) TestPtr(Ptab);
}
//----------------------------------------------------------------------------
Unoeud_BSP::~Unoeud_BSP()
{
if( Ptab ) delete [] Ptab;
if( devant ) delete devant;
if( derriere ) delete derriere;
}
//----------------------------------------------------------------------------
void Unoeud_BSP::CalculPlan()
{
Ufloat v1[3],v2[3],v[3];
vec3_sub( v1, Ptab[0]->Vtab[1]->c->origine, Ptab[0]->Vtab[0]->c->origine );
vec3_sub( v2, Ptab[0]->Vtab[2]->c->origine, Ptab[0]->Vtab[0]->c->origine );
vec3_xprd( v, v1, v2 );
vec3_normalize( v );
vec3_eg( plan.normal, v );
plan.dist = vec3_dot( v, Ptab[0]->Vtab[0]->c->origine );
if( devant ) devant->CalculPlan();
if( derriere ) derriere->CalculPlan();
}
//----------------------------------------------------------------------------
// Calcul la bounding d'un Noeud ( en fonction des enfants et de lui meme )
void Unoeud_BSP::CalculBounding()
{
U32 a,b;
BoundingBox B1;
for(a=0; a<nbfaces; a++)
for(b=0; b<Ptab[a]->nbVertex; b++)
B.TestEtActua( Ptab[a]->Vtab[b]->c->origine );
if( devant )
{
devant->CalculBounding();
devant->GetBounding( B1 );
for( a=0; a<8; a++)
B.TestEtActua( B1.pts[a] );
}
if( derriere )
{
derriere->CalculBounding();
derriere->GetBounding( B1 );
for( a=0; a<8; a++)
B.TestEtActua( B1.pts[a] );
}
}
//----------------------------------------------------------------------------
// Renvoie la bounding du noeud
void Unoeud_BSP::GetBounding(BoundingBox &box)
{
memcpy( &box, &B, sizeof(BoundingBox) );
}
//----------------------------------------------------------------------------
// on va afficher le contenue de TOUT se qu'englobe le noeud en fonction
// de la camera dans le PipeLine de faces
void Unoeud_BSP::Affiche(U32 flagc)
{
U32 a;
Camera *cam = U3D3Monde3D->GetActualCamera();
Ufloat *vue = cam->GetVue();
PolyPipeLine *pipe = U3D3Monde3D->GetActualPipe();
// réactualise les flags de clipping de l'espace délimité par
// la bounding Box
// flagc = cam->ClipInfo( &B, flagc );
flagc = ClipAll;
// c'est en dehors de l'ecran alors on laisse tomber
if( flagc==ClipCache ) return;
// cas de figure où la camera est devant le plan
if( plan.distance( cam->GetPos() ) >= 0 )
{
// on affiche dabord tout se qu'il ya derrière
if( derriere )
derriere->Affiche( flagc );
for(a=0; a<nbfaces; a++)
pipe->AddPoly( Ptab[a]->GetToDraw() );
if( devant )
devant->Affiche( flagc );
}
// cas de figure où la camera est derriere le plan
else
{
// on affiche dabord tout se qu'il ya devant
if( devant )
devant->Affiche( flagc );
for(a=0; a<nbfaces; a++)
pipe->AddPoly( Ptab[a]->GetToDraw() );
if( derriere )
derriere->Affiche( flagc );
}
}
//----------------------------------------------------------------------------
// meme fonction qu'en haut sauf que la on traite des objets dynamiques ( qui
// bougent en fait )
void Unoeud_BSP::AfficheDyna(U32 flagc)
{
U32 a;
Camera *cam = U3D3Monde3D->GetActualCamera();
Ufloat *vue = cam->GetVue();
PolyPipeLine *pipe = U3D3Monde3D->GetActualPipe();
// réactualise les flags de clipping de l'espace délimité par
// la bounding Box
// flagc = cam->ClipInfo( &B, flagc );
flagc = ClipAll;
// c'est en dehors de l'ecran alors on laisse tomber
if( flagc==ClipCache ) return;
// cas de figure où la camera est devant le plan
if( plan.distance( cam->GetPos() ) >= 0 )
{
// on affiche dabord tout se qu'il ya derrière
if( derriere )
derriere->AfficheDyna( flagc );
for(a=0; a<nbfaces; a++)
pipe->AddPolyDyna( Ptab[a]->GetToDraw() );
if( devant )
devant->AfficheDyna( flagc );
}
// cas de figure où la camera est derriere le plan
else
{
// on affiche dabord tout se qu'il ya devant
if( devant )
devant->AfficheDyna( flagc );
for(a=0; a<nbfaces; a++)
pipe->AddPolyDyna( Ptab[a]->GetToDraw() );
if( derriere )
derriere->AfficheDyna( flagc );
}
}*/
//----------------------------------------------------------------------------
|
89671d1641af346af1abd60e6bcfbdad15134c4a | be3ccec1fa1c97839199f0ede09a1f93ae2ac5f0 | /gen/rng_init.cpp | dcbf4a7767099e980b3d502be05a90aa45f44498 | [
"BSD-3-Clause"
] | permissive | bdapi/bdapi | 45829cfc870719be54bd38cca787cb38f72cc2e3 | f3995568925e4d1bdabbe11b7ef1e8c79969da67 | refs/heads/master | 2021-01-02T22:50:52.428487 | 2016-03-14T03:58:15 | 2016-03-14T03:58:15 | 23,017,813 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 835 | cpp | rng_init.cpp |
/* bdapi - brain damage api version 0.6.0 */
#ifndef BDAPI_GEN_RNG_INIT_CPP
#define BDAPI_GEN_RNG_INIT_CPP
#include "gen/rng.hpp"
/* includes */
// standard
#include "ctime"
// bdapi
/* namespaces */
namespace bdapi {
namespace gen {
/* static variable declarations */
static u32 seed_offset = 0;
/* random number generator class initialization function implementations */
// constructors
rng::rng()
{
set_seed( time(NULL) + seed_offset++ );
}
rng::rng( u32 seed )
{
set_seed( seed );
}
rng::rng( const rng& copy )
{
seed = copy.seed;
engine = copy.engine;
}
// set seed
rng& rng::set_seed( u32 seed )
{
this->seed = seed;
return reset();
}
rng& rng::set_seed( rng& other )
{
seed = other.generate_seed();
return reset();
}
// reset
rng& rng::reset()
{
engine.seed( seed );
RETHIS;
}
/* end */
}
}
#endif
|
713bcc2408056ae75e8b74efc4b1b4b428735697 | c654bdb7ff47f8534d2c7eed1bc878bd6209825d | /src/sdchain/beast/insight/Base.h | b476857a8dbf0c1c6bc94ffa745cae9cffbfc594 | [] | no_license | Gamma-Token/SDChain-Core | 6c2884b65efc2e53a53a10656b101a335a2ec50b | 88dc4cdd7c8f8c04144ffe9acd694958d34703a7 | refs/heads/master | 2020-06-18T06:37:12.570366 | 2019-04-29T05:27:18 | 2019-04-29T05:27:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 635 | h | Base.h | //------------------------------------------------------------------------------
/*
This file is part of Beast: https://github.com/vinniefalco/Beast
Copyright 2013, Vinnie Falco <vinnie.falco@gmail.com>
*/
//==============================================================================
#ifndef BEAST_INSIGHT_BASE_H_INCLUDED
#define BEAST_INSIGHT_BASE_H_INCLUDED
#include <memory>
namespace beast {
namespace insight {
/** Base for all metrics and hooks. */
class Base
{
public:
virtual ~Base () = 0;
Base() = default;
Base(Base const&) = default;
Base& operator=(Base const&) = default;
};
}
}
#endif
|
eb68701e461cd95540776fb670e0b4cae7cadd06 | 70421ae87edc8ef612438b8b624cf755996a866e | /c++/fibonacci.cpp | eaa2ec7253308c0b2ac6a07f1ecbd50346e720c8 | [] | no_license | antzdote/school-stuff | 27cf6c62d54faf43a1b82dd9043f907eefa160b3 | 2acaf6743d2c1644529101a93f2717788b14818c | refs/heads/master | 2020-06-23T13:44:00.335191 | 2019-07-24T13:43:02 | 2019-07-24T13:43:02 | 198,641,495 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 307 | cpp | fibonacci.cpp | #include <iostream>
using namespace std;
int fib(int n)
{
if (n<=0)
return 0;
else if (n==1)
return 1;
else
return fib(n-1)+fib(n-2);
}
int main()
{
int n;
cout<<"Enter a fibonacci number of terms to calculate: ";
cin>>n;
for(int i=0; i<n; i++)
{
cout<<fib(i)<<" ";
}
}
|
57ab9ca91b763b47932a08b18bb6975dfdfade9f | 9462d3ca1a80ea81f6a2416254072e1489699e1c | /Dynamic/Flowdown.cpp | 4cbc2554de2bc117cd695a4d73af121ee0a78807 | [] | no_license | muff1nman/Algorithms | 11419558b42d04689b0c9dc910ca311c41a5e1ed | 1bd0b4034451dff8c97be444e2eedf36f3e66164 | refs/heads/master | 2016-09-06T07:24:09.521034 | 2012-12-09T06:06:20 | 2012-12-09T06:06:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,587 | cpp | Flowdown.cpp | #include "Flowdown.h"
Flowdown::Flowdown(std::string palindrome): initdrome(palindrome) {
this->populateTable();
}
std::string Flowdown::getMaximum(){
return actPalindrome;
}
void Flowdown::calcMaximum(){
int index;
int max = 0;
for ( unsigned int i = 0; i < table.size(); ++i ) {
if ( table[i][table.size() - 1] > max ) {
max = table[i][table.size() - 1];
index = i;
}
}
actPalindrome = initdrome.substr(index,max);
}
void Flowdown::reserveTable(){
table.resize( initdrome.length());
for ( unsigned int i=0; i < initdrome.length(); ++i ) {
table[i].resize( initdrome.length(), 1 );
}
}
void Flowdown::populateTable(){
this->reserveTable();
for ( unsigned int i = 0; i < table.size(); ++i ) {
for ( unsigned int j = i+1; j < table.size(); ++j ) {
std::string temp = initdrome.substr(i,j-i+1);
if ( isPalindrome( temp.c_str(), temp.length() ) ) {
this->table[i][j] = temp.length();
} else {
this->table[i][j] = table[i][j-1];
}
}
}
}
void Flowdown::printTable(){
std::cout << " ";
for( unsigned int i = 0; i < table.size(); ++i) {
std::cout << initdrome[i] << " ";
}
std::cout << std::endl;
for(unsigned int i=0; i < table.size(); ++i) {
std::cout << initdrome[i] << " ";
for(unsigned int j=0; j < table[i].size(); ++j) {
std::cout << table[j][i] << " ";
}
std::cout << std::endl;
}
}
|
a5d210c2d30e1e326978fedbf239f92ace8fa6bd | a33aac97878b2cb15677be26e308cbc46e2862d2 | /program_data/PKU_raw/13/1455.c | 0f9791997a28829560b985dfc07eeedc24240ac2 | [] | no_license | GabeOchieng/ggnn.tensorflow | f5d7d0bca52258336fc12c9de6ae38223f28f786 | 7c62c0e8427bea6c8bec2cebf157b6f1ea70a213 | refs/heads/master | 2022-05-30T11:17:42.278048 | 2020-05-02T11:33:31 | 2020-05-02T11:33:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 429 | c | 1455.c | int main()
{
int n,i,j,cal=0,enter=1,num=0;
int a[100001]={0},b[100001]={0};
scanf("%d",&n);
for (i=1;i<=n;i++)
{
scanf("%d",&a[i]);
}
for (i=1;i<=n;i++)
{
for (j=1;j<=num;j++)
{
if (a[i]==b[j])
{
goto next;
break;
}
}
if (enter==1)
{
printf ("%d",a[i]);
enter=0;
}
else
printf (" %d",a[i]);
num++;
b[num]=a[i];
next:
b[0]=0;
}
return 0;
} |
f764cc519413a667778b60aa9d029eaa05316508 | 6ccb723686cf42b2ec8a9a080e0aefeb4e24319e | /tablice.cpp | 69f1a76b0bca8999ae57cd905609554b74fe75ba | [] | no_license | michczur/Rozne_drobiazgi | e7a50b6ffb08721e1a0ab36771edfe95fdd59034 | b869a0207a20373fd3eda326d2704a83262a869f | refs/heads/master | 2020-04-16T07:54:21.406667 | 2019-01-12T15:38:40 | 2019-01-12T15:38:40 | 165,403,325 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 766 | cpp | tablice.cpp | #include <iostream>
#include <cstdlib> //rand(), srand()
#include <ctime> //time()
int main()
{
srand(time(0));
//Zadanie:
//wylosuj 100 liczb
//wypisz ile z nich jest parzystych,
//a ile nieparzystych
int tab[2] = {0, 0};
// tab[0] = tab[1] = 0;
// int nieparzyste = 0, parzyste = 0;
for (int i = 0; i < 100; ++i) {
const int x = rand();
/*
if (x % 2 == 0)
++parzyste;
else
++nieparzyste;
*/
/*
if (x % 2 == 0)
++tab[0];
else
++tab[1];
*/
++tab[x % 2];
}
// std::cout << "parzyste = " << parzyste << '\n';
// std::cout << "nieparzyste = " << nieparzyste << '\n';
std::cout << "Wersja tablicowa:\n";
std::cout << "parzyste = " << tab[0] << '\n';
std::cout << "nieparzyste = " << tab[1] << '\n';
return 0;
}
|
f1527e2a4b2204bfac54727a0883fca14661f349 | e372f32ff25ebc35defb390b2df722d5040020f5 | /SharpUnrealTest/Plugins/SharpUnreal/Source/SharpUnreal/Public/SharpFunctionLibrary.h | 88467aee97143501864162699394bf79ea333a08 | [] | no_license | 19900623/SharpUnreal | a1a54e478d06beb48fbe93e0fb5982e13264ad74 | 7150bf04029741d3578b98d57687097a64c6636d | refs/heads/master | 2021-09-01T23:30:26.025862 | 2017-12-29T06:38:00 | 2017-12-29T06:38:00 | 259,869,100 | 1 | 0 | null | 2020-04-29T08:31:56 | 2020-04-29T08:31:55 | null | UTF-8 | C++ | false | false | 1,298 | h | SharpFunctionLibrary.h | #pragma once
#include "Kismet/BlueprintFunctionLibrary.h"
#include "SharpFunctionLibrary.generated.h"
/**
* 主要用于实现C#与蓝图的相互通讯
*/
UCLASS(ClassGroup = (SharpUnreal), meta = (BlueprintSpawnableComponent))
class SHARPUNREAL_API USharpFunctionLibrary : public UBlueprintFunctionLibrary
{
GENERATED_BODY()
public:
UFUNCTION(BlueprintCallable,Category="SharpUnreal")
static void SendStringEvent(FString evt, FString data);
UFUNCTION(BlueprintCallable, Category = "SharpUnreal")
static void SendIntEvent(FString evt, int data);
UFUNCTION(BlueprintCallable, Category = "SharpUnreal")
static void SendFloatEvent(FString evt, float data);
UFUNCTION(BlueprintCallable, Category = "SharpUnreal")
static void SetStringData(FString key, FString data);
UFUNCTION(BlueprintCallable, Category = "SharpUnreal")
static void SetIntData(FString key, int data);
UFUNCTION(BlueprintCallable, Category = "SharpUnreal")
static void SetFloatData(FString key, float data);
UFUNCTION(BlueprintCallable, Category = "SharpUnreal")
static FString GetStringData(FString key);
UFUNCTION(BlueprintCallable, Category = "SharpUnreal")
static int GetIntData(FString key);
UFUNCTION(BlueprintCallable, Category = "SharpUnreal")
static float GetFloatData(FString key);
};
|
b4b18899d5e502c7de435147e1093f7b2ebfbba3 | 698a11c977d074f3ab3f7d59883ba5e2e6f41002 | /tools/resourceviewer/model/smkitem.h | 68083dae7d50229bac225b9c2cc39c9daefe576c | [] | no_license | jeffmeese/tiberius | d0d92ebb69cd761baf2d79b75290e55cf21c70ec | 5a058cea86126d0b04b324830d757e7ece0fb497 | refs/heads/master | 2023-02-25T19:01:27.095207 | 2021-01-29T20:08:17 | 2021-01-29T20:08:17 | 306,618,752 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 332 | h | smkitem.h | #ifndef SMKITEM_H
#define SMKITEM_H
#include "resourceitem.h"
class Video;
class SmkItem
: public ResourceItem
{
public:
SmkItem(const QString & pathName);
public:
QWidget * createView() const override;
QList<Property> getProperties() const override;
private:
std::unique_ptr<Video> mVideo;
};
#endif // SMKITEM_H
|
7561290cdf77497f53a53b1e94698c1a543a6418 | 03ebbf7128e96abdb3ea146cb1f0825958152d68 | /Assignment 19/tree.cpp | 10bb57febd7fb97ecd8f823cb6d2bbbd85c6cfc8 | [] | no_license | leslieledeboer/CIS-7 | 75151ddebf5789bc36c7ecba28177db7c3f88179 | 391ab4d39b4c9219ddc8cdc7da2db6a67dc822db | refs/heads/master | 2021-01-20T12:10:47.061752 | 2017-12-01T19:53:39 | 2017-12-01T19:53:39 | 101,702,092 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,192 | cpp | tree.cpp | // Assignment 19
// tree.cpp
// Leslie Ledeboer
#include <iostream>
#include "tree.h"
using namespace std;
Tree::Node::Node(string name, Node * left, Node * right)
{
_name = name;
_left = left;
_right = right;
}
string Tree::Node::getName() const
{
return _name;
}
Tree::Node * Tree::Node::getLeft() const
{
return _left;
}
Tree::Node * Tree::Node::getRight() const
{
return _right;
}
void Tree::Node::setLeft(Node * left)
{
_left = left;
}
void Tree::Node::setRight(Node * right)
{
_right = right;
}
Tree::Node * Tree::traversal(const string & name, Node * current) const
{
Node * temp;
if (current == nullptr)
{
return nullptr;
}
if (current->getName() == name)
{
return current;
}
temp = traversal(name, current->getLeft());
if (temp)
{
return temp;
}
return traversal(name, current->getRight());
}
unsigned int Tree::traverseForDepth(Node * current, unsigned int currentDepth) const
{
static unsigned int maxDepth = 0;
if (current)
{
maxDepth = currentDepth;
traverseForDepth(current->getLeft(), currentDepth + 1);
traverseForDepth(current->getRight(), currentDepth + 1);
}
return maxDepth;
}
bool Tree::traverseForComplete(Node * current, unsigned int index) const
{
if (current == nullptr)
{
return true;
}
if (index >= treeSize)
{
return false;
}
return (traverseForComplete(current->getLeft(), 2 * index + 1) &&
traverseForComplete(current->getRight(), 2 * index + 2));
}
Tree::Tree()
{
root = new Node("root", nullptr, nullptr);
treeSize = 1;
}
Tree::~Tree()
{
delete root;
}
Tree & Tree::addNode(Node * node, bool side, const string & name)
{
if (!(side ? node->getLeft() : node->getRight()))
{
Node * leaf = new Node(name, nullptr, nullptr);
if (side)
{
node->setLeft(leaf);
}
else
{
node->setRight(leaf);
}
treeSize++;
}
return * this;
}
unsigned int Tree::getTreeSize() const
{
return treeSize;
}
Tree::Node * Tree::getNode(const string & name) const
{
return traversal(name, root);
}
unsigned int Tree::getTreeDepth() const
{
return traverseForDepth(root, 0);
}
bool Tree::isFull() const
{
return ((1 << (getTreeDepth() + 1)) - 1 == treeSize);
}
bool Tree::isComplete() const
{
return traverseForComplete(root, 0);
}
void Tree::preorder(Node * current) const
{
if (current)
{
cout << current->getName() << " ";
preorder(current->getLeft());
preorder(current->getRight());
}
}
void Tree::inorder(Node * current) const
{
if (current)
{
inorder(current->getLeft());
cout << current->getName() << " ";
inorder(current->getRight());
}
}
void Tree::postorder(Node * current) const
{
if (current)
{
postorder(current->getLeft());
postorder(current->getRight());
cout << current->getName() << " ";
}
}
|
c7d826c3e71a374b194c6362829ee1102ccad93c | 6281eaa96b579085f42433c00c4dc5a7c6d3ab42 | /03.03_exercise_set_3/exercise_18/main.cc | aaceaa412ad31ed8b32d8ea01f2307ba7ab28356 | [] | no_license | Keipi/Cpp-Part-I | a6c19c675f6995051e3ec1475fe278f092d55197 | b76edc869f66323283efee38e4abc4549f7325de | refs/heads/main | 2023-08-06T05:21:45.025098 | 2021-10-05T13:39:17 | 2021-10-05T13:39:17 | 406,343,707 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 173 | cc | main.cc | #include "main.ih"
int main(int argc, char *argv[])
{
if (argc == 1)
usage();
bool status = structCall(argc, argv);
if (status)
boundCall(argc, argv);
}
|
dbdd8f9ae6337f5b8b5780fb113cb6e0b3eacecc | b066028fea8c16eb9134bf94024a3962ca14ca97 | /lib/libgsmo/gmb_operate.cc | 2f3e2bafee7ede09825edf079dab75def82450b1 | [
"MIT"
] | permissive | elifesciences-publications/bpps-sipris-code | 9afa7646079f1da44f82539e8b8f472e46286374 | 3c5382489c5e6aeca20c93b7ba2907b19fad3cf7 | refs/heads/master | 2021-05-14T03:59:31.629499 | 2017-10-04T19:12:20 | 2017-10-04T19:12:20 | 116,630,816 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,327 | cc | gmb_operate.cc | /******************************************************************************************
Copyright (C) 1997-2014 Andrew F. Neuwald, Cold Spring Harbor Laboratory
and the University of Maryland School of Medicine.
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in the
Software without restriction, including without limitation the rights to use, copy,
modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so, subject to the
following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT
OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
For further information contact:
Andrew F. Neuwald
Institute for Genome Sciences and
Department of Biochemistry & Molecular Biology
University of Maryland School of Medicine
801 West Baltimore St.
BioPark II, Room 617
Baltimore, MD 21201
Tel: 410-706-6724; Fax: 410-706-1482; E-mail: aneuwald@som.umaryland.edu
******************************************************************************************/
#include "gmb_typ.h"
BooLean SlideColLeftCMSA(Int4 t, double *oldMap, double *newMap, cma_typ L)
{
}
BooLean SlideColRightCMSA(Int4 t, double *oldMap, double *newMap, cma_typ L)
{
}
BooLean gmb_typ::SlideColLeft(Int4 t, double *oldMap, double *newMap,
cma_typ L, double temperature)
/*************************************************************************
slide the end of one model onto the next model.
--[**.*.*]--[*.:**.*...***]--
| This operation allows escape from some
V nasty traps in alignment space.
--[**.*.*.*]---[**.*...***]--
returns TRUE if succeeds in sampling ends, otherwise returns FALSE.
*************************************************************************/
{
st_type sites = SitesCMSA(L);
fm_type M,*model=ModelsCMSA(L);
Int4 t1,t2,n,s,end,N,ntyp;
Int4 d0,d,i,j,e,start,length,offset,diff;
double map0,map,rand_no,*prob,total,ratio;
double *tmp_map;
unsigned char *seq;
BooLean right;
ntyp=nTypeSites(sites);
if(ntyp < 2) return FALSE; else if(t < 1 || t >= ntyp) return FALSE;
t1=t; t2 = t1+1; // slide left: source = t2, denstination = t1.
// 2. Make sure there are enough columns.
if(nColsFModel(model[t2]) <= 3) return FALSE;
map0 = RelMapCMSA(L); /** 1.b. Determine the alignment map. **/
*oldMap=map0;
// 3. Remove the last column from the source model.
M = model[t2]; length = LenFModel(M);
d0=RmColumnMSA(t2,1,L);
diff = length - LenFModel(M);
length = LenFModel(model[t1]);
// 4. Add the column to destination model.
end = length + diff;
tmp_map = new double [end+3];
NEW(prob,end+3,double);
for(total=1.0, i=length+1; i<=end; i++){
AddColumnMSA(t1,i,L);
map = RelMapCMSA(L);
tmp_map[i]=map;
ratio = exp(map-map0); /** ratio of new to old **/
if(temperature != 1.0) ratio = pow(ratio,temperature);
prob[i] = ratio; total += ratio;
s = LenFModel(model[t1]); RmColumnMSA(t1,s,L);
}
// 5. Sample an alignment.
rand_no = ((double)Random()/(double)RANDOM_MAX)*total;
for(i=length+1; i<=end; i++){
rand_no -= prob[i];
if(rand_no <= 0.0){
AddColumnMSA(t1,i,L);
// fprintf(stderr,"slide columns right to left (diff = %d)\n",diff);
*newMap=tmp_map[i]; delete [] tmp_map;
free(prob); return TRUE;
}
}
delete [] tmp_map;
AddColumnMSA(t2,1-diff,L); free(prob); return FALSE;
}
BooLean gmb_typ::SlideColRight(Int4 t, double *oldMap, double *newMap,
cma_typ L, double temperature)
/*************************************************************************
slide the end of one model onto the next model.
--[**.*.*.*]---[**.*...***]--
| This operation allows escape from some
V nasty traps in alignment space.
--[**.*.*]--[*.:**.*...***]--
returns TRUE if succeeds in sampling ends, otherwise returns FALSE.
*************************************************************************/
{
st_type sites = SitesCMSA(L);
fm_type M,*model=ModelsCMSA(L);
Int4 t1,t2,n,s,end,N,ntyp;
Int4 d0,d,i,e,start,length,offset,diff;
double map0,map,rand_no,*prob,total,ratio;
unsigned char *seq;
BooLean right;
double *tmp_map;
ntyp=nTypeSites(sites);
if(ntyp < 2) return FALSE; else if(t < 1 || t >= ntyp) return FALSE;
t1=t; t2 = t1+1;
if(nColsFModel(model[t1]) <= 3) return FALSE;
map0 = RelMapCMSA(L); /** 1.b. Determine the alignment map. **/
*oldMap=map0;
// source = t1, denstination = t2.
M = model[t1]; length = LenFModel(M);
/** 4. Remove the last column from the source model. **/
RmColumnMSA(t1,length,L);
diff = length - LenFModel(M);
NEW(prob,diff+3,double);
tmp_map = new double [diff+2];
/** 5. Add the columns to destination model **/
for(total=1.0, i=1; i<=diff; i++){
d=AddColumnMSA(t2,-(i-1),L);
map = RelMapCMSA(L);
tmp_map[i]=map;
ratio = exp(map-map0); /** ratio of new to old **/
if(temperature != 1.0) ratio = pow(ratio,temperature);
prob[i] = ratio; total += ratio;
RmColumnMSA(t2,1,L);
}
/** sample an alignment **/
rand_no = ((double)Random()/(double)RANDOM_MAX)*total;
for(i=1; i <= diff; i++){
rand_no -= prob[i];
if(rand_no <= 0.0){
AddColumnMSA(t2,-(i-1),L);
#if 1
fprintf(stderr,"slide columns from left to right adjacent models (diff = %d)\n",diff);
#endif
*newMap=tmp_map[i]; delete [] tmp_map;
free(prob); return TRUE;
}
} delete [] tmp_map;
AddColumnMSA(t1,length,L); free(prob);
return FALSE;
}
|
fb18173ce546f346b64c094d0c2e8d15e7480097 | 03131ac8b44268086b00cd29066667e9d13b4fc0 | /Tyontekija.cpp | 2fa73a4a8af950cde2e161c249caa37769fc5e41 | [
"MIT"
] | permissive | Mlindr/PersonelAndStudentManaging | 9cd4e5cd6eff815e0df2b50f64bb0de597261246 | 0f98e17b8f065279074ee61d7452a65c00505347 | refs/heads/master | 2020-04-17T04:40:17.057912 | 2019-01-17T14:55:06 | 2019-01-17T14:55:06 | 166,240,372 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 2,058 | cpp | Tyontekija.cpp | #include "Tyontekija.h"
#include <iostream>
#include <string>
#include <sstream>
using std::cin; using std::cout; using std::endl; using std::string; using std::getline;
/*Funktioiden nimet kertovat jo mitä tekevät*/
//oletusrakentaja
Tyontekija::Tyontekija(): Henkilo(),palkka_(),tunnus_()
{
}
//parametrirakentaja
Tyontekija::Tyontekija(string etunimi, string sukunimi, string osoite, string puhelinnumero,
double palkka, string tunnus): Henkilo(etunimi,sukunimi,osoite,puhelinnumero),palkka_(palkka),tunnus_(tunnus)
{
}
//kopiorakentaja
Tyontekija::Tyontekija(const Tyontekija &alkup): Henkilo(alkup),palkka_(alkup.palkka_),tunnus_(alkup.tunnus_)
{
}
//oletuspurkaja
Tyontekija::~Tyontekija()
{
}
Tyontekija &Tyontekija::operator=(const Tyontekija & sij)
{
if (this != &sij) {
Henkilo::operator=(sij);
palkka_ = sij.palkka_;
tunnus_ = sij.tunnus_;
}
return *this;
}
void Tyontekija::asetaPalkka(double palkka)
{
palkka_ = palkka;
}
void Tyontekija::asetaTunnus(string tunnus)
{
tunnus_ = tunnus;
}
double Tyontekija::annaPalkka() const
{
return palkka_;
}
string Tyontekija::annaTunnus() const
{
return tunnus_;
}
void Tyontekija::kysyTiedot()
{
Henkilo::kysyTiedot();//käytetään Henkilo luokan metodia, jolla saadaan nimi,sukunimi,jne...
//kysytään käyttäjältä palkka
cout << "anna palkka: ";
string palkka;
getline(cin, palkka);
palkanTarkistus(palkka);
//kysytään käyttäjältä tunnus
cout << "anna tunnus: ";
getline(cin, tunnus_);
}
void Tyontekija::tulosta() const
{
//tulostetaan henkilon tulostus eli nimi,jne.. sekä lisätään niiden tulostuksien perään palkan ja tunnuksen tulostus
Henkilo::tulosta();
cout << palkka_ << ", " << tunnus_ << ", ";
}
void Tyontekija::palkanTarkistus(string palkka)
{
//tehdään tyyppimuutoksen tarkistus, jos ei ollut double syöte string sisään->väärä syöte->pyydä uusi palkka
while (!(std::stringstream(palkka) >> palkka_)) {
cout << "V\x84\x84r\x84 sy\x94te, anna uusi palkka(pelk\x84t numeroarvot): ";
getline(cin, palkka);
}
} |
64a239647e897ddd99b07acf6b1d557af2925218 | af1f72ae61b844a03140f3546ffc56ba47fb60df | /src/lib/regurgitate/regurgitate.hpp | ddea009c4bb0d000fe1a46b414c7331b362309ee | [
"Apache-2.0"
] | permissive | Spirent/openperf | 23dac28e2e2e1279de5dc44f98f5b6fbced41a71 | d89da082e00bec781d0c251f72736602a4af9b18 | refs/heads/master | 2023-08-31T23:33:38.177916 | 2023-08-22T03:23:25 | 2023-08-22T07:13:15 | 143,898,378 | 23 | 16 | Apache-2.0 | 2023-08-22T07:13:16 | 2018-08-07T16:13:07 | C++ | UTF-8 | C++ | false | false | 12,946 | hpp | regurgitate.hpp | #ifndef _LIB_REGURGITATE_HPP_
#define _LIB_REGURGITATE_HPP_
#include <algorithm>
#include <array>
#include <atomic>
#include <cassert>
#include <numeric>
#include <iterator>
#include <iostream>
#include "api.h"
namespace ispc {
/*
* Generate a SFINAE wrapper for the specified key, value pairs.
*/
#define ISPC_MERGE_AND_SORT_WRAPPER(key_type, val_type) \
template <typename K, typename V> \
inline std::enable_if_t<std::conjunction_v<std::is_same<K, key_type>, \
std::is_same<V, val_type>>, \
unsigned> \
merge(K in_means[], \
V in_weights[], \
unsigned in_length, \
K out_means[], \
V out_weights[], \
unsigned out_length) \
{ \
return (regurgitate_merge_##key_type##_##val_type(in_means, \
in_weights, \
in_length, \
out_means, \
out_weights, \
out_length)); \
} \
template <typename K, typename V> \
inline std::enable_if_t<std::conjunction_v<std::is_same<K, key_type>, \
std::is_same<V, val_type>>, \
void> \
sort( \
K means[], V weights[], unsigned length, K scratch_m[], V scratch_w[]) \
{ \
regurgitate_sort_##key_type##_##val_type( \
means, weights, length, scratch_m, scratch_w); \
}
ISPC_MERGE_AND_SORT_WRAPPER(float, double)
ISPC_MERGE_AND_SORT_WRAPPER(float, float)
#undef ISPC_MERGE_AND_SORT_WRAPPER
} // namespace ispc
namespace regurgitate {
namespace detail {
template <typename Container> class centroid_container_iterator
{
static constexpr size_t invalid_idx = std::numeric_limits<size_t>::max();
std::reference_wrapper<Container> container_;
size_t idx_ = invalid_idx;
public:
using difference_type = std::ptrdiff_t;
using value_type = typename Container::value_type;
using pointer = void;
using reference = value_type&;
using iterator_category = std::forward_iterator_tag;
centroid_container_iterator(Container& container, size_t idx = 0)
: container_(container)
, idx_(idx)
{}
centroid_container_iterator(const Container& container, size_t idx = 0)
: container_(const_cast<Container&>(container))
, idx_(idx)
{}
centroid_container_iterator(const centroid_container_iterator& other)
: container_(other.container_)
, idx_(other.idx_)
{}
centroid_container_iterator&
operator=(centroid_container_iterator const& other)
{
if (this != &other) {
container_ = other.container_;
idx_ = other.idx_;
}
return (*this);
}
bool operator==(centroid_container_iterator const& other)
{
return (idx_ == other.idx_);
}
bool operator!=(centroid_container_iterator const& other)
{
return (idx_ != other.idx_);
}
centroid_container_iterator& operator++()
{
idx_++;
return (*this);
}
centroid_container_iterator operator++(int)
{
auto to_return = *this;
idx_++;
return (to_return);
}
value_type operator*() { return (container_.get()[idx_]); }
};
template <typename ValueType, typename WeightType, size_t Size>
struct centroid_container
{
using centroid = std::pair<ValueType, WeightType>;
using iterator = centroid_container_iterator<
centroid_container<ValueType, WeightType, Size>>;
using const_iterator = const iterator;
using difference_type = std::ptrdiff_t;
using value_type = centroid;
using reference_type = value_type&;
using size_type = size_t;
std::array<ValueType, Size> means_;
std::array<WeightType, Size> weights_;
size_t cursor_ = 0;
inline void push_back(ValueType v, WeightType w)
{
return (push_back({v, w}));
}
inline void push_back(centroid&& x)
{
assert(x.second != 0);
assert(cursor_ < Size);
means_[cursor_] = x.first;
weights_[cursor_] = x.second;
cursor_++;
}
value_type operator[](size_t idx)
{
return (centroid{means_[idx], weights_[idx]});
}
value_type operator[](size_t idx) const
{
return (centroid{means_[idx], weights_[idx]});
}
void reset() { cursor_ = 0; }
ValueType* means() { return (means_.data()); }
WeightType* weights() { return (weights_.data()); }
bool empty() const { return (cursor_ == 0); }
size_t size() const { return (cursor_); }
size_t capacity() const { return (Size); }
centroid front() const { return ((*this)[0]); }
centroid back() const { return ((*this)[size()]); }
iterator begin() { return (iterator(*this)); }
const_iterator begin() const { return (iterator(*this)); }
iterator end() { return (iterator(*this, size())); }
const_iterator end() const { return (iterator(*this, size())); }
void dump() const
{
std::cout << "length = " << size() << std::endl;
std::cout << '[';
std::for_each(begin(), end(), [](const auto& pair) {
std::cout << "(" << pair.first << "," << pair.second << "), ";
});
std::cout << "\b\b]" << std::endl;
}
};
} // namespace detail
/*
* fetch_add(1, std::memory_order_anything) compiles to a `lock inc` on x86.
* This is just an `inc`.
*/
template <typename T> void fast_inc(std::atomic<T>& t)
{
t.store(t.load(std::memory_order_relaxed) + 1, std::memory_order_release);
}
/*
* This digest class is designed to be used by a single reader and a single
* writer. Only writers should call the insert function. Readers may call
* anything else.
*/
template <typename ValueType, typename WeightType, size_t Size> class digest
{
using buffer = detail::
centroid_container<ValueType, WeightType, regurgitate_optimum_length>;
buffer buffer_;
using container = detail::centroid_container<ValueType, WeightType, Size>;
container a_;
container b_;
container* active_ = &a_;
std::atomic<unsigned> generation_ = 0;
/* Merge the current digest with the incoming data in the buffer. */
void merge()
{
if (buffer_.empty()) { return; }
auto scratch = buffer{};
auto* inactive = (&a_ == active_ ? &b_ : &a_);
fast_inc(generation_);
/* Add all active data to the end of the buffer */
std::copy(
active_->begin(), active_->end(), std::back_inserter(buffer_));
/* Sort the buffer in place */
ispc::sort(buffer_.means(),
buffer_.weights(),
buffer_.size(),
scratch.means(),
scratch.weights());
/* Merge buffer data and compress into the inactive container */
inactive->cursor_ = ispc::merge(buffer_.means(),
buffer_.weights(),
buffer_.size(),
inactive->means(),
inactive->weights(),
inactive->capacity());
/* Swap the containers and clean up */
std::swap(active_, inactive);
buffer_.reset();
inactive->reset();
fast_inc(generation_);
}
public:
digest()
{
/* Perform run-time benchmarking if we haven't already */
regurgitate_init();
}
digest(const digest& other)
: buffer_(other.buffer_)
, a_(other.a_)
, b_(other.b_)
, active_(other.active_ == &other.a_ ? &a_ : &b_)
{}
digest& operator=(const digest& other)
{
if (this != &other) {
buffer_ = other.buffer_;
a_ = other.a_;
b_ = other.b_;
active_ = (other.active_ == other.a_ ? &a_ : &b_);
}
return (*this);
}
digest(digest&& other) noexcept
: buffer_(std::move(other.buffer_))
, a_(std::move(other.a_))
, b_(std::move(other.b_))
, active_(other.active_ == &other.a_ ? &a_ : &b_)
{}
digest& operator=(digest&& other) noexcept
{
if (this != &other) {
buffer_ = std::move(other.buffer_);
a_ = std::move(other.a_);
b_ = std::move(other.b_);
active_ = (other.active_ == other.a_ ? &a_ : &b_);
}
return (*this);
}
inline void insert(ValueType v) { insert(v, 1); }
inline void insert(ValueType v, WeightType w)
{
buffer_.push_back(v, w);
/*
* We need to be able to add up to Size items to the buffer
* in order to merge.
*/
if (buffer_.size() >= regurgitate_optimum_length - Size) { merge(); }
}
/* Retrieve an accurate view of the current data set. */
void get_snapshot(container& snapshot) const
{
assert(snapshot.empty());
using snapshot_buffer =
detail::centroid_container<ValueType,
WeightType,
regurgitate_optimum_length + Size>;
auto data = snapshot_buffer{};
auto gen = 0U;
container* src = nullptr;
bool need_merge;
/*
* Copy data points using the generation value as a key.
* If the generation value is odd, then we read the data during a merge.
* If the generation value from the beginning doesn't match the
* generation at the end, then we read data across a merge. In either
* case, we need to restart.
*/
do {
need_merge = false;
data.reset();
gen = generation_.load(std::memory_order_acquire);
src = active_;
if (!buffer_.empty()) {
std::copy(std::begin(buffer_),
std::end(buffer_),
std::back_inserter(data));
need_merge = true;
}
std::copy(std::begin(*active_),
std::end(*active_),
std::back_inserter(data));
} while (gen % 2 || gen != generation_.load(std::memory_order_acquire));
/*
* If we read data from both the buffer and the active container,
* then we need to manually merge the data.
*/
if (need_merge) {
auto scratch = buffer{};
ispc::sort(data.means(),
data.weights(),
data.size(),
scratch.means(),
scratch.weights());
snapshot.cursor_ = ispc::merge(data.means(),
data.weights(),
data.size(),
snapshot.means(),
snapshot.weights(),
snapshot.capacity());
} else {
/* We can just copy the data out */
std::copy(
std::begin(data), std::end(data), std::back_inserter(snapshot));
}
}
std::vector<typename container::centroid> get() const
{
/* Get a snapshot... */
auto tmp = container{};
get_snapshot(tmp);
/* ... and copy it out */
auto to_return = std::vector<typename container::centroid>{};
to_return.reserve(tmp.size());
std::copy(
std::begin(tmp), std::end(tmp), std::back_inserter(to_return));
return (to_return);
}
void dump() const { active_->dump(); }
};
} // namespace regurgitate
#endif /* _LIB_REGURGITATE_HPP_ */
|
f546a756b9524fbe15ac997a8ea26e6f5391a3b7 | a01b67b20207e2d31404262146763d3839ee833d | /trunk/Projet/tags/Monofin_20090407_0.1a/Ui/parametersdialog.cpp | 4e0b54c95f4b1b8039a4f705483681cf14979c41 | [] | no_license | BackupTheBerlios/qtfin-svn | 49b59747b6753c72a035bf1e2e95601f91f5992c | ee18d9eb4f80a57a9121ba32dade96971196a3a2 | refs/heads/master | 2016-09-05T09:42:14.189410 | 2010-09-21T17:34:43 | 2010-09-21T17:34:43 | 40,801,620 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,280 | cpp | parametersdialog.cpp | #include "parametersdialog.h"
#include "../Data/stratefile.h"
#include "layerparameters.h"
#include <QFileDialog>
ParametersDialog::ParametersDialog(QWidget *parent) :
QDialog(parent)
{
setupUi(this);
for(int i=0; i<4; ++i)
m_strates.append(new StrateFile);
layerTabWidget->clear();
for(int i=0; i<m_strates.count(); ++i)
layerTabWidget->addTab(new LayerParameters, tr("layer %1").arg(i));
setConnections();
_retranslateUi();
}
void ParametersDialog::setConnections()
{
connect(browseButton, SIGNAL(clicked()), this, SLOT(chooseFile()));
}
void ParametersDialog::_retranslateUi()
{
for(int i=0; i<layerTabWidget->count(); ++i)
layerTabWidget->setTabText(i, tr("layer %1").arg(i));
retranslateUi(this);
}
void ParametersDialog::chooseFile()
{
QString dir;
if(QFile::exists(pathLineEdit->text()))
dir = pathLineEdit->text();
QString str = QFileDialog::getOpenFileName(this, QString(), dir);
if(!str.isEmpty())
pathLineEdit->setText(str);
}
void ParametersDialog::changeEvent(QEvent *e)
{
switch (e->type()) {
case QEvent::LanguageChange:
_retranslateUi();
break;
default:
break;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.