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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
25cdeda843f43a51f553e6e0ea25f69f2f842b59 | c2484df95f009d516bf042dca93857b43a292333 | /google/2015/qualification_round/b/main.cpp | 3b01f3a6264e36688e285f64637a301d26381e89 | [
"Apache-2.0"
] | permissive | seirion/code | 545a78c1167ca92776070d61cd86c1c536cd109a | a59df98712c7eeceabc98f6535f7814d3a1c2c9f | refs/heads/master | 2022-12-09T19:48:50.444088 | 2022-12-06T05:25:38 | 2022-12-06T05:25:38 | 17,619,607 | 14 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 648 | cpp | main.cpp | // https://code.google.com/codejam/contest/6224486/dashboard#s=p1
// Problem B. Infinite House of Pancakes
#include <cstdio>
#include <iostream>
using namespace std;
int in[1001];
int solve() {
int n; cin >> n;
for (int i = 0; i < n; i++) {
cin >> in[i];
}
int answer = 1000;
for (int i = 1; i <= 1000; i++) {
int minute = i;
for (int j = 0; j < n; j++) {
minute += (in[j] - 1) / i;
}
answer = min(answer, minute);
}
return answer;
}
int main() {
int t;
cin >> t;
for (int i = 1; i <= t; i++) {
printf("Case #%d: %d\n", i, solve());
}
}
|
fee93c1b6eec06c6d50543bb15719c1e8ab72702 | 465ef3d0cb1d0c8bf13ffe16a0636dae563c9a5a | /src/map/CHyperTime2D.cpp | fb11aca13d7ccc4ef85cecff507c9abffee388e7 | [] | no_license | chronorobotics/pedestrians | 99368e37eca61db6a1184be32c50ef36bf812cbf | c6ad9179826910f7e1c360d945778524629755c4 | refs/heads/master | 2021-07-18T20:24:01.236298 | 2019-09-05T14:01:37 | 2019-09-05T14:01:37 | 195,369,924 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,226 | cpp | CHyperTime2D.cpp | #include "CHyperTime2D.h"
using namespace std;
static bool quick = false;
CHyperTime2D::CHyperTime2D(const char* name,float spatialCellSize,int temporalCellSize,const char* model,int order)
{
lastError = 1000000000000;
timeDimension = 2;
covarianceType = EM::COV_MAT_GENERIC;
positives = 0;
corrective = 1.0;
order = 1;
periods.clear();
temporalScale = 10;
/*load grid info*/
FILE* file=fopen(name,"r");
long int minTime,maxTime;
float minX,maxX,minY,maxY;
fscanf(file,"%ld %ld\n",&minTime,&maxTime);
fscanf(file,"%f %f\n",&minX,&maxX);
fscanf(file,"%f %f\n",&minY,&maxY);
set(minTime,minX,minY,(int)((maxTime-minTime)/temporalCellSize),(int)((maxX-minX)/spatialCellSize),(int)((maxY-minY)/spatialCellSize),spatialCellSize,temporalCellSize);
/*fill the grid with data*/
long int time;
float x,y;
Mat sample(1,2+timeDimension,CV_32FC1);
int numPositives=0;
timeArray = (long int*)calloc(1000000,sizeof(long int));
periods.push_back(86400);
periods.push_back(86400*7);
while (feof(file)==0)
{
fscanf(file,"%ld %f %f\n",&time,&x,&y);
histogram[getCellIndex(time,x,y)]++;
sample.at<float>(0,0)=x;
sample.at<float>(0,1)=y;
sample.at<float>(0,2)=temporalScale*cos((float)time/86400*2*M_PI);
sample.at<float>(0,3)=temporalScale*sin((float)time/86400*2*M_PI);
// sample.at<float>(0,4)=temporalScale*cos((float)time/86400/7*2*M_PI);
// sample.at<float>(0,5)=temporalScale*sin((float)time/86400/7*2*M_PI);
samplesPositive.push_back(sample);
timeArray[positives++] = time;
}
fclose(file);
}
CHyperTime2D::CHyperTime2D(long int originT,float originX,float originY,int dimT,int dimX,int dimY,float spatialCellSize,int temporalCellSize)
{
set(originT,originX,originY,dimT,dimX,dimY,spatialCellSize,temporalCellSize);
}
void CHyperTime2D::set(long int originT,float originX,float originY,int dimT,int dimX,int dimY,float spatialCellSize,int temporalCellSize)
{
lastTimeStamp = 0;
minProb = 0.05;
maxProb = 1-minProb;
debug = false;
oT = originT;
oX = originX;
oY = originY;
tDim = dimT;
xDim = dimX;
yDim = dimY;
printf("%i %i %i\n",dimX,dimY,dimT);
spatialResolution = spatialCellSize;
temporalResolution = temporalCellSize;
numFrelements = yDim*xDim;
numCells = tDim*yDim*xDim;
probs = (float*) malloc(numCells*sizeof(float));
histogram = (int*) malloc(numCells*sizeof(int));
memset(histogram,0,numCells*sizeof(int));
}
CHyperTime2D::~CHyperTime2D()
{
free(histogram);
}
int CHyperTime2D::generateFromData(long int *time, float *x,float *y,int number)
{
int cellIndex = 0;
for (int i = 0;i<number;i++)
{
cellIndex = getCellIndex(time[i],x[i],y[i]);
histogram[cellIndex]++;
}
return 0;
}
void CHyperTime2D::display(bool verbose)
{
for (int s = 0;s<numFrelements;s++)
{
int i = 0;
for (int t = 0;t<tDim;t++){
i = t*xDim*yDim+s;
if (s == 63 || quick == false) {
printf("AA: %.3f %i\n",probs[i],histogram[i]);
}
}
}
}
void CHyperTime2D::update(int order)
{
float sumProb = 0;
float sumHist = 0;
for (int k = 0;k<0;k++)
{
if (!modelPositive.empty()) modelPositive.release();
modelPositive = EM::create();
modelPositive->setClustersNumber(order);
modelPositive->setCovarianceMatrixType(covarianceType);
modelPositive->setTermCriteria(TermCriteria(TermCriteria::COUNT+TermCriteria::EPS, EM::DEFAULT_MAX_ITERS, FLT_EPSILON));
modelPositive->trainEM(samplesPositive);
Mat meansPositive = modelPositive->getMeans();
std::cout << meansPositive << std::endl;
sumProb = 0;
sumHist = 0;
/*calculate relevant corrections*/
for (int it = 0;it<tDim;it++){
float t = it*temporalResolution+oT+temporalResolution/2;
for (int ix = 0;ix<xDim;ix++)
{
float x = ix*spatialResolution+oX+spatialResolution/2;
for (int iy = 0;iy<yDim;iy++)
{
float y = iy*spatialResolution+oY+spatialResolution/2;
if (histogram[getCellIndex(t,x,y)]>0) sumProb += estimate(t,x,y);
//printf("%.3f %.3f %.3f %f\n",x,y,t,estimate(t,x,y));
}
}
}
corrective = positives/sumProb;
printf("UUU: %.3f %i %f\n",sumProb,positives,corrective);
// return;
/*determine periodics*/
CFrelement fremen(0);
fremen.init(86400*7,5,1);
float sumErr = 0;
for (int it = 0;it<tDim;it++){
float t = it*temporalResolution+oT+temporalResolution/2;
for (int ix = 0;ix<xDim;ix++)
{
float x = ix*spatialResolution+oX+spatialResolution/2;
for (int iy = 0;iy<yDim;iy++)
{
float y = iy*spatialResolution+oY+spatialResolution/2;
float err = (corrective*estimate(t,x,y)-histogram[getCellIndex(t,x,y)]);
fremen.add(t,err);
sumErr += err*err;
}
}
}
sumErr = sqrt(sumErr);
fremen.update(5+1);
fremen.print(true);
if (timeDimension == 0){
for (int i = 0;i<5;i++) periods.push_back(fremen.getPredictFrelements()[i].period);
}
int period = periods[timeDimension/2];
printf("Error: %.0f, last %.0f adding period %i \n",sumErr,lastError,period);
if (lastError > sumErr){
Mat hypertimePositive(positives,2,CV_32FC1);
for (int i = 0;i<positives;i++)
{
hypertimePositive.at<float>(i,0)=temporalScale*cos((float)timeArray[i]/period*2*M_PI);
hypertimePositive.at<float>(i,1)=temporalScale*sin((float)timeArray[i]/period*2*M_PI);
}
hconcat(samplesPositive, hypertimePositive,samplesPositive);
timeDimension+=2;
}
lastError = sumErr;
}
if (!modelPositive.empty()) modelPositive.release();
modelPositive = EM::create();
modelPositive->setClustersNumber(order);
modelPositive->setCovarianceMatrixType(covarianceType);
modelPositive->setTermCriteria(TermCriteria(TermCriteria::COUNT+TermCriteria::EPS, EM::DEFAULT_MAX_ITERS, FLT_EPSILON));
modelPositive->trainEM(samplesPositive);
/*calculate relevant corrections*/
for (int it = 0;it<tDim;it++){
float t = it*temporalResolution+oT+temporalResolution/2;
for (int ix = 0;ix<xDim;ix++)
{
float x = ix*spatialResolution+oX+spatialResolution/2;
for (int iy = 0;iy<yDim;iy++)
{
float y = iy*spatialResolution+oY+spatialResolution/2;
if (histogram[getCellIndex(t,x,y)]>0) sumProb += estimate(t,x,y);
}
}
}
corrective = positives/sumProb;
printf("UUU: %.3f %i %f\n",sumProb,positives,corrective);
}
float CHyperTime2D::estimate(uint32_t t,float x,float y)
{
/*is the model valid?*/
if (modelPositive->isTrained()){
Mat sample(1,2+timeDimension,CV_32FC1);
sample.at<float>(0,0)=x;
sample.at<float>(0,1)=y;
for (int i = 0;i<timeDimension/2;i++){
sample.at<float>(0,2+i)=temporalScale*cos((float)t/periods[i]*2*M_PI);
sample.at<float>(0,3+i)=temporalScale*sin((float)t/periods[i]*2*M_PI);
}
Mat probs(1,2,CV_32FC1);
Vec2f a = modelPositive->predict(sample, probs);
return exp(a(0));
}
/*any data available?*/
return positives;
}
float CHyperTime2D::computeError(int order)
{
events = 0;
float error = 0;
FILE* file = fopen("error.pgm","w");
fprintf(file,"P2\n%i %i\n %i\n",xDim,yDim,255);
float cellError[numFrelements];
float maxCellError = 0;
for (int s = 0;s<numFrelements;s++){
cellError[s] = 0;
if (s == 63 || quick == false){
for (int t = 0;t<tDim;t++){
int i = t*xDim*yDim+s;
if (histogram[i] > 0){
cellError[s] += pow(probs[i]-histogram[i],2);
events += histogram[i];
}
}
}
//if (i%xDim == 0 && i != 0) fprintf(file,"\n");
error+=cellError[s];
//maxCellError = max(maxCellError,cellErrors[s]);
}
//fprintf(file,"%i ",(int)(cellError*255/maxHist));
fclose(file);
return sqrt(error);
}
/*void CHyperTime2D::drawError(long int time)
{
float maxHist = 0;
char filename[10];
sprintf(filename,"%05ld.pgm",time);
FILE* file = fopen(filename,"w");
for (int i = 0;i<numFrelements;i++) maxHist = max(probs[i],maxHist);
fprintf(file,"P2\n#pic at time %ld\n%i %i\n %i\n",time,xDim,yDim,255);
for (int i = 0;i<numFrelements;i++){
if (i%xDim == 0 && i != 0) fprintf(file,"\n");
fprintf(file,"%i ",(int)(probs[i+xDim*yDim*time]*255/maxHist));
}
fclose(file);
}*/
int CHyperTime2D::generateFromModel(int order,CHyperTime2D *grid)
{
if (grid == NULL) grid = this;
grid->update(order);
for (int ix = 0;ix<xDim;ix++)
{
float x = ix*spatialResolution+oX;
for (int iy = 0;iy<yDim;iy++)
{
float y = iy*spatialResolution+oY;
for (int it = 0;it<tDim;it++){
float t = it*temporalResolution+oT;
probs[getCellIndex(t,x,y)]= grid->corrective*grid->estimate(t,x,y);
}
}
}
return 0;
}
void CHyperTime2D::drawTime(long int time)
{
float maxHist = 0;
char filename[10];
sprintf(filename,"%05ld.pgm",time);
FILE* file = fopen(filename,"w");
for (int i = 0;i<numCells;i++) maxHist = max(probs[i],maxHist);
fprintf(file,"P2\n#pic at time %ld\n%i %i\n %i\n",time,xDim,yDim,255);
for (int i = 0;i<numFrelements;i++){
if (i%xDim == 0 && i != 0) fprintf(file,"\n");
fprintf(file,"%i ",(int)(probs[i+xDim*yDim*time]*255/maxHist));
}
fclose(file);
}
int CHyperTime2D::getFrelementIndex(float x,float y)
{
int iX,iY;
iX = (int)((x-oX)/spatialResolution);
iY = (int)((y-oY)/spatialResolution);
if (iX < xDim && iY < yDim && iX >= 0 && iY >=0) return iX+xDim*iY;
return 0;
}
int CHyperTime2D::getCellIndex(long int t,float x,float y)
{
int iX,iY,iT;
iT = (int)((t-oT)/temporalResolution);
iX = (int)((x-oX)/spatialResolution);
iY = (int)((y-oY)/spatialResolution);
if (iX < xDim && iY < yDim && iT < tDim && iX >= 0 && iY >=0 && iT >= 0) return iX+xDim*(iY+yDim*iT);
return 0;
}
void CHyperTime2D::save(const char* filename,bool lossy,int forceOrder)
{
FILE* f=fopen(filename,"w");
fwrite(&xDim,sizeof(int),1,f);
fwrite(&yDim,sizeof(int),1,f);
fwrite(&tDim,sizeof(long int),1,f);
fwrite(&oX,sizeof(float),1,f);
fwrite(&oY,sizeof(float),1,f);
fwrite(&oT,sizeof(long int),1,f);
fwrite(&spatialResolution,sizeof(float),1,f);
fwrite(&temporalResolution,sizeof(float),1,f);
fwrite(probs,sizeof(float),numCells,f);
// for (int i=0;i<numCells;i++) temporalArray[i]->save(f,false);
fclose(f);
}
bool CHyperTime2D::load(const char* filename)
{
int ret = 0;
FILE* f=fopen(filename,"r");
if (f == NULL){
printf("FrOctomap %s not found, aborting load.\n",filename);
return false;
}
ret += fread(&xDim,sizeof(int),1,f);
ret += fread(&yDim,sizeof(int),1,f);
ret += fread(&tDim,sizeof(long int),1,f);
ret += fread(&oX,sizeof(float),1,f);
ret += fread(&oY,sizeof(float),1,f);
ret += fread(&oT,sizeof(long int),1,f);
ret += fread(&spatialResolution,sizeof(float),1,f);
ret += fread(&temporalResolution,sizeof(float),1,f);
numCells = xDim*yDim*tDim;
numFrelements = xDim*yDim;
ret += fread(probs,sizeof(float),numCells,f);
// for (int i=0;i<numFrelements;i++) temporalArray[i]->load(f);
/*cellArray = (CFrelement**) malloc(numCells*sizeof(CFrelement*));
for (int i=0;i<numCells;i++) cellArray[i] = new CFrelement();
for (int i=0;i<numCells;i++){
cellArray[i]->load(f);
cellArray[i]->signalLength = signalLength;
}*/
printf("Loaded a grid of %i bytes with %i cells as %ix%ix%i.\n",ret,numCells,tDim,xDim,yDim);
fclose(f);
//update();
return true;
}
void CHyperTime2D::print(bool verbose)
{
//for (int i = 0;i<numFrelements;i++) temporalArray[i]->print(verbose);
//if (frelements[i].periodicities > 0)
//{
//printf("Cell: %i %i ",i,frelements[i].periodicities);
//}
}
|
f62af6922780b1225b78d9c26d82ba0b203903fe | 3d14f17273aa51c7e8c1403a8b1d53175941d0f1 | /depends/univplan/src/univplan/minmax/minmax-predicates.h | 976b9c6a8469e22a4ff6ac074ff9dd92b5dc94e7 | [
"LicenseRef-scancode-unknown",
"MIT",
"BSD-4-Clause-UC",
"BSD-3-Clause",
"ISC",
"bzip2-1.0.6",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"BSD-4-Clause",
"Artistic-2.0",
"PostgreSQL"
] | permissive | chiyang10000/hawq | 3341d705aa0b6922a6439b71bb09fced7d890066 | 74ce659bc0696faa8bb7f6943931f5a4f4daf2af | refs/heads/master | 2023-03-26T13:37:56.325334 | 2021-03-16T03:54:44 | 2021-03-17T05:33:31 | 110,235,661 | 0 | 0 | Apache-2.0 | 2021-03-02T07:16:11 | 2017-11-10T10:37:11 | C | UTF-8 | C++ | false | false | 19,060 | h | minmax-predicates.h | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#ifndef UNIVPLAN_SRC_UNIVPLAN_MINMAX_MINMAX_PREDICATES_H_
#define UNIVPLAN_SRC_UNIVPLAN_MINMAX_MINMAX_PREDICATES_H_
#include <map>
#include <memory>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>
#include "dbcommon/common/tuple-batch.h"
#include "dbcommon/common/tuple-desc.h"
#include "dbcommon/nodes/datum.h"
#include "univplan/common/expression.h"
#include "univplan/common/statistics.h"
#include "univplan/common/univplan-type.h"
#include "univplan/common/var-util.h"
namespace univplan {
class PredicateStats {
public:
PredicateStats() {}
virtual ~PredicateStats() {}
typedef std::unique_ptr<PredicateStats> uptr;
dbcommon::Scalar maxValue;
dbcommon::Scalar minValue;
bool hasAllNull = false;
bool hasMinMax = false;
};
class MinMaxPredicatesAbstract;
class MinMaxPredicatesPage;
class MinMaxPredicatesCO;
#define PREDPAGE(pred) (dynamic_cast<const MinMaxPredicatesPage*>(pred))
#define PREDCO(pred) (dynamic_cast<const MinMaxPredicatesCO*>(pred))
class PredicateOper {
public:
explicit PredicateOper(const MinMaxPredicatesAbstract* pred) : pred(pred) {}
virtual ~PredicateOper() {}
typedef std::unique_ptr<PredicateOper> uptr;
virtual bool canDrop() { return false; }
protected:
const MinMaxPredicatesAbstract* pred = nullptr;
};
class ListPredicate : public PredicateOper {
public:
ListPredicate(const univplan::UnivPlanExprPolyList* exprs,
const MinMaxPredicatesAbstract* pred);
~ListPredicate() {}
typedef std::unique_ptr<ListPredicate> uptr;
bool canDrop() override;
private:
std::vector<PredicateOper::uptr> children;
};
class BooleanPredicate : public PredicateOper {
public:
BooleanPredicate(const MinMaxPredicatesAbstract* pred,
const univplan::UnivPlanBoolExpr* op);
~BooleanPredicate() {}
typedef std::unique_ptr<BooleanPredicate> uptr;
protected:
std::vector<PredicateOper::uptr> children;
};
class VarPredicate : public PredicateOper {
public:
VarPredicate(const MinMaxPredicatesAbstract* pred,
const univplan::UnivPlanVar* var)
: PredicateOper(pred), var(var) {}
~VarPredicate() {}
typedef std::unique_ptr<VarPredicate> uptr;
bool canDrop() override;
private:
const univplan::UnivPlanVar* var;
};
class BooleanTestPredicate : public PredicateOper {
public:
BooleanTestPredicate(const MinMaxPredicatesAbstract* pred,
const univplan::UnivPlanBooleanTest* op)
: PredicateOper(pred), var(&op->arg().var()) {}
~BooleanTestPredicate() {}
typedef std::unique_ptr<BooleanTestPredicate> uptr;
protected:
const univplan::UnivPlanVar* var;
};
class IsTrueBooleanTestPredicate : public BooleanTestPredicate {
public:
IsTrueBooleanTestPredicate(const MinMaxPredicatesAbstract* pred,
const univplan::UnivPlanBooleanTest* op)
: BooleanTestPredicate(pred, op) {}
~IsTrueBooleanTestPredicate() {}
typedef std::unique_ptr<IsTrueBooleanTestPredicate> uptr;
bool canDrop() override;
};
class IsNotTrueBooleanTestPredicate : public BooleanTestPredicate {
public:
IsNotTrueBooleanTestPredicate(const MinMaxPredicatesAbstract* pred,
const univplan::UnivPlanBooleanTest* op)
: BooleanTestPredicate(pred, op) {}
~IsNotTrueBooleanTestPredicate() {}
typedef std::unique_ptr<IsNotTrueBooleanTestPredicate> uptr;
bool canDrop() override;
};
class IsFalseBooleanTestPredicate : public BooleanTestPredicate {
public:
IsFalseBooleanTestPredicate(const MinMaxPredicatesAbstract* pred,
const univplan::UnivPlanBooleanTest* op)
: BooleanTestPredicate(pred, op) {}
~IsFalseBooleanTestPredicate() {}
typedef std::unique_ptr<IsFalseBooleanTestPredicate> uptr;
bool canDrop() override;
};
class IsNotFalseBooleanTestPredicate : public BooleanTestPredicate {
public:
IsNotFalseBooleanTestPredicate(const MinMaxPredicatesAbstract* pred,
const univplan::UnivPlanBooleanTest* op)
: BooleanTestPredicate(pred, op) {}
~IsNotFalseBooleanTestPredicate() {}
typedef std::unique_ptr<IsNotFalseBooleanTestPredicate> uptr;
bool canDrop() override;
};
class IsUnknownBooleanTestPredicate : public BooleanTestPredicate {
public:
IsUnknownBooleanTestPredicate(const MinMaxPredicatesAbstract* pred,
const univplan::UnivPlanBooleanTest* op)
: BooleanTestPredicate(pred, op) {}
~IsUnknownBooleanTestPredicate() {}
typedef std::unique_ptr<IsUnknownBooleanTestPredicate> uptr;
bool canDrop() override;
};
class IsNotUnknownBooleanTestPredicate : public BooleanTestPredicate {
public:
IsNotUnknownBooleanTestPredicate(const MinMaxPredicatesAbstract* pred,
const univplan::UnivPlanBooleanTest* op)
: BooleanTestPredicate(pred, op) {}
~IsNotUnknownBooleanTestPredicate() {}
typedef std::unique_ptr<IsNotUnknownBooleanTestPredicate> uptr;
bool canDrop() override;
};
class AndPredicate : public BooleanPredicate {
public:
AndPredicate(const MinMaxPredicatesAbstract* pred,
const univplan::UnivPlanBoolExpr* op)
: BooleanPredicate(pred, op) {}
~AndPredicate() {}
typedef std::unique_ptr<AndPredicate> uptr;
bool canDrop() override;
};
class OrPredicate : public BooleanPredicate {
public:
OrPredicate(const MinMaxPredicatesAbstract* pred,
const univplan::UnivPlanBoolExpr* op)
: BooleanPredicate(pred, op) {}
~OrPredicate() {}
typedef std::unique_ptr<OrPredicate> uptr;
bool canDrop() override;
};
class NullTestPredicate : public PredicateOper {
public:
NullTestPredicate(const MinMaxPredicatesAbstract* pred,
const univplan::UnivPlanNullTest* op)
: PredicateOper(pred) {
if (!op->arg().has_var())
LOG_ERROR(ERRCODE_FEATURE_NOT_SUPPORTED,
"NullTestPredicate only work for simple expression");
univplan::VarUtil varUtil;
varAttrNo = varUtil.collectVarAttNo(
const_cast<univplan::UnivPlanExprPoly*>(&op->arg()));
}
~NullTestPredicate() {}
typedef std::unique_ptr<NullTestPredicate> uptr;
protected:
std::vector<int32_t> varAttrNo;
};
class IsNullPredicate : public NullTestPredicate {
public:
IsNullPredicate(const MinMaxPredicatesAbstract* pred,
const univplan::UnivPlanNullTest* op)
: NullTestPredicate(pred, op) {}
~IsNullPredicate() {}
typedef std::unique_ptr<IsNullPredicate> uptr;
bool canDrop() override;
};
class IsNotNullPredicate : public NullTestPredicate {
public:
IsNotNullPredicate(const MinMaxPredicatesAbstract* pred,
const univplan::UnivPlanNullTest* op)
: NullTestPredicate(pred, op) {}
~IsNotNullPredicate() {}
typedef std::unique_ptr<IsNotNullPredicate> uptr;
bool canDrop() override;
};
class CompPredicate : public PredicateOper {
public:
CompPredicate(const MinMaxPredicatesAbstract* pred,
const univplan::UnivPlanOpExpr* op)
: PredicateOper(pred), expr(op) {
assert(op->args_size() == 2);
typeKinds.push_back(univplan::PlanNodeUtil::exprType(op->args(0)));
typeKinds.push_back(univplan::PlanNodeUtil::exprType(op->args(1)));
univplan::VarUtil varUtil;
varAttNo.push_back(varUtil.collectVarAttNo(
const_cast<univplan::UnivPlanExprPoly*>(&op->args(0))));
varAttNo.push_back(varUtil.collectVarAttNo(
const_cast<univplan::UnivPlanExprPoly*>(&op->args(1))));
}
~CompPredicate() {}
typedef std::unique_ptr<CompPredicate> uptr;
void addArg(ExprState::uptr arg) { args.push_back(std::move(arg)); }
bool isValidToPredicate() const;
protected:
PredicateStats::uptr calcLeft();
PredicateStats::uptr calcRight();
int32_t compareTo(const dbcommon::Scalar& s1, dbcommon::TypeKind t1,
const dbcommon::Scalar& s2, dbcommon::TypeKind t2);
private:
dbcommon::TupleBatch::uptr buildTupleBatch(int32_t argIndex);
PredicateStats::uptr doCalc(int32_t argIndex);
std::string covertPredicateTypeStr(std::string typeName);
protected:
std::vector<dbcommon::TypeKind> typeKinds;
const univplan::UnivPlanOpExpr* expr;
private:
std::vector<ExprState::uptr> args;
std::vector<std::vector<int32_t>> varAttNo;
dbcommon::Timestamp minTimestamp;
dbcommon::Timestamp maxTimestamp;
std::vector<dbcommon::TupleBatch::uptr> tbVec_;
};
class EqualPredicate : public CompPredicate {
public:
EqualPredicate(const MinMaxPredicatesAbstract* pred,
const univplan::UnivPlanOpExpr* op)
: CompPredicate(pred, op) {}
~EqualPredicate() {}
typedef std::unique_ptr<EqualPredicate> uptr;
bool canDrop() override;
};
class NEPredicate : public CompPredicate {
public:
NEPredicate(const MinMaxPredicatesAbstract* pred,
const univplan::UnivPlanOpExpr* op)
: CompPredicate(pred, op) {}
~NEPredicate() {}
typedef std::unique_ptr<NEPredicate> uptr;
bool canDrop() override;
};
class GTPredicate : public CompPredicate {
public:
GTPredicate(const MinMaxPredicatesAbstract* pred,
const univplan::UnivPlanOpExpr* op)
: CompPredicate(pred, op) {}
~GTPredicate() {}
typedef std::unique_ptr<GTPredicate> uptr;
bool canDrop() override;
};
class GEPredicate : public CompPredicate {
public:
GEPredicate(const MinMaxPredicatesAbstract* pred,
const univplan::UnivPlanOpExpr* op)
: CompPredicate(pred, op) {}
~GEPredicate() {}
typedef std::unique_ptr<GEPredicate> uptr;
bool canDrop() override;
};
class LTPredicate : public CompPredicate {
public:
LTPredicate(const MinMaxPredicatesAbstract* pred,
const univplan::UnivPlanOpExpr* op)
: CompPredicate(pred, op) {}
~LTPredicate() {}
typedef std::unique_ptr<LTPredicate> uptr;
bool canDrop() override;
};
class LEPredicate : public CompPredicate {
public:
LEPredicate(const MinMaxPredicatesAbstract* pred,
const univplan::UnivPlanOpExpr* op)
: CompPredicate(pred, op) {}
~LEPredicate() {}
typedef std::unique_ptr<LEPredicate> uptr;
bool canDrop() override;
};
class MinMaxPredicatesAbstract {
public:
MinMaxPredicatesAbstract(const univplan::UnivPlanExprPolyList* predicateExprs,
const dbcommon::TupleDesc* tupleDesc)
: exprs(predicateExprs), td(tupleDesc) {}
virtual ~MinMaxPredicatesAbstract() {}
// facility for building general purpose predicate tree
static PredicateOper::uptr buildPredicateOper(
const univplan::UnivPlanExprPolyList* exprs,
const MinMaxPredicatesAbstract* owner);
static PredicateOper::uptr buildPredicateOper(
const univplan::UnivPlanExprPoly* expr,
const MinMaxPredicatesAbstract* owner);
const dbcommon::TupleDesc* getTupleDesc() const { return td; }
protected:
const univplan::UnivPlanExprPolyList* exprs; // original pushed filter
const dbcommon::TupleDesc* td; // full tuple desc
PredicateOper::uptr predicate; // generated predicate
};
class MinMaxPredicatesPage : public MinMaxPredicatesAbstract {
public:
MinMaxPredicatesPage(const Statistics* s,
const univplan::UnivPlanExprPolyList* predicateExprs,
const dbcommon::TupleDesc* tupleDesc)
: MinMaxPredicatesAbstract(predicateExprs, tupleDesc), stripeStats(s) {}
virtual ~MinMaxPredicatesPage() {}
typedef std::unique_ptr<MinMaxPredicatesPage> uptr;
virtual bool canDrop(); // page level min-max calculation interface
public:
virtual bool hasNull(int32_t colId) const = 0;
virtual bool hasAllNull(int32_t colId) const = 0;
virtual bool canDropByBloomFilter(int32_t colId, PredicateStats* stat,
dbcommon::TypeKind type) const = 0;
virtual PredicateStats getMinMax(int32_t colId) const = 0;
virtual PredicateStats getMinMax(int32_t colId,
dbcommon::Timestamp* minTimestamp,
dbcommon::Timestamp* maxTimestamp) const = 0;
protected:
const Statistics* stripeStats;
};
class COBlockTask {
public:
COBlockTask(uint64_t offset, uint64_t beginRowId, uint64_t rowCount)
: offset(offset),
beginRowId(beginRowId),
rowCount(rowCount),
taskBeginRowId(beginRowId),
taskRowCount(rowCount),
lastTaskBeginRowId(0),
lastTaskRowCount(0),
intersected(false) {}
COBlockTask(uint64_t offset, uint64_t beginRowId, uint64_t rowCount,
uint64_t taskBeginRowId, uint64_t taskRowCount)
: offset(offset),
beginRowId(beginRowId),
rowCount(rowCount),
taskBeginRowId(taskBeginRowId),
taskRowCount(taskRowCount),
lastTaskBeginRowId(0),
lastTaskRowCount(0),
intersected(false) {
LOG_DEBUG("CO block task %llu %llu %llu %llu %llu", offset, beginRowId,
rowCount, taskBeginRowId, taskRowCount);
}
typedef std::unique_ptr<COBlockTask> uptr;
public:
inline uint64_t getEndRowId() const { return beginRowId + rowCount - 1; }
inline uint64_t getTaskEndRowId() const {
return taskBeginRowId + taskRowCount - 1;
}
inline uint64_t getLastTaskEndRowId() const {
return lastTaskBeginRowId + lastTaskRowCount - 1;
}
inline void resetIntersection() {
intersected = false;
lastTaskBeginRowId = taskBeginRowId;
lastTaskRowCount = taskRowCount;
taskRowCount = 0;
}
inline void resetUnionAll() {
lastTaskBeginRowId = taskBeginRowId;
lastTaskRowCount = taskRowCount;
}
inline void intersect(const COBlockTask& srcTask) {
if (srcTask.getTaskEndRowId() < lastTaskBeginRowId ||
srcTask.taskBeginRowId > this->getLastTaskEndRowId()) {
if (!intersected) {
if (srcTask.getEndRowId() < this->lastTaskBeginRowId) {
// does not touch existing job, so restore original version
taskBeginRowId = lastTaskBeginRowId;
taskRowCount = lastTaskRowCount;
intersected = true;
} else if (srcTask.getEndRowId() <= this->getLastTaskEndRowId()) {
// restore partial job
taskBeginRowId = srcTask.getEndRowId() + 1;
taskRowCount = this->getLastTaskEndRowId() - taskBeginRowId + 1;
intersected = true;
}
return;
}
}
if (!intersected) {
// fix task begin row id, the source task may have smaller task begin row
// id, thus check to make sure this task has valid task begin row id. end
// row id has the same problem as well.
taskBeginRowId = srcTask.taskBeginRowId < taskBeginRowId
? taskBeginRowId
: srcTask.taskBeginRowId;
uint64_t tmpTaskEndRowId = srcTask.getTaskEndRowId();
tmpTaskEndRowId = tmpTaskEndRowId > this->getLastTaskEndRowId()
? this->getLastTaskEndRowId()
: tmpTaskEndRowId;
taskRowCount = tmpTaskEndRowId - taskBeginRowId + 1;
intersected = true;
} else {
// dont check begin row id again, as we expect srce tasks are processed
// in ascending order, and we use last task row id range to perform
// intersection
uint64_t tmpTaskEndRowId = srcTask.getTaskEndRowId();
tmpTaskEndRowId = tmpTaskEndRowId > this->getLastTaskEndRowId()
? this->getLastTaskEndRowId()
: tmpTaskEndRowId;
taskRowCount = tmpTaskEndRowId - taskBeginRowId + 1;
}
}
inline void unionAll(const COBlockTask& srcTask) {
if (srcTask.getTaskEndRowId() < beginRowId ||
srcTask.taskBeginRowId > this->getEndRowId()) {
// skip this part, as no overlap in row id range
return;
}
// we always check its possible new begin rowid and it should not go out of
// current task range
taskBeginRowId = taskBeginRowId > srcTask.taskBeginRowId
? srcTask.taskBeginRowId
: taskBeginRowId;
taskBeginRowId = taskBeginRowId < beginRowId ? beginRowId : taskBeginRowId;
// then is its end rowid
uint64_t tmpTaskEndRowId = srcTask.getTaskEndRowId();
tmpTaskEndRowId = tmpTaskEndRowId > this->getTaskEndRowId()
? tmpTaskEndRowId
: this->getTaskEndRowId();
tmpTaskEndRowId = tmpTaskEndRowId > this->getEndRowId()
? this->getEndRowId()
: tmpTaskEndRowId;
taskRowCount = tmpTaskEndRowId - taskBeginRowId + 1;
}
public:
uint64_t offset;
uint64_t beginRowId;
uint64_t rowCount;
uint64_t taskBeginRowId;
uint64_t taskRowCount;
uint64_t lastTaskBeginRowId;
uint64_t lastTaskRowCount;
private:
bool intersected;
};
class COBlockTaskList {
public:
COBlockTaskList();
void add(COBlockTask::uptr task) {
uint64_t taskBeginRowId = task->taskBeginRowId;
taskList[taskBeginRowId] = std::move(task);
}
void intersect(const COBlockTaskList& source);
void unionAll(const COBlockTaskList& source);
typedef std::unique_ptr<COBlockTaskList> uptr;
public:
std::map<uint64_t, COBlockTask::uptr> taskList;
};
class MinMaxPredicatesCO : public MinMaxPredicatesAbstract {
public:
MinMaxPredicatesCO(const univplan::UnivPlanExprPolyList* predicateExprs,
const dbcommon::TupleDesc* tupleDesc)
: MinMaxPredicatesAbstract(predicateExprs, tupleDesc) {}
virtual ~MinMaxPredicatesCO() {}
// methods implemented by sub-class to provide customized data preparation
virtual void preparePredicatesForStrip() = 0;
virtual COBlockTask::uptr buildCOTaskFromCurrentStrip(int colId) = 0;
// methods of whole calculation framework
virtual void preparePredicates();
virtual void calculate(std::unordered_map<int, COBlockTaskList::uptr>* res);
protected:
// holding one strip's statistics
std::unique_ptr<univplan::Statistics> stripStatistics;
// holding one page level predicates to do actual calculation
std::unique_ptr<MinMaxPredicatesPage> predicatesForPages;
};
} // namespace univplan
#endif // UNIVPLAN_SRC_UNIVPLAN_MINMAX_MINMAX_PREDICATES_H_
|
e358e546e5c32cca404b19a522b04c294dbd8bb9 | e46bd22112c15d9558ad9531deef183849636d62 | /LeetCode/30-Day Challenge/November/Week 4.7 Sliding Window Maximum.cpp | 251390fc56fdfdf675029188e2803b19103a67ba | [] | no_license | jariasf/Online-Judges-Solutions | 9082b89cc6d572477dbfb89ddd42f81ecdb2859a | 81745281bd0099b8d215754022e1818244407721 | refs/heads/master | 2023-04-29T20:56:32.925487 | 2023-04-21T04:59:27 | 2023-04-21T04:59:27 | 11,259,169 | 34 | 43 | null | 2020-10-01T01:41:21 | 2013-07-08T16:23:08 | C++ | UTF-8 | C++ | false | false | 1,148 | cpp | Week 4.7 Sliding Window Maximum.cpp | /*******************************************
***Problema: Sliding Window Maximum
***ID: Week4.7
***Juez: LeetCode
***Tipo: Sliding Window + Deque
***Autor: Jhosimar George Arias Figueroa
*******************************************/
class Solution {
public:
#define pii pair<int,int>
#define mp make_pair
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
vector<int> result;
int n = nums.size();
if( n == 0 ) return result;
if( k == 1 ) return nums;
deque<pii> Q;
for( int i = 0 ; i < k ; ++i ){
while( !Q.empty() && Q.back().first < nums[i] ){
Q.pop_back();
}
Q.push_back( mp(nums[i],i));
}
result.push_back(Q.front().first);
for( int i = k, left = 0 ; i < n ; ++i, ++left ){
if( !Q.empty() && Q.front().second == left ) Q.pop_front();
while( !Q.empty() && Q.back().first < nums[i] ){
Q.pop_back();
}
Q.push_back( mp(nums[i],i));
result.push_back(Q.front().first);
}
return result;
}
};
|
3e886b9f171c02fe9163094604a3d4e152114965 | f72c5434750740d01b046c2227baf88349112911 | /CSES/dp/rectanglesCutting.cpp | 72e597ebba9ddf80a7095f5bd698077fdd726802 | [] | no_license | urishabh12/practice | 00145e024daccacc3f631fae3671951f9e2d6f5a | 17143214a024b87a76afc6b4c33b8725885a78a1 | refs/heads/master | 2022-12-27T02:23:09.406093 | 2021-07-10T06:50:12 | 2021-07-10T06:50:12 | 193,316,611 | 0 | 0 | null | 2022-12-14T04:46:18 | 2019-06-23T06:59:51 | Jupyter Notebook | UTF-8 | C++ | false | false | 1,269 | cpp | rectanglesCutting.cpp | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
vector<vector<int>> dp(501, vector<int>(501, 1e9));
int solve(int a, int b)
{
if (a == b)
{
return 0;
}
if (dp[a][b] != 1e9)
{
return dp[a][b];
}
for (int i = 1; i < a; i++)
{
dp[a][b] = min(dp[a][b], 1 + solve(a - i, b) + solve(i, b));
}
for (int i = 1; i < b; i++)
{
dp[a][b] = min(dp[a][b], 1 + solve(a, b - i) + solve(a, i));
}
return dp[a][b];
}
int iter(int a, int b)
{
for (int i = 1; i <= a; i++)
{
for (int j = 1; j <= b; j++)
{
if (i == j)
{
dp[i][j] = 0;
}
else
{
for (int k = 1; k < i; k++)
{
dp[i][j] = min(dp[i][j], 1 + dp[i - k][j] + dp[k][j]);
}
for (int k = 1; k < j; k++)
{
dp[i][j] = min(dp[i][j], 1 + dp[i][j - k] + dp[i][k]);
}
}
}
}
return dp[a][b];
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(0);
int a, b;
cin >> a >> b;
int ans = iter(a, b);
cout << ans << '\n';
return 0;
}
|
39e0e5636105b4c0ddb83b84e1fb628f403adec9 | 82347d3003e4c19b5ca312cac3db829583cdfc21 | /src/baserobotctrl.h | dbf4fd39666c026cb543a04237375d1a5a209ddc | [] | no_license | jwawerla/ifd | 8598fb50371c2164c381ab9a7b52cb10351cfaa6 | e37a91f0e558758602870c11a83773697a96a2ac | refs/heads/master | 2021-01-02T08:09:54.445837 | 2009-11-10T15:59:35 | 2009-11-10T15:59:35 | 316,068 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,087 | h | baserobotctrl.h | /***************************************************************************
* Project: IFD *
* Author: Jens Wawerla (jwawerla@sfu.ca) *
* $Id: $
***************************************************************************
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
**************************************************************************/
#ifndef BASEROBOTCTRL_H
#define BASEROBOTCTRL_H
#include "RapiLooseStage"
#include "pathplannerlookup.h"
#include "patchinterface.h"
#include "robotctrlinterface.h"
#include <list>
#include <vector>
using namespace Rapi;
/** Type definition for FSM */
typedef enum {START = 0, SW_PATCH, FORAGE, CHOOSE_PATCH,
ROTATE90, RETURN_TO_PATCH_RND, RETURN_TO_PATCH,
NUM_STATES} tState;
/** Type definition for action results */
typedef enum {COMPLETED, IN_PROGRESS, FAILED } tActionResult;
/**
* Base class for all robots
* @author Jens Wawerla
*/
class ABaseRobotCtrl : public ARobotCtrl, public IRobotCtrl
{
public:
/**
* Default constructor
*/
ABaseRobotCtrl( ARobot* robot );
/** Default destructor */
virtual ~ABaseRobotCtrl();
/**
* Update function called by the RAPI
* @param dt size of time step [s]
*/
virtual void updateData( float dt );
/**
* Adds a patch to the list of patches
* @param patch to be added
*/
void addPatch( IPatch* patch );
/**
* Gets the robots current pose
* @return pose
*/
virtual CPose2d getPose() const;
protected:
/**
* Should we leave the current patch or not
* @return true if we should leave, false otherwise
*/
virtual bool patchLeavingDecision();
/**
* Action selects a patch at random
* @return action result
*/
virtual tActionResult actionSelectPatch();
/**
* Action randomly forages for pucks in a given patch
* @param dt time step size [s]
* @return action result
*/
virtual tActionResult actionForage( float dt );
/**
* This function gets called by the controller every time puck is collected
*/
virtual void puckCollectedEvent();
/**
* Event called when a patch is entered
*/
virtual void patchEnteringEvent();
/**
* Checks if the robot is making progress moving around, or if it is stuck
* in some behavioural loop
* @return true if making progress, false if stuck
*/
bool isMakingProgress();
/**
* Checks in robot is currently in a corridor
* @return true if in corridor, false otherwise
*/
inline bool inCorridor() {
if (( mLaser->mRangeData[0].range +
mLaser->mRangeData[mLaser->getNumSamples()-1].range ) < 2.7 )
return true;
return false;
};
/**
* Checks if the robot is within the patch
* @return true if in patch, false otherwise
*/
bool inPatch() const;
/** Current pose of robot */
CPose2d mRobotPose;
/** List of patches */
std::vector<IPatch*> mPatchVector;
/** Flags if the state of the FSM has changed */
bool mFgStateChanged;
/** Current patch */
IPatch* mCurrentPatch;
/** State of FSM */
tState mState;
/** Elapsed time since the current state was entered [s] */
float mElapsedStateTime;
/** Logger */
CDataLogger* mDataLogger;
/** Number of pucks collected */
int mNumPucksCollected;
/** Patch residence time for the current patch [s] */
float mPatchResidenceTime;
private:
/** Previous state */
tState mPrevState;
/** Current waypoint */
CWaypoint2d mCurrentWaypoint;
/** Path planner */
CPathPlannerLookup* mPathPlanner;
/** List of way points */
std::list<CWaypoint2d> mWaypointList;
/** Stage gripper model */
Stg::ModelGripper* mGripper;
/** Stage position model */
CLooseStageDrivetrain2dof* mDrivetrain;
/** Stage laser model */
CLooseStageLaser* mLaser;
/** Stage blobfinder model */
CLooseStageBlobFinder* mBlobFinder;
/** Stage power pack */
CLooseStagePowerPack* mPowerPack;
/** Stage fiducial model */
//CLooseStageFiducialFinder* mFiducial;
/** Text display */
CLooseStageTextDisplay* mTextDisplay;
/** General purpose counter */
int mCounter;
/** Current velocity of robot */
CVelocity2d mRobotVelocity;
/** Counter for obstacle avoidance [steps] */
int mAvoidCount;
/** Counter to determine when it is time to replan */
int mReplanCounter;
/** Single word describtion of FSM states */
std::string mFsmText[NUM_STATES];
/** String for status messages */
std::string mStatusStr;
/** Robot pose to measure progress */
CPose2d mRobotProgressPose;
/** Timer for measuring progress */
CTimer* mProgressTimer;
/** Flags if we make progress or not */
bool mFgProgress;
/** Heading for rotatign 90 deg [rad] */
float mHeading;
/** Right front laser reading [m] */
float mRightFrontDistance;
/** Last switching time (cost) [s] */
float mSwitchingTime;
/**
* Action selects the inital patch at random
* @return action result
*/
virtual tActionResult actionSelectInitialPatch();
/**
* Action randomly returns the robot to the current patch
* @return action result
*/
tActionResult actionReturnToPatch();
/**
* Action drives the robot along the waypoint list
* @return action result
*/
tActionResult actionFollowWaypointList();
/**
* Action causes the robot to rotate 90 deg
* @return action result
*/
tActionResult actionRotate90();
/**
* Transfer waypoints to stages position device
*/
void transferWaypointToStage();
/**
* Avoid obstacles and move to current waypoint
* @return true if still avoiding obstacles, false if no obstacles have
* to be avoided
*/
bool obstacleAvoid();
};
#endif
|
0e5ff092e31052e0e78f69593940e73bb28b0ac4 | bdcb92c759d9af3ee4b115989a2a82db1194f64f | /EventObserver.cpp | c22fa9c1e5374d44086e1e2407bb49ed8c5d9b2c | [] | no_license | robre22/FlyingDot | 78f21093200c174d09fc09fff4d2fe2582989275 | c748f8a220bf2038fe775132e98d8e35c0271f9e | refs/heads/master | 2021-05-12T02:50:03.349037 | 2018-02-16T10:46:37 | 2018-02-16T10:46:37 | 117,601,190 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 525 | cpp | EventObserver.cpp | #include "EventObserver.h"
#include "Player.h"
#include "Canvas.h"
#include <iostream>
EventObserver::EventObserver(Player* pPlayer,Canvas* pCanvas)
:m_pPlayer(pPlayer),m_pCanvas(pCanvas)
{
}
EventObserver::~EventObserver()
{
}
void EventObserver::onNotify()
{
float fPosX,fPosY;
m_pPlayer->getPos(fPosX,fPosY);
if(fPosY <= -1.0f)//lose the game
{
std::cout << " You lose the game! Press UP to start again!" << std::endl;
m_pPlayer->setState(Player::State::GAME_OVER);
m_pCanvas->m_isRunning = false;
}
} |
adceae1925a5227531dcf363b31cd279d4664a2a | 704008c5ad0c3c2bdcb3f01fe173580b1c42eee9 | /C++11/C++11生产者消费者模型.cpp | b5910f8da13212da54f73c2c99f5d9eb81c53969 | [] | no_license | BeHappyBeAlive/notes-for-cpp | 8406d30b7a2e395af3fb1345d530be9d31904169 | 851c0473609e476640ad1b418ede2c87a9165f65 | refs/heads/main | 2023-07-23T10:04:39.710202 | 2021-08-29T17:31:04 | 2021-08-29T17:31:04 | 398,747,090 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,483 | cpp | C++11生产者消费者模型.cpp | #include<iostream>
#include<thread>
#include<mutex>
#include<condition_variable> // 条件变量
#include<queue> // C++ STL所有的容器都不是线程安全的
using namespace std;
/*
C++多线程编程 - 线程间的同步通信机制
多线程编程两个问题:
1. 线程间的互斥
竞态条件 =》 临界区代码段 =》 原子操作 =》 线程互斥锁mutex 轻量级的无锁实现CAS
strace ./a.out mutex => pthread_mutex_t
2. 线程间的同步通信
生产者、消费者线程模型
*/
std::mutex mtx; // 定义互斥锁
std::condition_variable cv; //定义条件变量,做线程间的同步通信操作
// 生产者生产一个物品,通知消费者消费一个;消费完了之后,消费者通知生产者继续生产
class Queue {
public:
void put(int val) { // 生产物品
//lock_guard<std::mutex> guard(mtx); //scoped_ptr
unique_lock<std::mutex> lck(mtx); // unique_ptr
while (!que.empty()) {
// que不为空,生产者应该通知消费者去消费,消费完了再生产
// 生产者线程应该进入阻塞#1等待状态,并且#2把mtx互斥锁释放掉
cv.wait(lck);
}
que.push(val);
/*
notify_one:通知另外一个线程
notify_all:通知其他所有线程
通知其他线程我生产了一个物品,赶快消费
其他线程得到该通知,就会从等待状态 =》 阻塞状态 =》 获取互斥锁才能继续执行
*/
cv.notify_all();
cout << "生产者 生产:" << val << "号物品" << endl;
}
int get() { // 消费物品
//lock_guard<std::mutex> guard(mtx);
unique_lock<std::mutex> lck(mtx);
while (que.empty()) {
//消费者发现que为空,通知生产者线程先生产物品
//#1 进入等待状态 #2 把互斥锁mutex释放掉
cv.wait(lck);
}
int val = que.front();
que.pop();
cv.notify_all(); //通知其他线程我消费完了,赶快生产吧
cout << "消费者 消费:" << val << "号物品" << endl;
return val;
}
private:
queue<int> que;
};
void producer(Queue *que) //生产者线程
{
for (int i = 1; i <= 10; ++i)
{
que->put(i);
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
}
void consumer(Queue* que) //消费者线程
{
for (int i = 1; i <= 10; ++i)
{
que->get();
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
}
int main() {
Queue que; // 两个线程共享的队列
std::thread t1(producer, &que);
std::thread t2(consumer, &que);
t1.join();
t2.join();
}
|
f907da7751d95869244169d09e2384b0c931899b | 132cb81550b5a18abbcf4b21717b8f3e2017b3b4 | /include/Han/DebugGuiLayer.hpp | 38cedfe86e6f3a7d63d698f8cde3a7fd951ef0c8 | [] | no_license | leohahn/han | e0ff38f6772d0f15968fd188dde5b446069ea90c | 1f3837075b67e5860c76f8e497ae16d0cde71875 | refs/heads/master | 2020-04-22T02:27:49.331440 | 2019-10-04T02:41:53 | 2019-10-04T02:41:53 | 170,050,083 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 592 | hpp | DebugGuiLayer.hpp | #pragma once
#include "Han/Layer.hpp"
class DebugGuiLayer : public Layer
{
public:
DebugGuiLayer()
: Layer(String("DebugGui"))
{}
void OnAttach() override;
void OnDetach() override;
void OnUpdate(DeltaTime delta) override;
void OnEvent(Event& ev) override;
private:
bool OnMouseButtonPress(MouseButtonPressEvent& ev);
bool OnKeyPress(KeyPressEvent& ev);
bool OnKeyRelease(KeyReleaseEvent& ev);
bool OnMouseWheel(MouseWheelEvent& ev);
bool OnMouseMove(MouseMoveEvent& ev);
bool OnMouseButtonRelease(MouseButtonReleaseEvent& ev);
bool OnTextInputEvent(TextInputEvent& ev);
}; |
7bc1ddd74aa6836b3bcd2805497c6e8c8d16d3d4 | 795de5afea1a2d0174c9d8834c513739a337ba8d | /4. Random variables/dice2.cpp | 6d2546cc29f11a040a4d91c6e937ef049f06c9f3 | [] | no_license | Myung-Hyun/SW-Lab-Cpp | b36fd3595cd8a2d811eca8dcca3ab9e08d8fe40a | 1a77a8f15877e17d8ad11fa15e6d636abf45168b | refs/heads/master | 2022-12-20T14:21:04.324831 | 2020-10-18T07:04:26 | 2020-10-18T07:04:26 | 299,815,276 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,223 | cpp | dice2.cpp |
#include <iostream>
#include <cstdlib> // for rand()
#include <ctime>
#include <fstream>
#include <random> // gaussian
#include <math.h>
using namespace std;
int main()
{
ofstream my_out("out.txt");
default_random_engine generator;
normal_distribution<double> myGauss(350.0, 17.07);
int y[501], Ntry=300000;
for (int i = 0;i < 501;i++)
{
y[i] = 0;
}
for (int i = 0; i < Ntry; i++)
{
double number = myGauss(generator);
int quant = round(number); //quantization
y[quant - 100]++;
}
for (int i = 0; i < 501;i++)
{
my_out << y[i] << endl;
}
/*
ofstream my_out("out.txt");
srand((unsigned int)time(NULL));
int y[501], Ntry = 100000;
for (int i = 0;i < 501;i++)
{
y[i] = 0;
}
float std_deviation = 0;
for (int j = 0; j < Ntry; j++)
{
int y_sum = 0; // 초기화 위치 중요함.
for (int i = 0; i < 100; i++)
{
int temp = ((rand() % 6) + 1);
y_sum += temp; // 100~600 인 RV y 생성
}
std_deviation += pow((y_sum - 350), 2);
y[y_sum - 100]++;
}
std_deviation = std_deviation / (float)Ntry; // 표준편차: 편차 제곱의 평균을 제곱근 씌운 것.
cout << sqrt(std_deviation);
for (int i = 0; i < 501;i++)
{
my_out << y[i] << endl;
}*/
return 0;
}
// 프로그램 실행: <Ctrl+F5> 또는 [디버그] > [디버깅하지 않고 시작] 메뉴
// 프로그램 디버그: <F5> 키 또는 [디버그] > [디버깅 시작] 메뉴
// 시작을 위한 팁:
// 1. [솔루션 탐색기] 창을 사용하여 파일을 추가/관리합니다.
// 2. [팀 탐색기] 창을 사용하여 소스 제어에 연결합니다.
// 3. [출력] 창을 사용하여 빌드 출력 및 기타 메시지를 확인합니다.
// 4. [오류 목록] 창을 사용하여 오류를 봅니다.
// 5. [프로젝트] > [새 항목 추가]로 이동하여 새 코드 파일을 만들거나, [프로젝트] > [기존 항목 추가]로 이동하여 기존 코드 파일을 프로젝트에 추가합니다.
// 6. 나중에 이 프로젝트를 다시 열려면 [파일] > [열기] > [프로젝트]로 이동하고 .sln 파일을 선택합니다.
|
47fb6e03f70b522ca6d41f6a1cc123379d723c9f | 5eae9247f28c05539173ffafb3d243b6e806b1b0 | /ElectronicSystems/DeterministicAnalysis/+Utils/constructHotSpot.cpp | 239c472ee078a8d585538c24d07ff8a3ac5c61fd | [
"MIT"
] | permissive | hilbert-space/MathRocks | 2f077d73757c31be627af55fc4d125dc6d6195ce | f4ea67d4d9dfab5d9cfeee9e3dbd75bd6e95da80 | refs/heads/master | 2021-09-26T08:51:10.305446 | 2018-10-28T13:51:55 | 2018-10-28T13:51:55 | 22,913,563 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,095 | cpp | constructHotSpot.cpp | #include <mex_utils.h>
#include <HotSpot.h>
using namespace std;
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
string floorplan_file = from_matlab<string>(prhs[0]);
string config_file = from_matlab<string>(prhs[1]);
string config_line = from_matlab<string>(prhs[2]);
HotSpot hotspot(floorplan_file, config_file, config_line);
size_t processor_count = hotspot.get_processor_count();
size_t node_count = hotspot.get_node_count();
mxArray *A = mxCreateDoubleMatrix(node_count, 1, mxREAL);
mxArray *B = mxCreateDoubleMatrix(node_count, node_count, mxREAL);
mxArray *G = mxCreateDoubleMatrix(node_count, node_count, mxREAL);
mxArray *G_amb = mxCreateDoubleMatrix(processor_count + EXTRA, 1, mxREAL);
double *_A = mxGetPr(A);
double *_B = mxGetPr(B);
double *_G = mxGetPr(G);
double *_G_amb = mxGetPr(G_amb);
hotspot.get_A(_A);
hotspot.get_B(_B);
hotspot.get_G(_G);
hotspot.get_G_amb(_G_amb);
cross_matlab(_B, node_count, node_count);
cross_matlab(_G, node_count, node_count);
plhs[0] = A;
plhs[1] = B;
plhs[2] = G;
plhs[3] = G_amb;
}
|
38680fc037311f575725f65a4b5ea33fd12c749d | ea11886c946f0998d1eb7e9b61047d54d1eb245e | /Classes/smartfish/smash/time/AnimatedComponent.h | b0942cf6c2e199a6b21f714d66528617b280819a | [] | no_license | edwardandy/KylinMobile | 6a9b41c674f70c62db66dc44e8984ccd864752db | fc6fa4b14616444c5440a4824ddebed82f384088 | refs/heads/master | 2021-01-22T09:09:08.840775 | 2014-02-07T15:04:36 | 2014-02-07T15:04:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 923 | h | AnimatedComponent.h | // AnimatedComponent.h
// Smash
//
// Created by Luke on 13-3-20.
//
//
#ifndef __Smash__AnimatedComponent__
#define __Smash__AnimatedComponent__
#include <iostream>
#include "../core/SmashMacros.h"
#include "../core/EntityComponent.h"
NS_SF_BEGIN
class AnimatedComponent : public EntityComponent {
public:
AnimatedComponent( );
virtual ~AnimatedComponent( );
bool get_registerForUpdates( );
void set_registerForUpdates( bool value );
virtual void onFrame( float deltaTime );
virtual void onAdd( );
virtual void onRemove( );
/**
* The update priority for this component. Higher numbered priorities have
* onInterpolateTick and onTick called before lower priorities.
*/
float updatePriority;
private:
bool registerForUpdates;
protected:
virtual void onStop( );
virtual void onResume( );
};
NS_SF_END
#endif /* defined(__Smash__AnimatedComponent__) */
|
2d235887e31aae110cdf8544a2e226de450206a2 | 9e30313d5f67e7cdfe0f3710a3ab98b90af1fbb3 | /Zork/Zork/Item.cpp | 9f845e361f0b992f3cbc2a4c385c77c20010798f | [
"MIT"
] | permissive | JoanStinson/Zork | 3388819b7e71ab663723b8079790d006b4a69fe7 | d8f869a5d0935e1f38d9e05a5863efcc1000077c | refs/heads/master | 2022-10-05T15:57:17.769119 | 2022-09-16T17:28:09 | 2022-09-16T17:28:09 | 192,528,780 | 6 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 77 | cpp | Item.cpp | #include "Item.h"
ItemType Item::GetItemType() const {
return itemType;
}
|
63010dd423c2b409c8c7fd7ed5eb9a641f0aa9aa | 23562908ceff614f2864bf03eeb70b4a506f3834 | /src/Source.cpp | 6ba05a9a86b9cdb3e2be74a38999b310028b2d40 | [
"MIT"
] | permissive | unknu/VpkPacker | 009f605711ca6ab94af13f8ede3c6ff55e9c0248 | 8498b75b3b167fa000f7f14255266cdc7d741c6a | refs/heads/master | 2021-01-12T18:26:36.436677 | 2016-11-02T01:07:43 | 2016-11-02T01:07:43 | 71,377,455 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 669 | cpp | Source.cpp | #include <psp2/kernel/processmgr.h>
#include <psp2/sysmodule.h>
#include "Header.h"
int main( int argc, char *argv[] )
{
vita2d_init();
vita2d_set_clear_color( RGBA_BLACK );
// sceIoSetPriority
VpkPacker::Unity u;
while( 1 ) {
if(! u.CheckDraw() ) continue;
sceKernelPowerTick( SCE_KERNEL_POWER_TICK_DISABLE_AUTO_SUSPEND );
vita2d_start_drawing();
vita2d_clear_screen();
u.Draw();
vita2d_end_drawing();
vita2d_swap_buffers();
}
vita2d_fini();
if( sceSysmoduleIsLoaded( SCE_SYSMODULE_PGF ) == SCE_SYSMODULE_LOADED ) sceSysmoduleUnloadModule( SCE_SYSMODULE_PGF );
sceKernelExitProcess( 0 );
return 0;
}
|
97b6424ed42e2e1ddbe32ef5a395427516620a83 | ebd3360a127b9f0f38363dc0dad35a5d452140ac | /29.cpp | 7bba9d6ab5861b1bc9efc87f70a67031dd0033f9 | [] | no_license | peachhhhh/CodingInterviews | e4c0f41ad956f0519e59d28de0064e381b9f5693 | 54e0bea986a30188b716c5a794222054b015b98f | refs/heads/master | 2020-09-12T06:54:39.782020 | 2020-01-16T08:33:50 | 2020-01-16T08:33:50 | 222,347,045 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,311 | cpp | 29.cpp | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
//调整大顶堆
void adjustHeap(vector<int> &v, int i, int k)
{
if (i > k / 2)
{
return;
}
int maxindex = i;
int l = i * 2;
int r = l + 1;
if (v[l] > v[maxindex] && l < k)
{
maxindex = l;
}
if (v[r] > v[maxindex] && r < k)
{
maxindex = r;
}
if (maxindex != i)
{
swap(v[maxindex], v[i]);
adjustHeap(v, maxindex, k);
}
}
//构建大顶堆
void buildHeap(vector<int> &v, int k)
{
for (int i = k / 2; i >= 0; --i)
{
adjustHeap(v, i, k);
}
}
//最小的K个数,构建大小为k的大顶堆,每次将堆顶最大元素和新元素比较大小,取较小一个保留在堆顶,调整堆
vector<int> GetLeastNumbers_Solution(vector<int> input, int k)
{
int len = input.size();
if (len == 0 || k > len)
{
return {};
}
buildHeap(input, k);
for (int i = k; i < len; ++i)
{
if (input[0] > input[i])
{
input[0] = input[i];
adjustHeap(input, 0, k);
}
}
vector<int> res(input.begin(), input.begin() + k);
return res;
}
void test()
{
int a = 1 / 2;
cout << a << endl;
}
int main()
{
test();
return 0;
} |
316a3a64bb28106025d7c22cd15ae654cf4166ba | 8395619f0e794e204df5a1f3227db2af68f55a78 | /break.cpp | f8054e43120a060b1164104c702146b0322e4bdf | [] | no_license | gawbi/ch07 | d2fba796dc757562758e91d84e93adeb576d54bc | 25a5cde3e57410e8127abdb1a72fdef7b485a8f6 | refs/heads/main | 2023-01-30T16:44:05.102924 | 2020-12-15T08:39:23 | 2020-12-15T08:39:23 | 321,603,182 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 674 | cpp | break.cpp | // file:break.c
#define _CRT_SECURE_NO_WARNINGS //scanf() 오류를 방지하기 위한 상수 정의
#include<stdio.h>
int main(void)
{
int input;
while (1)
{
printf("정수[음수, 0(종료), 양수]를 입력 후 [Enter] :");
scanf("%d", &input);
printf("입력한 정수 %d\n", input);
if (input == 0)
break;
}
puts("종료합니다.");
return 0;
}
/* 결과
정수[음수, 0(종료), 양수]를 입력 후 [Enter] :10
입력한 정수 10
정수[음수, 0(종료), 양수]를 입력 후 [Enter] :-5
입력한 정수 -5
정수[음수, 0(종료), 양수]를 입력 후 [Enter] :0
입력한 정수 0
종료합니다.
*/
|
67e8ba06d42fdafef162d229e4946683147d2cec | 783a20108e50539082e60338e4e6d07a64cba6e5 | /ios/custom_frameworks/PI_MediaCore.framework/Headers/psreport.h | 2f3b9f5685ca3f691b1671e85b1669ba3fe900f0 | [
"MIT"
] | permissive | sinianshou/Demo | 72463db9ba873c87c617278ed72306aada697dc1 | db7e80f7ce9f736630ea8cddbe50af3846a175d7 | refs/heads/master | 2023-01-30T08:32:42.652804 | 2019-10-10T07:11:55 | 2019-10-10T07:11:55 | 210,132,828 | 0 | 0 | MIT | 2022-12-10T03:18:28 | 2019-09-22T11:03:39 | Objective-C | UTF-8 | C++ | false | false | 930 | h | psreport.h |
#ifndef _LIB_PS_REPORT_H_
#define _LIB_PS_REPORT_H_
class PSReport
{
public:
static PSReport *GetInstance() {
if (!m_pInstance) {
m_pInstance = new PSReport;
}
return m_pInstance;
}
virtual void destructor();
int SetReportInterval(int report_interval);
int SetReportInfo(const char *info);
void ReportProc();
private:
PSReport();
PSReport(PSReport const &);
PSReport & operator=(PSReport const &);
~PSReport();
int HttpConnect(int timeout_ms);
int HttpPost(const char *buf);
static PSReport *m_pInstance;
pthread_mutex_t mutex;
int m_iReportInterval;
int m_iStopFlag;
int m_iStatus;
char *m_pInfo;
char m_pDomain[64];
int m_iPort;
SOCKET m_sockfd;
PSNDSelector *m_pSelector;
};
#endif
|
281edd52cf4c4b67a9aeff069947316c067a6376 | 26aa8adc6efb6c83b936fbced99f74cd8d65f3c1 | /student/lab5/lab5.cpp | 08e814c03b0ed9d4fe34ce00d561cb6ec1e6a1cf | [] | no_license | leylafiratli/old_code | 12c16fb3b6e5bc87c662aca6de5746aedc44a20f | b66a770cd9e86d127bdb35c3d69f082e5e2ef2f9 | refs/heads/master | 2021-01-19T22:15:09.972910 | 2014-05-06T03:21:32 | 2014-05-06T03:21:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,063 | cpp | lab5.cpp | #include <iostream>
#include <cmath>
#include "bmplib.h"
using namespace std;
int n = 3;
int ulr;
int ulc;
int h;
int w;
int cr;
int cc;
int a;
int b;
int x;
int y;
unsigned char image[SIZE][SIZE];
// Prototypes
void draw_rectangle(int ulr, int ulc, int h, int w);
void draw_ellipse(int cr, int cc, int a, int b);
int main()
{
// initialize the image to all white pixels
for(int i=0; i < SIZE; i++){
for(int j=0; j < SIZE; j++){
image[i][j] = 255;
}
}
// Main program loop here
while(true)
{
cout << "Please enter 0 if you would like a rectangle and 1 if you would like an ellipse. To exit, press 2" << endl;
cin >> n;
if(n==0)
{
cout << "Upper left row: " <<endl;
cin >> ulr;
cout << "Upper left column: " <<endl;
cin >> ulc;
cout << "Height: " <<endl;
cin >> h;
cout << "Width: " <<endl;
cin >> w;
draw_rectangle(ulr, ulc, h, w);
}
if(n==1)
{
cout << "Upper left row: " <<endl;
cin >> cr;
cout << "Upper left column: " <<endl;
cin >> cc;
cout << "Major length: " <<endl;
cin >> a;
cout << "Minor length: " <<endl;
cin >> b;
draw_ellipse(cr, cc, a, b);
}
if(n==2)
{
// Write the resulting image to the .bmp file
writeGSBMP("output.bmp", image);
cout << "Your output has been stored!" << endl;
cout << "To view it, enter 'firefox output.bmp &'" << endl;
break;
}
}
return 0;
}
void draw_rectangle(int ulr, int ulc, int h, int w)
{
for (int x=ulr, y=ulc; y<ulc+w; y++) //top
{
image[x][y]=0;
}
for (int x=ulc, y=ulr+w; x<ulc+h; x++) //left
{
image[x][y]=0;
}
for (int x=ulr+h, y=ulc; y<ulc+w; y++) //bottom
{
image[x][y]=0;
}
for (int x=ulr, y=ulr; x<ulc+h; x++) //right
{
image[x][y]=0;
}
}
void draw_ellipse(int cr, int cc, int a, int b)
{
for(double theta=0.0; theta < 2*M_PI; theta += .01)
{
int x = (a/2)*cos(theta);
int y = (b/2)*sin(theta);
x += cr;
y += cc;
image[y][x] = 0;
}
}
|
cc89113cf750e237b35a4e7fc41d77c3603a85c7 | 2ed1fc231f58fc916d0fac184d7199f73169c1b5 | /practice/temp.cpp | 47c8c83bfdeb82322c4aa57750330d5897f24aaf | [] | no_license | niteshsurtani/algorithm_coding | 15478c557aa351aadfd977d52866f3520d79d3b7 | ebda983feb7265ad953907ac1ebd5febcfbc9c5f | refs/heads/master | 2020-07-17T16:11:22.391780 | 2016-11-16T14:33:41 | 2016-11-16T14:33:41 | 73,928,528 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,613 | cpp | temp.cpp | string Solution::largestNumber(const vector<int> &A) {
// Do not write main() function.
// Do not read input, instead use the arguments to the function.
// Do not print the output, instead return values as specified
// Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details
vector<string> prev, latest;
int len = A.size();
int max_len = 0,c=0;
int i,j,k;
for(i=0;i<len;i++){
std::string s = std::to_string(A[i]);
prev.push_back(s);
// cout << s.length() << endl;
if(s.length() > max_len) max_len = s.length();
}
std::sort(prev.begin(), prev.end());
// cout << prev[0] << endl;
char prev_char, digit;
vector<char> digits;
vector<char> prev_digits;
// cout << prev[0] << prev [1] << endl;
while(c<max_len){
cout << c << endl;
int start=0, end=0;
for(i=0;i<len;i++){
cout << prev[i]) << " ";
// if(c>prev[i].length()) digits.push_back(prev[i].at(0));
// else{
// cout << "HERE" << endl;
// digits.push_back(prev[i].at(c));
}
}
while(end<len){
if(c==0){
start = 0;
end = len;
}
else{
start = end;
prev_char = prev_digits[start];
while(prev_digits[end] == prev_char){
end++;
}
}
// Sort function
// cout << " HERE " << endl;
for(j=start + 1;j<end;j++){
char temp = digits[j];
string tempStr = prev[j];
for(k=j-1;k>=0;k--){
if(digits[k] < temp){
// swap digits and corresponding vector elements
digits[k+1] = digits[k];
prev[k+1] = prev[k];
}
else break;
}
digits[k+1] = temp;
prev[k+1] = tempStr;
}
}
prev_digits = digits;
digits.clear();
for(i=0;i<len;i++){
cout << prev_digits[i] << " ";
}
cout << endl;
for(i=0;i<len;i++){
cout << prev[i] << " ";
}
cout << endl;
c++;
}
// cout << prev[0] << endl;
string str = "";
for(i=0;i<len;i++){
str += prev[i];
}
return str;
}
|
840b4a000e251743f939b0d9e86da454987fd5b0 | 69b1f623ef673bf2778c25b0006ce48084fb1ba0 | /server/chores.cpp | afcfacea4a944848c1a074e9a4a38208b41ed4bc | [] | no_license | lotuskip/yuxtapa | 640a25e74d74b4fcc8fa7869be7b89385a0529a3 | 6fcf7dc23d69e52569cf6381701344ecdf09519b | refs/heads/master | 2020-05-27T11:55:00.095231 | 2018-10-24T08:04:29 | 2018-10-24T08:04:29 | 941,914 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 47,114 | cpp | chores.cpp | // Please see LICENSE file.
#ifndef MAPTEST
#include "chores.h"
#include "actives.h"
#include "network.h"
#include "game.h"
#include "viewpoint.h"
#include "spiral.h"
#include "settings.h"
#include "../common/los_lookup.h"
#include "../common/util.h"
#include <cstdlib>
#include <algorithm>
#ifdef DEBUG
#include <iostream>
#include "log.h"
#endif
namespace Game { extern Map *curmap; }
extern e_GameMode gamemode;
extern unsigned short tdm_kills[2];
extern e_Dir obj_sector; // defined in game.cpp
namespace
{
using namespace std;
const string teammate_str = "TEAMMATE ";
const string spell_kill_msg[2][3] = {
/* mms: */ { " could not outrun ", "her own ", "magic missile." },
/* zaps */ { " was zapped by ", "herself", "." }
};
const char IDLE_TURNS_TO_AUTOSWAP = 8; /* NOTE: this should be larger than
the amount of turns it takes to complete any of the "chores" (trap, dig,
disguise) */
const char MAX_LIMITER = 10;
const char MAX_BLK_DIST = 4;
const char SCARED_TO_DEATH_DIST = 3;
const char CORPSE_DECAY_TURNS = 60; // 15 seconds on normal settings
const char DIG_TURNS = 5;
const char TRAP_TURNS = 6;
const char DISGUISE_TURNS = 7;
const char BASE_TURNS_TO_DETECT_TRAPS = 10;
const char DETECT_TRAPS_RAD = 3;
const char SNEAK_RADIUS = 3;
const char CHANCE_RUST = 65;
const char RUST_MOD = 2;
const char CHANCE_ARROW_TRIG_TRAP = 60;
// Calls update_static_light for all those torches that are close enough
// to c.
void update_lights_around(const Coords &c)
{
for(list<NOccEnt>::const_iterator it = noccents[NOE_TORCH].begin();
it != noccents[NOE_TORCH].end(); ++it)
{
if(c.dist_walk(it->getpos()) <= TORCH_LIGHT_RADIUS)
update_static_light(it->getpos());
}
}
// returns 0: can dig, 1: can't dig, -1: illusory wall!
char cant_dig_in(const Coords &c, const e_Dir d)
{
// Mining requires one of: (A) there is a wall/window/door, (B) there is a blocked
// boulder, (C) there is a boulder source.
Tile* tp = Game::curmap->mod_tile(c);
if(tp->symbol == '#' && tp->flags & TF_WALKTHRU)
return -1;
if(tp->symbol == '#' || tp->symbol == '|' || tp->symbol == '-' || tp->symbol == '+'
|| ((tp->flags & TF_NOCCENT) && any_noccent_at(c, NOE_BLOCK_SOURCE)
!= noccents[NOE_BLOCK_SOURCE].end()))
return 0;
// that was (A) and (C); (B) is more complicated:
if(tp->flags & TF_OCCUPIED && any_boulder_at(c) != boulders.end())
{
Coords pushtarpos = c.in(d);
Tile *pushtar = Game::curmap->mod_tile(pushtarpos);
if((tp->flags & TF_SLOWWALK) || (pushtar->flags & TF_OCCUPIED)
|| !(pushtar->flags & TF_WALKTHRU) || pushtar->symbol == '\\'
|| ((pushtar->flags & TF_NOCCENT)
&& any_noccent_at(pushtarpos, NOE_FLAG) != noccents[NOE_FLAG].end()))
return 0; // cannot push; hence can dig
}
return 1;
}
void capt_flag(const list<NOccEnt>::iterator fit, const e_Team t)
{
/* A special situation in which capturing cannot be allowed: game mode is
* steal, and green team has secured the treasure: */
if(gamemode == GM_STEAL && t == T_PURPLE && team_flags[t].empty())
return;
// Otherwise okay (various checks already made prior to calling this):
fit->set_col(team_colour[t]);
fit->set_misc(t);
team_flags[t].push_back(fit);
string msg = str_team[t] + " team captured the "
+ long_sector_name[Game::curmap->coords_in_sector(fit->getpos())]
+ " flag!";
Network::construct_msg(msg, team_colour[t]);
Network::broadcast();
// In dominion&conquest this always changes objective status:
if(gamemode == GM_DOM || gamemode == GM_CONQ)
Game::send_team_upds(cur_players.end());
Game::send_flag_upds(cur_players.end());
}
void record_kill(const list<Player>::iterator pit, const char method)
{
++(pit->stats_i->kills[method]);
if(gamemode == GM_TDM)
{
int cmp = int(tdm_kills[T_GREEN]) - tdm_kills[T_PURPLE];
++tdm_kills[pit->team];
// First cmp = A-B, then either A or B is incremented by one, and
// we want to know whether their relative order has changed. This
// test suffices:
if((int(tdm_kills[T_GREEN]) - tdm_kills[T_PURPLE])*cmp == 0)
Game::send_team_upds(cur_players.end());
}
}
bool test_hit(const list<Player>::iterator def, const char tohit,
char numdies, const char ddie, const char dadd)
{
Coords loc = def->own_pc->getpos();
char P = def->cl_props.dv - tohit;
char R = random()%20;
if(R >= P || R == 19) // hit
{
char dam = dadd;
while(numdies--)
dam += 1 + random()%ddie;
if(R != 19 && R/P < 2) // not critical hit; apply PV
dam -= def->cl_props.pv;
def->cl_props.hp -= max(0, int(dam));
def->needs_state_upd = true;
add_action_ind(loc, A_HIT);
return true;
}
add_action_ind(loc, A_MISS);
return false;
}
void missile_hit_PC(const list<Player>::iterator pit, OwnedEnt* mis,
const bool should_void_zap)
{
list<Player>::iterator shooter = mis->get_owner();
if(dynamic_cast<Arrow*>(mis)) // it's an arrow
{
if(pit->team != shooter->team) // shooting teammates don't count as hit
shooter->stats_i->arch_hits++;
if(test_hit(pit, 7, 1, 7, 0)) // arrows: 1d7+0 damage, +7 to hit
{
if(pit->cl_props.hp <= 0) // (check if died)
{
string msg = " was shot by ";
if(pit->team == shooter->team)
{
msg += teammate_str;
shooter->stats_i->tks++;
}
else // shot enemy, count kill
record_kill(shooter, WTK_ARROW);
player_death(pit, msg + shooter->nick + '.', true);
}
else
pit->needs_state_upd = true;
}
mis->makevoid(); // occupied flag is unset in kill_player if necessary
}
else // a mm or a zap
{
bool is_zap = dynamic_cast<Zap*>(mis);
if(is_zap && shooter->team != pit->team)
shooter->stats_i->cm_hits++;
if(pit->nomagicres())
{
add_action_ind(pit->own_pc->getpos(), A_HIT);
char dam = 1 + random()%5; // 1d5
if(is_zap)
dam += 1 + random()%5; // 2d5 for zaps
pit->cl_props.hp -= dam;
if(pit->cl_props.hp <= 0) // died
{
string msg = spell_kill_msg[is_zap][0];
if(pit == shooter)
msg += spell_kill_msg[is_zap][1];
else
{
if(pit->team == shooter->team)
{
msg += teammate_str;
shooter->stats_i->tks++;
}
else
record_kill(shooter, is_zap ? WTK_ZAP : WTK_MM);
msg += shooter->nick;
if(!is_zap)
msg += "\'s ";
}
msg += spell_kill_msg[is_zap][2];
player_death(pit, msg, true);
}
else
pit->needs_state_upd = true;
} // no magic resistance
else
add_action_ind(pit->own_pc->getpos(), A_MISS);
// mms voided always, zaps only if we are allowed to do so here:
if(should_void_zap || !is_zap)
mis->makevoid(); // occupied flag is unset in kill_player if necessary
} // mm or zap
}
void heal_PC(const list<Player>::iterator pit)
{
if(pit->cl_props.hp < classes[pit->cl].hp)
{
/* always heal at least once, but sometimes more */
while(++(pit->stats_i->healing_recvd) && // this first one is of course always true
++(pit->cl_props.hp) < classes[pit->cl].hp && !(random()%4));
pit->poisoner = cur_players.end();
pit->needs_state_upd = true;
add_action_ind(pit->own_pc->getpos(), A_HEAL);
}
}
void conditional_blind(const Coords &c)
{
list<PCEnt>::iterator pc_it = any_pc_at(c);
// Must be valid PC, not assassin, and not a mind's eye using planewalker:
if(pc_it != PCs.end() && pc_it->get_owner()->cl != C_ASSASSIN
&& (pc_it->get_owner()->cl != C_PLANEWALKER || !pc_it->get_owner()->limiter))
{
pc_it->get_owner()->turns_without_axn = 0; // being blinded stops "idling"
pc_it->get_owner()->own_vp->blind();
}
}
void flash_at(const Coords &pos)
{
// Every non-assassin within LOS is blinded (note that
// the radius is the same as for trap detection).
char line, ind;
Coords c;
unsigned short f;
list<PCEnt>::iterator pc_it;
for(line = 0; line < DETECT_TRAPS_RAD*8; ++line)
{
for(ind = 0; ind < 2*DETECT_TRAPS_RAD; ind += 2)
{
c.x = loslookup[DETECT_TRAPS_RAD-2][line*2*DETECT_TRAPS_RAD+ind] + pos.x;
c.y = loslookup[DETECT_TRAPS_RAD-2][line*2*DETECT_TRAPS_RAD+ind+1] + pos.y;
if((f = Game::curmap->get_tile(c).flags) & TF_OCCUPIED)
conditional_blind(c);
else if(!(f & TF_SEETHRU))
break;
}
}
// At pos itself, too:
conditional_blind(pos);
add_sound(pos, S_ZAP);
}
void fireball_trigger(const Coords &pos, const list<Player>::iterator triggerer,
const bool intentional)
{
Coords c;
list<PCEnt>::iterator pc_it;
char ch;
string msg;
for(c.x = min(pos.x+2, Game::curmap->get_size()-2); c.x >= max(1, pos.x-2); --(c.x))
{
for(c.y = min(pos.y+2, Game::curmap->get_size()-2); c.y >= max(1, pos.y-2); --(c.y))
{
add_sound(c, S_BOOM);
if((c == pos /* occupied-flag might not be set for the triggerer yet;
we check this point unnecessarily when triggering with an arrow. */
|| (Game::curmap->get_tile(c).flags & TF_OCCUPIED))
&& (pc_it = any_pc_at(c)) != PCs.end())
{
// damage is (3-radius)d6:
for(ch = 3 - pos.dist_walk(c); ch > 0; --ch)
pc_it->get_owner()->cl_props.hp -= 1 + random()%6;
if(pc_it->get_owner()->cl_props.hp <= 0) // died
{
if(pc_it->get_owner() == triggerer)
player_death(triggerer, " fried to a trap.", false);
else
{
msg = " was taken to the flames by ";
if(pc_it->get_owner()->team == triggerer->team)
{
msg += teammate_str;
if(intentional)
triggerer->stats_i->tks++;
}
else
record_kill(pc_it->get_owner(), WTK_FIREB);
msg += triggerer->nick + '.';
player_death(pc_it->get_owner(), msg, false);
}
}
else // survived
{
pc_it->get_owner()->needs_state_upd = true;
// light torch if any:
if(!pc_it->torch_is_lit() && pc_it->get_owner()->torch_left)
pc_it->toggle_torch();
}
}
}
}
fball_centers.push_back(pos);
}
void move_player_to(const list<Player>::iterator p, const Coords &c,
const bool do_flags); // (This needs to call trigger_trap needs to call this)
bool trigger_trap(const list<Player>::iterator pit, const list<Trap>::iterator tr,
const bool intentional)
{
Coords pos = pit->own_pc->getpos();
switch(tr->get_m())
{
case TRAP_WATER:
// Extinguish torch, make splash sound, possibly rust weapon
if(pit->own_pc->torch_is_lit())
pit->own_pc->toggle_torch();
add_sound(pos, S_SPLASH);
// Rusting happens only once; to see if it has happened we compare
// the PCs 2-hit to the 2-hit of that class by default:
if(pit->cl_props.tohit == classes[pit->cl].tohit
&& random()%100 < CHANCE_RUST)
{
string msg = "Your weapon rusts!";
Network::construct_msg(msg, C_WATER_TRAP_LIT);
Network::send_to_player(*pit);
pit->cl_props.tohit -= RUST_MOD;
pit->cl_props.dam_add -= RUST_MOD;
pit->needs_state_upd = true;
}
break;
case TRAP_LIGHT:
flash_at(pos);
break;
case TRAP_TELE:
if(pit->nomagicres())
{
// Get a random tile that's walkable and not occupied:
Coords tar(1 + random()%(Game::curmap->get_size()-1),
1 + random()%(Game::curmap->get_size()-1));
init_nearby(tar);
unsigned short f = Game::curmap->get_tile(tar).flags;
while(!(f & TF_WALKTHRU) || (f & TF_OCCUPIED))
f = Game::curmap->get_tile((tar = next_nearby())).flags;
event_set.insert(pos); // necessary if 'T'riggering the trap
move_player_to(pit, tar, true);
// NOTE: do not clear axn queue like in blinking
return true; // do not make triggered teleportation traps seen
}
else
add_action_ind(pos, A_MISS);
break;
case TRAP_BOOBY:
if(test_hit(pit, 9, 2, 6, 0) // 2d6+0, +9 tohit
&& pit->cl_props.hp <= 0)
{
string msg = " died to a trap.";
if(tr->get_owner() != cur_players.end())
{
msg = intentional ? " decided to step into " : " failed to notice ";
if(tr->get_owner() == pit)
msg += "her own";
else
{
if(tr->get_owner()->team == pit->team)
{
msg += teammate_str;
if(!intentional)
tr->get_owner()->stats_i->tks++;
}
else
record_kill(tr->get_owner(), WTK_BOOBY);
msg += tr->get_owner()->nick + "\'s";
}
msg += " boobytrap.";
}
player_death(pit, msg, true);
}
add_sound(pos, S_CREAK);
// Boobytraps are always destroyed:
traps.erase(tr);
Game::curmap->mod_tile(pos)->flags &= ~(TF_TRAP);
return !pit->is_alive(); // cannot set the destroyed trap as seen!
case TRAP_FIREB:
fireball_trigger(pos, pit, intentional);
if(!pit->is_alive())
return true;
break;
case TRAP_ACID:
if(test_hit(pit, 7, 3, 3, 0) // 3d3+0, +7 tohit
&& pit->cl_props.hp <= 0)
player_death(pit, " dissolved.", true);
add_sound(pos, S_SPLASH);
if(!pit->is_alive())
return true;
break;
//default: anything else is an error!
}
// If here, trap should be made known:
tr->set_seen_by(pit->team);
return false;
}
void move_player_to(const list<Player>::iterator p, const Coords &c,
const bool do_flags)
{
Coords opos = p->own_pc->getpos();
// must move both the PC entity and the viewpoint:
p->own_pc->setpos(c);
p->own_vp->set_pos(c);
if(p == pl_with_item)
add_action_ind(c, A_TRAP);
else // add_action inserts to event_set
event_set.insert(c);
// Check if ended up in some special tile: (note that some of
// these are checked only when *walking* into them, but in
// this function we don't know the "method of arrival")
Tile* tile = Game::curmap->mod_tile(c);
if(tile->flags & TF_KILLS) // chasm
{
if(p->warned_of_chasm == Config::int_settings[Config::IS_SAFE_CHASMS])
{
player_death(p, " fell into oblivion.", false);
add_voice(c, "Aieeeee...!");
Game::curmap->mod_tile(opos)->flags &= ~(TF_OCCUPIED);
}
else
{
p->warned_of_chasm++;
string msg = "You almost fall into a chasm!";
Network::construct_msg(msg, C_WALL_LIT);
Network::send_to_player(*p);
// revert original coords:
p->own_pc->setpos(opos);
p->own_vp->set_pos(opos);
}
return; // either died or did not move
}
if(tile->flags & TF_TRAP)
{
list<Trap>::iterator tr_it = any_trap_at(c);
// A trap is triggered always if not seen and sometimes if it's dark:
if(!tr_it->is_seen_by(p->team) || p->own_vp->is_blind()
|| (!(tile->flags & TF_LIT) && random()%100 < 15 && !is_dynlit(c)))
{
if(trigger_trap(p, tr_it, false))
{
// if returned true, PC died or teleported
Game::curmap->mod_tile(opos)->flags &= ~(TF_OCCUPIED);
return;
}
}
}
// If we made it here, the PC survived the checks.
if(tile->flags & TF_DROWNS) // water slows down
{
p->wait_turns += 2;
if(p->cl != C_ASSASSIN && p->cl != C_SCOUT)
add_sound(c, S_SPLASH);
}
else if((tile->flags & TF_SLOWWALK) // slow non-trappers/scouts
&& p->cl != C_TRAPPER && p->cl != C_SCOUT)
p->wait_turns++;
// The occupied flags don't need to be changed when switching places:
if(do_flags)
{
Game::curmap->mod_tile(opos)->flags &= ~(TF_OCCUPIED);
Game::curmap->mod_tile(c)->flags |= TF_OCCUPIED;
}
// Check if moved to another sector:
e_Dir newsector = Game::curmap->coords_in_sector(c);
if(p->sector != newsector)
{
p->sector = newsector;
p->needs_state_upd = true;
}
// Whenever a PC moves, we check if they spot some hiding enemies.
// The requirement for this is that this PC is facing directly at a hiding
// enemy, whose position is lit, at a distance of 2.
opos = c.in(p->facing).in(p->facing); // reusing opos
list<PCEnt>::iterator pc_it = any_pc_at(opos);
if(pc_it != PCs.end() && !pc_it->isvoid() && !pc_it->visible_to_team(p->team)
&& ((Game::curmap->get_tile(opos).flags & TF_LIT) || is_dynlit(opos)))
pc_it->set_invis_to_team(T_NO_TEAM); // seen!
// Also, whenever a PC moves, we check if they are seen by enemy scouts:
if(p->own_pc->visible_to_team(opp_team[p->team]))
{
Coords thc; // "their coords"
char d = classes[C_SCOUT].losr;
if(!(Game::curmap->get_tile(c).flags & TF_LIT))
d = (d+5)/3; // not lit, shorter radius
for(list<Player>::const_iterator pit = cur_players.begin();
pit != cur_players.end(); ++pit)
{
// Search for opponent scouts who are alive...
if(pit->team != p->team && pit->cl == C_SCOUT && pit->is_alive()
&& Game::curmap->LOS_between(c, pit->own_pc->getpos(), d))
{
p->own_pc->set_seen_by_team(pit->team);
return; // done
}
} // loop through current players
}
// If we end up here, was not seen by enemy scouts:
p->own_pc->set_seen_by_team(T_NO_TEAM);
}
void swap_places(const list<Player>::iterator pit1, const list<Player>::iterator pit2)
{
Coords pos1 = pit1->own_pc->getpos();
Coords pos2 = pit2->own_pc->getpos();
move_player_to(pit1, pos2, false);
move_player_to(pit2, pos1, false);
pit1->wants_to_move_to = pit2->wants_to_move_to = MAX_D;
// A very rare possibility is that one of the players dies due to a
// trap; we must check this:
if(!pit1->is_alive())
Game::curmap->mod_tile(pos1)->flags &= ~(TF_OCCUPIED);
if(!pit2->is_alive())
Game::curmap->mod_tile(pos2)->flags &= ~(TF_OCCUPIED);
}
void portal_jump(const list<Player>::iterator pit, const Coords &tar)
{
add_sound(pit->own_pc->getpos(), S_WHOOSH);
add_sound(tar, S_WHOOSH);
move_player_to(pit, tar, true);
}
void try_move(const list<Player>::iterator pit, const e_Dir d)
{
// get target tile and its position:
Coords opos = pit->own_pc->getpos();
Coords tarpos = opos.in(d);
Tile *tar = Game::curmap->mod_tile(tarpos.x, tarpos.y);
list<Player>::iterator them;
// unwalkable tiles are unwalkable tiles:
if(!(tar->flags & TF_WALKTHRU))
{
// Check if walking to a closed door; if so, open it
if(tar->symbol == '+')
{
tar->symbol = '\\';
tar->flags |= TF_WALKTHRU|TF_SEETHRU;
update_lights_around(tarpos);
if(random()%2)
add_sound(tarpos, S_CREAK);
else // a sound sets an event
event_set.insert(tarpos);
}
return; // do not move
}
/*else*/ if(tar->flags & TF_OCCUPIED)
{
// Tile is occupied; first check for another PC:
list<PCEnt>::iterator pc_it = any_pc_at(tarpos);
if(pc_it != PCs.end())
{
them = pc_it->get_owner();
if(them->team == pit->team) // teammate
{
if(them->wants_to_move_to == !d) // That player is willing to swap places
swap_places(them, pit);
else // the processing of this move is finished later
pit->wants_to_move_to = d;
}
else // enemy, do melee attack:
{
// if a hiding assassin, damage is different:
char multip = 1 + char(pit->cl == C_ASSASSIN
&& (!pit->own_pc->visible_to_team(opp_team[pit->team])
|| them->own_vp->is_blind()));
if(test_hit(them, pit->cl_props.tohit, multip, pit->cl_props.dam_die,
multip*(pit->cl_props.dam_add)) // was hit...
&& them->cl_props.hp <= 0) // ...and died
{
if(multip == 2)
{
player_death(them, " was backstabbed by " + pit->nick + '.', true);
record_kill(pit, WTK_BACKSTAB);
}
else
{
player_death(them, " was killed by " + pit->nick + '.', true);
record_kill(pit, WTK_MELEE);
}
}
pit->own_pc->set_disguised(false);
}
return; // do not move
}
// else check all other occents; first blocks:
list<OccEnt>::iterator bl_it = any_boulder_at(tarpos);
if(bl_it != boulders.end()) // there's a block
{
// First check if PC can push blocks:
if(!pit->cl_props.can_push)
return; // do not move
// Get the tile where we'd push the block:
Coords pushtarpos = tarpos.in(d);
Tile *pushtar = Game::curmap->mod_tile(pushtarpos);
// Cannot push if block is currently standing on nonflat terrain.
// Cannot push into nonwalkables, occupieds, doorways, flags.
if((tar->flags & TF_SLOWWALK) || (pushtar->flags & TF_OCCUPIED)
|| !(pushtar->flags & TF_WALKTHRU) || pushtar->symbol == '\\'
|| ((pushtar->flags & TF_NOCCENT)
&& any_noccent_at(pushtarpos, NOE_FLAG) != noccents[NOE_FLAG].end()))
return; // do not move
// Pushing to a chasm destroys the block:
if(pushtar->flags & TF_KILLS)
{
boulders.erase(bl_it);
tar->flags &= ~(TF_OCCUPIED);
}
// Pushing to water makes a "bridge":
else if(pushtar->flags & TF_DROWNS)
{
boulders.erase(bl_it);
tar->flags &= ~(TF_OCCUPIED);
*pushtar = T_FLOOR;
add_sound(pushtarpos, S_SPLASH);
}
else // otherwise we just push:
{
bl_it->setpos(pushtarpos);
pushtar->flags |= TF_OCCUPIED;
tar->flags &= ~(TF_OCCUPIED);
}
pit->wait_turns++;
// PC will be moved below, and that will also add to event_set.
}
else // no block, must be arrow/zap/mm
{
// A nasty hack needed. If the PC should die to the missile, that calls
// player_death, which generates a corpse to pit->own_pc->getpos(), which
// is the *wrong* place for it! Hence we move the PC (just the PC, nothing
// else) already here:
pit->own_pc->setpos(tarpos);
missile_hit_PC(pit, any_missile_at(tarpos), true);
if(pit->cl_props.hp <= 0) // died; don't walk!
{
// missile_hit_PC has called kill_player, which has unset the
// occupied-flag of PC's position (which we just set with our
// hack), but now we must unset the flag for the originating
// position, too!
Game::curmap->mod_tile(opos)->flags &= ~(TF_OCCUPIED);
return;
}
// else survived; let walk; but so that the flags are updated
// correctly, put the PC back where he's walking from:
pit->own_pc->setpos(opos);
}
} // target tile is occupied
// Check for various effects of *walking* into various things:
// (the rest, those that apply regardless of whether walking or not,
// are checked in move_player_to(...))
if(gamemode == GM_STEAL && pit->team == T_GREEN
&& pl_with_item == cur_players.end() && tarpos == the_item.getpos())
{
pl_with_item = pit;
item_moved = true;
Game::send_team_upds(cur_players.end());
string msg = "The green team has stolen the treasure!";
Network::construct_msg(msg, C_PORTAL_IN_LIT);
Network::broadcast();
}
else if(tar->flags & TF_NOCCENT)
{
list<NOccEnt>::iterator noe_it = any_noccent_at(tarpos, NOE_FLAG);
if(noe_it != noccents[NOE_FLAG].end()) // there's a flag
{
// A neutral flag is always captured:
if(noe_it->get_m() == T_NO_TEAM)
capt_flag(noe_it, pit->team);
// Enemy flag capturing depends on game mode.
else if(noe_it->get_m() != pit->team)
{
// dominion: capture always
// conquest: green team can capture
// others: capture if not their last flag
if(gamemode == GM_DOM
|| (gamemode == GM_CONQ && pit->team == T_GREEN)
|| (gamemode != GM_CONQ &&
team_flags[noe_it->get_m()].size() >= 2))
{
team_flags[noe_it->get_m()].erase(find(team_flags[noe_it->get_m()].begin(),
team_flags[noe_it->get_m()].end(), noe_it));
capt_flag(noe_it, pit->team);
}
}
// else own flag:
else if(pit == pl_with_item // is carrying item (implies team is green and gamemode steal)
&& noe_it == *(team_flags[T_GREEN].begin())) // original flag
{
// Green wins. We ensure this by clearing the purple flags list,
// so actually the map won't end until the next purple spawning:
team_flags[T_PURPLE].clear();
string msg = "The green team has secured the treasure!";
Network::construct_msg(msg, C_PORTAL_IN_LIT);
Network::broadcast();
pl_with_item = cur_players.end();
the_item.setpos(Coords(-1,0)); // ensure it doesn't get drawn anywhere
}
}
else if((noe_it = any_noccent_at(tarpos, NOE_PORTAL_ENTRY))
!= noccents[NOE_PORTAL_ENTRY].end())
{
// Get a random, non-blocked 1-way portal exit:
char ind = randor0(noccents[NOE_PORTAL_EXIT].size());
for(noe_it = noccents[NOE_PORTAL_EXIT].begin(); ind > 0; --ind)
++noe_it;
list<NOccEnt>::iterator startit = noe_it;
while(Game::curmap->mod_tile(noe_it->getpos())->flags & TF_OCCUPIED)
{
if(++noe_it == noccents[NOE_PORTAL_EXIT].end())
noe_it = noccents[NOE_PORTAL_EXIT].begin();
if(noe_it == startit) // went around!
{
// Just move the PC onto the portal without jumping
move_player_to(pit, tarpos, true);
return;
}
}
portal_jump(pit, noe_it->getpos());
return;
}// else
if((noe_it = any_noccent_at(tarpos, NOE_PORTAL_2WAY))
!= noccents[NOE_PORTAL_2WAY].end())
{
list<NOccEnt>::iterator startit = noe_it;
do {
if(++noe_it == noccents[NOE_PORTAL_2WAY].end())
noe_it = noccents[NOE_PORTAL_2WAY].begin();
if(noe_it == startit) // went around!
{
// Just move the PC onto the portal without jumping
move_player_to(pit, tarpos, true);
return;
}
}
while(Game::curmap->mod_tile(noe_it->getpos())->flags & TF_OCCUPIED);
portal_jump(pit, noe_it->getpos());
return;
}
}
// Hiding checks:
bool hide = false;
if(!(tar->flags & TF_LIT)
&& ((pit->cl == C_ASSASSIN && (tar->flags & TF_BYWALL))
|| (pit->cl == C_TRAPPER && tar->symbol == 'T'))
&& !is_dynlit(tarpos))
{
// No enemy may see here; note that we use a fixed radius 3,
// not the LOS radius of the respective enemy!
for(them = cur_players.begin(); them != cur_players.end(); ++them)
{
if(them->team != pit->team && them->is_alive()
&& !them->own_vp->is_blind()
&& Game::curmap->LOS_between(them->own_pc->getpos(),
tarpos, SNEAK_RADIUS))
break; // seen by an enemy
}
if(them == cur_players.end()) // seen by no-one!
hide = true;
}
pit->own_pc->set_invis_to_team(hide ? opp_team[pit->team] : T_NO_TEAM);
// If we ever arrive here, we are to move the PC:
move_player_to(pit, tarpos, true);
}
void limiter_upd(const list<Player>::iterator pit)
{
if(pit->limiter < MAX_LIMITER)
pit->limiter++;
pit->wait_turns += 2*pit->limiter;
}
// Used when mining open a tile. If it is a wall tile (not window or door), this should
// be follows by finish_wall_dig([coords]). Otherwise (if window or door), it should be
// followed by event_set.insert(c).
void dig_open(Tile* const tp)
{
tp->symbol = '.';
tp->flags |= TF_WALKTHRU|TF_SEETHRU;
}
void finish_wall_dig(const Coords &c)
{
update_lights_around(c);
// Need to update BYWALL for neighbours:
e_Dir dir = D_N;
Coords cn;
do {
cn = c.in(dir);
Game::curmap->upd_by_wall_flag(cn);
} while(++dir != D_N);
event_set.insert(c);
}
} // end local namespace
// This function assumes that pit points to a player who is alive, and
// axn is an action that "makes sense for that player to do"
void process_action(const Axn &axn, const list<Player>::iterator pit)
{
Coords c;
// Stuff that happens whenever a PC acts:
pit->acted_this_turn = true;
pit->wants_to_move_to = MAX_D;
switch(axn.xncode)
{
case XN_CLOSE_DOOR:
{
// Find an open door, starting the search from the facing direction:
e_Dir d = pit->facing;
Tile *t;
do {
c = pit->own_pc->getpos().in(d);
t = Game::curmap->mod_tile(c);
if(t->symbol == '\\' && !(t->flags & TF_OCCUPIED))
{
t->symbol = '+';
t->flags &= ~(TF_WALKTHRU|TF_SEETHRU);
update_lights_around(c);
if(random()%2)
add_sound(c, S_CREAK);
else // a sound sets an event
event_set.insert(c);
pit->facing = d;
break;
}
++d;
} while(d != pit->facing);
break;
}
case XN_TORCH_HANDLE:
{
c = pit->own_pc->getpos();
if(pit->own_pc->torch_is_lit())
{
pit->own_pc->toggle_torch();
event_set.insert(c);
}
else if(pit->torch_left) // wants to light it
{
// Check the three conditions: wizard, on a static torch, or
// next to a teammate with a lit torch:
if(pit->cl == C_WIZARD || any_noccent_at(c, NOE_TORCH) != noccents[NOE_TORCH].end())
{
pit->own_pc->toggle_torch();
event_set.insert(c);
}
else // Check the teammates:
{
for(list<PCEnt>::const_iterator pcit = PCs.begin();
pcit != PCs.end(); ++pcit)
{
if(pcit->getpos().dist_walk(c) == 1
&& pcit->torch_is_lit()
&& pcit->get_owner()->team == pit->team)
{
pit->own_pc->toggle_torch();
event_set.insert(c);
break;
}
}
}
} // trying to light a torch
break;
}
case XN_TRAP_TRIGGER:
if(Game::curmap->get_tile(pit->own_pc->getpos()).flags & TF_TRAP)
trigger_trap(pit, any_trap_at(pit->own_pc->getpos()), true);
break;
case XN_SUICIDE:
{
// Check for "scared to death" possibility:
// Go through the PCs looking for any visible enemy close enough
list<PCEnt>::iterator it = PCs.begin();
while(it != PCs.end())
{
// not void, visible, enemy (NOTE: pass the actual
// distance to LOS_between; this way it will only check one
// direction (whether 'pit' sees 'it', not if 'it' sees 'pit'))
if(!it->isvoid() && it->visible_to_team(pit->team)
&& it->get_owner()->team != pit->team
&& Game::curmap->LOS_between(pit->own_pc->getpos(), it->getpos(),
SCARED_TO_DEATH_DIST, it->getpos().dist_walk(pit->own_pc->getpos())))
{
player_death(pit, " was scared to death by "
+ it->get_owner()->nick + '.', true);
record_kill(it->get_owner(), WTK_SCARE);
break;
}
++it;
}
if(it != PCs.end()) // was broken
break;
// If here, check for being poisoned with just 1 hp:
if(pit->poisoner != cur_players.end() && pit->cl_props.hp == 1)
player_poisoned(pit);
else // a valid suicide
player_death(pit, " suicided.", true);
break;
}
case XN_MOVE:
// If player is in water and action queue is nonempty, do not allow swimming
if(pit->action_queue.empty() ||
!(Game::curmap->mod_tile(pit->own_pc->getpos())->flags & TF_DROWNS))
try_move(pit, (pit->facing = e_Dir(axn.var1)));
break;
case XN_SHOOT:
{
// The coords are already validated in network.cpp upon receiving!
c.x = axn.var1; c.y = axn.var2;
pit->facing = Coords(0,0).dir_of(c);
pit->stats_i->arch_shots++;
arrows.push_back(Arrow(c, pit));
break;
}
case XN_FLASH:
if(pit->limiter) // have flashbombs left
{
flash_at(pit->own_pc->getpos());
pit->limiter--;
}
break;
case XN_ZAP:
limiter_upd(pit);
pit->facing = e_Dir(axn.var1);
zaps.push_back(Zap(pit, pit->facing));
pit->stats_i->cm_shots++;
break;
case XN_CIRCLE_ATTACK:
pit->facing = e_Dir(axn.var1);
pit->doing_a_chore = 2;
break;
case XN_HEAL:
if(axn.var1 != MAX_D)
{
c = pit->own_pc->getpos().in((pit->facing = e_Dir(axn.var1)));
list<PCEnt>::iterator pc_it = any_pc_at(c);
if(pc_it != PCs.end())
{
list<Player>::iterator nit = pc_it->get_owner();
if(nit->team == pit->team) // teammate => heal
heal_PC(nit);
else // enemy => poison
{
nit->poisoner = pit;
add_action_ind(c, A_POISON);
}
}
}
else // healing self
heal_PC(pit);
break;
case XN_BLINK:
{
limiter_upd(pit);
// Determine a point to blink to, if any:
Coords opos = pit->own_pc->getpos();
vector<Coords> optimals;
Coords cg = opos; // "good" coords
char line, ind;
for(line = 0; line < MAX_BLK_DIST*8; ++line)
{
for(ind = 0; ind < 2*MAX_BLK_DIST; ind += 2)
{
c.x = loslookup[MAX_BLK_DIST-2][line*2*MAX_BLK_DIST+ind]
+ opos.x;
c.y = loslookup[MAX_BLK_DIST-2][line*2*MAX_BLK_DIST+ind+1]
+ opos.y;
// the point must be visible:
if(!(Game::curmap->get_tile(c).flags & TF_SEETHRU))
break;
//else
cg = c;
}
// Note that points outside of the map cannot be reached; the edge
// wall prevents them from being visible!
// Endpoint must be walkable and not occupied:
if((Game::curmap->get_tile(cg).flags & TF_WALKTHRU)
&& !(Game::curmap->get_tile(cg).flags & TF_OCCUPIED))
{
// Trying to get as far as possible:
if(optimals.empty())
optimals.push_back(cg); // no previous record
else if(cg.dist_walk(opos) > optimals.front().dist_walk(opos))
{
optimals.clear(); // a new record!
optimals.push_back(cg);
}
else if(cg.dist_walk(opos) == optimals.front().dist_walk(opos))
optimals.push_back(cg); // repeat old record
}
}
if(optimals.empty())
break; // cannot blink!
c = optimals[randor0(optimals.size())];
// Do the transfer:
event_set.insert(opos);
move_player_to(pit, c, true);
pit->action_queue.clear(); /* Rarely does one plan her actions
beyond a blink. */
break;
}
case XN_MINE:
{
pit->facing = e_Dir(axn.var1);
c = pit->own_pc->getpos().in(e_Dir(axn.var1));
char rv;
if(!(rv = cant_dig_in(c, e_Dir(axn.var1))))
{
pit->doing_a_chore = DIG_TURNS;
add_sound(c, S_RUMBLE);
}
else if(rv == -1) // illusory wall
{
string msg = "That is no real wall!";
Network::construct_msg(msg, C_WALL_LIT);
Network::send_to_player(*pit);
}
// else there is nothing to dig
break;
}
case XN_DISGUISE:
{
c = pit->own_pc->getpos();
if(Game::curmap->get_tile(c).flags & TF_NOCCENT)
{
// check that there's an enemy corpse
list<NOccEnt>::iterator c_it = any_noccent_at(c, NOE_CORPSE);
if(c_it != noccents[NOE_CORPSE].end()
&& c_it->get_colour() != team_colour[pit->team])
{
pit->doing_a_chore = DISGUISE_TURNS;
add_action_ind(c, A_DISGUISE);
}
}
break;
}
case XN_SET_TRAP:
{
// A trap can be set/disarmed where there is no noccent:
if(!(Game::curmap->get_tile(pit->own_pc->getpos()).flags
& TF_NOCCENT))
{
pit->doing_a_chore = TRAP_TURNS;
add_action_ind(pit->own_pc->getpos(), A_TRAP);
}
break;
}
case XN_MM:
{
limiter_upd(pit);
e_Dir d;
unsigned short flgs;
for(char ch = 0; ch < 4; ++ch)
{
d = e_Dir((pit->facing + 2*ch)%MAX_D);
c = pit->own_pc->getpos().in(d);
flgs = Game::curmap->mod_tile(c)->flags;
if(flgs & TF_WALKTHRU && !(flgs & TF_OCCUPIED))
{
MMs.push_back(MM(pit, d));
event_set.insert(c);
}
// else cannot conjure a MM there
}
break;
}
case XN_MINDS_EYE:
if(!(pit->limiter = !pit->limiter)) // turning mind's eye off
{
pit->own_vp->set_pos(pit->own_pc->getpos());
pit->cl_props.dv = classes[pit->cl].dv;
}
else // turning mind's eye on
{
pit->cl_props.dv = 11;
while(pit->own_vp->is_blind())
pit->own_vp->reduce_blind();
}
pit->needs_state_upd = true;
break;
}
}
void player_death(const list<Player>::iterator pit, const string &way,
const bool corpse)
{
string msg = pit->nick + way;
Network::construct_msg(msg, DEF_MSG_COL);
Network::broadcast();
pit->stats_i->deaths++;
pit->needs_state_upd = true;
Coords pos;
// Item carrier leaves no corpse! Also, if the place is a water square,
// do not generate a corpse:
if(corpse && pit != pl_with_item &&
!(Game::curmap->mod_tile((pos = pit->own_pc->getpos()))->flags & TF_DROWNS))
{
// If there is already a corpse there, this corpse "overrules" the
// older one. But if there is some other noccent there, do not cover
// it with a corpse.
list<NOccEnt>::iterator enoe = any_noccent_at(pos, NOE_CORPSE);
if(enoe != noccents[NOE_CORPSE].end())
{
enoe->set_col(team_colour[pit->team]);
enoe->set_misc(CORPSE_DECAY_TURNS);
}
else
{
Tile* tp = Game::curmap->mod_tile(pos);
if(!(tp->flags & TF_NOCCENT))
{
noccents[NOE_CORPSE].push_back(NOccEnt(pos, '%',
team_colour[pit->team], CORPSE_DECAY_TURNS));
tp->flags |= TF_NOCCENT;
}
}
}
kill_player(pit);
}
void kill_player(const list<Player>::iterator pit)
{
if(pit->cl_props.hp > 0)
pit->cl_props.hp = 0; // if they're negative, we don't overwrite that
pit->doing_a_chore = pit->warned_of_chasm = 0;
event_set.insert(pit->own_pc->getpos());
Tile* tp = Game::curmap->mod_tile(pit->own_pc->getpos());
// if was carrying item, drop it
if(pit == pl_with_item)
{
pl_with_item = cur_players.end();
the_item.setpos(pit->own_pc->getpos());
// Change item colour for certain tile types:
if(tp->flags & TF_DROWNS) // water
the_item.set_col(C_WATER_TRAP);
else if(tp->flags & TF_KILLS) // chasm
the_item.set_col(C_BROWN_PC);
else
the_item.set_col(C_LIGHT_TRAP);
obj_sector = Game::curmap->coords_in_sector(pit->own_pc->getpos());
Game::send_team_upds(cur_players.end());
string msg = "Treasure dropped!";
Network::construct_msg(msg, C_PORTAL_IN_LIT);
Network::broadcast();
}
// If was a planewalker on a trip, return to view own corpse:
if(pit->cl == C_PLANEWALKER && pit->limiter)
pit->own_vp->set_pos(pit->own_pc->getpos());
// (limiter and pv are reset upon next spawn)
tp->flags &= ~(TF_OCCUPIED);
pit->own_pc->makevoid();
pit->action_queue.clear();
pit->poisoner = cur_players.end();
// If requested to change class:
if(pit->next_cl != pit->cl)
Game::send_state_change(pit);
pit->stats_i->time_played[pit->cl] += time(NULL) - pit->last_switched_cl;
time(&(pit->last_switched_cl));
}
void player_poisoned(const list<Player>::iterator it)
{
it->poisoner->stats_i->kills[WTK_POISON]++;
player_death(it, " was poisoned by " + it->poisoner->nick + '.', true);
}
void process_swaps()
{
for(list<Player>::iterator it = cur_players.begin();
it != cur_players.end(); ++it)
{
if(it->is_alive() && it->wants_to_move_to != MAX_D)
{
Coords tarpos = it->own_pc->getpos().in(it->wants_to_move_to);
if(Game::curmap->get_tile(tarpos).flags & TF_OCCUPIED)
{
// Check if there is teammate willing to swap:
list<PCEnt>::iterator pc_it = any_pc_at(tarpos);
if(pc_it != PCs.end())
{
list<Player>::iterator pp = pc_it->get_owner();
if(pp->team == it->team
&& (pp->wants_to_move_to == !(it->wants_to_move_to)
|| pp->turns_without_axn >= IDLE_TURNS_TO_AUTOSWAP))
swap_places(pp, it);
}
}
else // not occupied; can move there!
{
move_player_to(it, tarpos, true);
it->wants_to_move_to = MAX_D;
}
}
}
}
void progress_chore(const list<Player>::iterator pit)
{
Coords c;
--(pit->doing_a_chore);
switch(pit->cl)
{
case C_SCOUT: // disguise
if(!pit->doing_a_chore) // done
{
c = pit->own_pc->getpos();
list<NOccEnt>::iterator c_it = any_noccent_at(c, NOE_CORPSE);
if(c_it != noccents[NOE_CORPSE].end()) // corpse might've been removed already
{
noccents[NOE_CORPSE].erase(c_it);
Game::curmap->mod_tile(c)->flags &= ~(TF_NOCCENT);
}
pit->own_pc->set_disguised(true);
string msg = "You are now disguised as the enemy.";
Network::construct_msg(msg, C_BROWN_PC);
Network::send_to_player(*pit);
event_set.insert(c);
}
break;
case C_FIGHTER: // circle strike
{
list<Player>::iterator them;
list<PCEnt>::const_iterator pc_it;
c = pit->own_pc->getpos();
Coords d;
char die = 8, add = 0;
// see if weapon has rusted:
if(pit->cl_props.tohit != classes[pit->cl].tohit)
{
die -= RUST_MOD;
add -= RUST_MOD;
}
for(char ch = 0; ch < 4; ++ch)
{
d = c.in(pit->facing);
if((pc_it = any_pc_at(d)) != PCs.end())
{
them = pc_it->get_owner();
if(test_hit(them, 5, 1, die, add) // was hit...
&& them->cl_props.hp <= 0) // ...and died
{
string msg = " was sliced in half by ";
if(pit->team == them->team)
{
msg += teammate_str;
pit->stats_i->tks++;
}
else
record_kill(pit, WTK_CIRCLE);
player_death(them, msg + pit->nick + '.', true);
}
}
else
add_action_ind(d, A_MISS);
++(pit->facing);
}
break;
}
case C_MINER: // mine
{
c = pit->own_pc->getpos().in(pit->facing);
if(!pit->doing_a_chore) // done
{
// Digging is done; outcome depends on what exactly is there:
Tile* tp = Game::curmap->mod_tile(c);
list<OccEnt>::iterator b_it;
if(tp->symbol == '#') // wall; dig a passage unless NODIG
{
if(tp->flags & TF_NODIG)
{
string msg = "The wall resists.";
Network::construct_msg(msg, C_WALL_LIT);
Network::send_to_player(*pit);
break;
}
dig_open(tp);
finish_wall_dig(c);
}
// windows&doors -- same thing but no NODIG check:
else if(tp->symbol == '|' || tp->symbol == '-' || tp->symbol == '+')
{
dig_open(tp);
if(tp->symbol == '+') // since doors are not seethru
update_lights_around(c);
event_set.insert(c);
}
// Destroying a boulder:
else if(tp->flags & TF_OCCUPIED && (b_it = any_boulder_at(c)) != boulders.end())
{
// boulder; made this far so just destroy it:
boulders.erase(b_it);
tp->flags &= ~(TF_OCCUPIED);
event_set.insert(c);
}
// Carving a new boulder:
else if(tp->flags & TF_NOCCENT
&& any_noccent_at(c, NOE_BLOCK_SOURCE) != noccents[NOE_BLOCK_SOURCE].end())
{
boulders.push_back(OccEnt(c, 'O', C_WALL));
if(tp->flags & TF_OCCUPIED) // we know it's not a boulder!
{
list<PCEnt>::iterator pc_it = any_pc_at(c);
if(pc_it != PCs.end())
{
list<Player>::iterator pit2 = pc_it->get_owner();
string msg = " was squashed by ";
if(pit->team == pit2->team) // note: no team kill recorded
msg += teammate_str;
else
record_kill(pit, WTK_SQUASH);
msg += pit->nick + "\'s carving frenzy.";
player_death(pit2, msg, false);
}
else // may assume it's a missile
any_missile_at(c)->makevoid(); // tile remains occupied by the boulder
}
tp->flags |= TF_OCCUPIED; /* Note: set in any case; if a player
was killed, that cleared the occupied-flag! */
event_set.insert(c);
}
// else it is not possible to finish for some reason
}
else if(cant_dig_in(c, pit->facing))
pit->doing_a_chore = 0; // must abort
else
add_sound(c, S_RUMBLE);
break;
}
case C_TRAPPER: // plant trap
if(!pit->doing_a_chore) // done
{
c = pit->own_pc->getpos();
string msg;
// If there is a trap, disarm it, else plant one:
if(Game::curmap->mod_tile(c)->flags & TF_TRAP)
{
traps.erase(any_trap_at(c));
Game::curmap->mod_tile(c)->flags &= ~TF_TRAP;
msg = "You disarm the trap.";
}
else
{
traps.push_back(Trap(c, TRAP_BOOBY, pit));
traps.back().set_seen_by(pit->team);
Game::curmap->mod_tile(c)->flags |= TF_TRAP;
msg = "You set a boobytrap.";
}
Network::construct_msg(msg, C_BOOBY_TRAP_LIT);
Network::send_to_player(*pit);
}
break;
#ifdef DEBUG
default: // Reaching this is an error!
to_log("Error: progress_chore called with class "
+ lex_cast(pit->cl));
break;
#endif
}
}
bool missile_coll(OwnedEnt* mis, const Coords &c)
{
Tile* tar = Game::curmap->mod_tile(c);
if(!(tar->flags & TF_WALKTHRU))
{
Zap* mis_as_z;
if(tar->symbol != '+' // zaps don't bounce off of doors!
&& (mis_as_z = dynamic_cast<Zap*>(mis)))
{
// Handle zap bouncing off of walls. This is a bit complicated.
Coords now_at = mis->getpos();
/* We want to get the tiles marked by 1 and 2 here, and they are
* defined differently for diagonal/nondiagonal movement:
2 2#
---# /1
1 / */
e_Dir d = mis_as_z->get_dir();
e_Dir dtest = d;
add_sound(now_at.in(d), S_ZAP);
Tile *t1, *t2;
Coords c1, c2;
if(d%2) // a diagonal direction
{
--dtest;
t2 = Game::curmap->mod_tile((c2 = now_at.in(dtest)));
++(++dtest);
t1 = Game::curmap->mod_tile((c1 = now_at.in(dtest)));
}
else // not diagonal dir
{
++(++dtest);
t1 = Game::curmap->mod_tile((c1 = c.in(dtest)));
t2 = Game::curmap->mod_tile((c2 = c.in(!dtest)));
}
// If BOTH or NEITHER of 1&2 are blocked, we bounce back. If exactly one
// is blocked, we bounce to the direction that is not blocked.
if(bool(t1->flags & TF_WALKTHRU) != bool(t2->flags & TF_WALKTHRU))
{
if(t1->flags & TF_WALKTHRU) // go to t1
++(++d);
else // go to t2
{
--(--d);
c1 = c2;
}
// Now 'd' holds the new movement direction and c1 is the next location.
if(mis_as_z->bounce(d))
return true; // didn't have energy to bounce any more
// else: imitate moving to c1:
mis->setpos(c1.in(!d));
return missile_coll(mis, c1);
}
// else both or neither is walkthru; bounce back
if(mis_as_z->bounce(!d))
return true;
mis->setpos(c);
return missile_coll(mis, c.in(!d));
}
//else
mis->makevoid(); // caller has unset occupied flag
add_action_ind(c, A_MISS);
return true;
}
/*else*/ if(tar->flags & TF_OCCUPIED)
{
// There is something. A boulder?
list<OccEnt>::iterator bl_it = any_boulder_at(c);
if(bl_it != boulders.end())
{
// Missile hits a boulder: missile is destroyed.
mis->makevoid(); // caller has unset occ flag for missile; for block no change
add_action_ind(c, A_MISS);
return true;
}
//else: PC?
list<PCEnt>::iterator pc_it = any_pc_at(c);
if(pc_it != PCs.end())
{
missile_hit_PC(pc_it->get_owner(), mis, false);
return true;
}
// else may assume it's another missile.
// Missile hits missile -- both are destroyed:
mis->makevoid();
any_missile_at(c)->makevoid();
Game::curmap->mod_tile(c)->flags &= ~(TF_OCCUPIED);
add_action_ind(c, A_MISS);
return true;
}
// else tile is passable and not occupied -- check for trees:
/*else*/ if(tar->symbol == 'T' && mis->hit_tree())
{
mis->makevoid();
add_action_ind(c, A_MISS);
return true;
}
return false; // no collision or bounced
}
void trap_detection(const list<Player>::iterator pit)
{
unsigned char req_turns = BASE_TURNS_TO_DETECT_TRAPS;
if(pit->cl == C_SCOUT) req_turns = 3*req_turns/4;
else if(pit->cl == C_TRAPPER) req_turns /= 2;
if(pit->turns_without_axn >= req_turns)
{
pit->turns_without_axn = 0; // detection counts as an action!
// Go through traps in a radius of 3 squares:
Coords pos = pit->own_vp->get_pos(); /* Note: using viewpoint's pos
instead of PC's assures that planewalkers can detect traps with mind's eye. */
Coords c;
short f;
char line, ind;
list<Trap>::iterator tr_i;
bool ded = false; // detected any traps?
for(line = 0; line < DETECT_TRAPS_RAD*8; ++line)
{
for(ind = 0; ind < 2*DETECT_TRAPS_RAD; ind += 2)
{
c.x = loslookup[DETECT_TRAPS_RAD-2][line*2*DETECT_TRAPS_RAD+ind] + pos.x;
c.y = loslookup[DETECT_TRAPS_RAD-2][line*2*DETECT_TRAPS_RAD+ind+1] + pos.y;
if(Game::curmap->point_out_of_map(c)
|| !((f = Game::curmap->get_tile(c).flags) & TF_SEETHRU))
break;
else if(f & TF_TRAP && (req_turns < BASE_TURNS_TO_DETECT_TRAPS
|| ((f & TF_LIT) && random()%100 < 75)
|| (!(f & TF_LIT) && random()%100 < 60))
&& !(tr_i = any_trap_at(c))->is_seen_by(pit->team))
{
tr_i->set_seen_by(pit->team);
ded = true;
event_set.insert(c);
}
}
}
if(ded)
{
string msg = "You detect some traps.";
Network::construct_msg(msg, C_FIREB_TRAP);
Network::send_to_player(*pit);
}
} // if should detect traps
}
void arrow_fall(const OwnedEnt* arr, const Coords &c)
{
Tile* tar = Game::curmap->mod_tile(c);
// Arrow falling on a trap might trigger the trap:
if((tar->flags & TF_TRAP) && random()%100 < CHANCE_ARROW_TRIG_TRAP)
{
list<Trap>::iterator tr_it = any_trap_at(c);
// Functionality is somewhat different from trigger_trap(...), but we
// also repeat some functionality here...
switch(tr_it->get_m())
{
case TRAP_WATER:
case TRAP_ACID:
add_sound(c, S_SPLASH);
break;
case TRAP_LIGHT:
flash_at(c);
break;
case TRAP_BOOBY:
add_sound(c, S_CREAK);
// Boobytraps are always destroyed:
traps.erase(tr_it);
tar->flags &= ~(TF_TRAP);
break;
//case TRAP_TELE: // (detected by nothing happening!)
case TRAP_FIREB:
fireball_trigger(c, arr->get_owner(), tr_it->is_seen_by(arr->get_owner()->team));
break;
}
} // trap found there
else
add_action_ind(c, A_MISS);
}
#endif // not maptest build
|
a99ff9d74aed1a8407de66c1c3c115dfca8a8842 | ba5edf42a024e5bd09b8ac5812b9aed29b86f854 | /src/PluginProcessor.h | 8cf276b5ddadbe052d9f42022e02703566041f41 | [
"Apache-2.0"
] | permissive | GuitarML/SmartGuitarAmp | 59d4278c88824499b85989d85b4e2ee3644aa84a | 883944d1b46d03e6e906602db2f15cf24ecb743b | refs/heads/main | 2023-04-30T09:17:24.545782 | 2023-04-11T18:03:36 | 2023-04-11T18:03:36 | 293,843,943 | 465 | 35 | Apache-2.0 | 2023-03-21T23:13:09 | 2020-09-08T15:00:15 | C++ | UTF-8 | C++ | false | false | 4,124 | h | PluginProcessor.h | /*
==============================================================================
This file was auto-generated!
It contains the basic framework code for a JUCE plugin processor.
==============================================================================
*/
#pragma once
#include "../JuceLibraryCode/JuceHeader.h"
#include "WaveNet.h"
#include "WaveNetLoader.h"
#include "Eq4Band.h"
#define CLEAN_GAIN_ID "cleangain"
#define CLEAN_GAIN_NAME "CleanGain"
#define CLEAN_BASS_ID "cleanbass"
#define CLEAN_BASS_NAME "CleanBass"
#define CLEAN_MID_ID "cleanmid"
#define CLEAN_MID_NAME "CleanMid"
#define CLEAN_TREBLE_ID "cleantreble"
#define CLEAN_TREBLE_NAME "CleanTreble"
#define LEAD_GAIN_ID "leadgain"
#define LEAD_GAIN_NAME "LeadGain"
#define LEAD_BASS_ID "leadbass"
#define LEAD_BASS_NAME "LeadBass"
#define LEAD_MID_ID "leadmid"
#define LEAD_MID_NAME "LeadMid"
#define LEAD_TREBLE_ID "leadtreble"
#define LEAD_TREBLE_NAME "LeadTreble"
#define PRESENCE_ID "presence"
#define PRESENCE_NAME "Presence"
#define MASTER_ID "master"
#define MASTER_NAME "Master"
//==============================================================================
/**
*/
class WaveNetVaAudioProcessor : public AudioProcessor
{
public:
//==============================================================================
WaveNetVaAudioProcessor();
~WaveNetVaAudioProcessor();
//==============================================================================
void prepareToPlay (double sampleRate, int samplesPerBlock) override;
void releaseResources() override;
#ifndef JucePlugin_PreferredChannelConfigurations
bool isBusesLayoutSupported (const BusesLayout& layouts) const override;
#endif
void processBlock (AudioBuffer<float>&, MidiBuffer&) override;
//==============================================================================
AudioProcessorEditor* createEditor() override;
bool hasEditor() const override;
//==============================================================================
const String getName() const override;
bool acceptsMidi() const override;
bool producesMidi() const override;
bool isMidiEffect() const override;
double getTailLengthSeconds() const override;
//==============================================================================
int getNumPrograms() override;
int getCurrentProgram() override;
void setCurrentProgram (int index) override;
const String getProgramName (int index) override;
void changeProgramName (int index, const String& newName) override;
//==============================================================================
void getStateInformation (MemoryBlock& destData) override;
void setStateInformation (const void* data, int sizeInBytes) override;
void loadConfigAmp();
void set_ampEQ(float bass_slider, float mid_slider, float treble_slider, float presence_slider);
// Pedal/amp states
int amp_state = 1; // 0 = off, 1 = on
int amp_lead = 1; // 1 = clean, 0 = lead
int custom_tone = 0; // 0 = custom tone loaded, 1 = default channel tone
double gui_scale_factor = 1.0;
File loaded_tone;
juce::String loaded_tone_name;
AudioProcessorValueTreeState treeState;
private:
WaveNet waveNet; // Amp Clean Channel / Lead Channel
Eq4Band eq4band; // Amp EQ
std::atomic<float>* presenceParam = nullptr;
std::atomic<float>* cleanBassParam = nullptr;
std::atomic<float>* cleanMidParam = nullptr;
std::atomic<float>* cleanTrebleParam = nullptr;
std::atomic<float>* cleanGainParam = nullptr;
std::atomic<float>* leadGainParam = nullptr;
std::atomic<float>* leadBassParam = nullptr;
std::atomic<float>* leadMidParam = nullptr;
std::atomic<float>* leadTrebleParam = nullptr;
std::atomic<float>* masterParam = nullptr;
float previousGainValue = 0.5;
float previousMasterValue = 0.5;
var dummyVar;
//==============================================================================
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WaveNetVaAudioProcessor)
};
|
a2eb65b05a16f470e405c9eee66f6c86f16c266f | ccac8bf0c462ed112726ac4e11578a4a2ed83228 | /compiler/code/IR/IRInstr/CmpMnemonics/IRInstrCmp_ge.h | dcf1a967b5e400a9d46118f4faf2d2d8504fa1ca | [
"MIT"
] | permissive | kenza-bouzid/PLD-COMP-H4242 | 16821ca45dcfe97e05dd2a83ead58379e7844060 | a72dcf4bd6dab6e5d2b825aa58c5e3560917490e | refs/heads/master | 2022-05-10T09:37:07.259924 | 2020-04-10T11:18:31 | 2020-04-10T11:18:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 288 | h | IRInstrCmp_ge.h | #pragma once
#include "../IRInstr.h"
class IRInstrCmp_ge : public IRInstr
{
private:
/* data */
string dest;
string op1;
string op2;
public:
IRInstrCmp_ge(BasicBlock *bb_, string dest, string op1, string op2);
void gen_asm(ostream &o);
~IRInstrCmp_ge();
};
|
e4a4a5c16b2dab88febc10a02cb8508ca65bf4d8 | eeda19981e21fc916b83ed4ed624fa427577ac46 | /Codeforces Solutions/1535-C_UnstableString.cpp | 0eb6fc3fadae0e0791d261f844f7c7981e041862 | [] | no_license | omarsamy09/Competitive-Programming-solutions | 1b54c5f856d92f76754ccac8cbb863c70cbd1e79 | bfafed917a507f7bbb9336f40a6fe2a9e9ca139d | refs/heads/main | 2023-07-16T02:53:40.189965 | 2021-08-20T23:07:59 | 2021-08-20T23:07:59 | 398,418,712 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 56 | cpp | 1535-C_UnstableString.cpp | https://codeforces.com/contest/1535/submission/118457961 |
a7a4405b43175c9e6cfa1010d605c487308544ed | cadb836d9ac9c9e3b618cf44c936015a0aea24a8 | /daily_challenge/2023/LT_2023-03-03_28._Find_the_Index_of_the_First_Occurrence_in_a_String.cpp | 7dfa3b953ec0c0901963ad0c73b86ab79f5001a9 | [] | no_license | checkoutb/LeetCodeCCpp | c6341a9fa5583a69046555a892bb41052624e83c | 38832f7ccadf26b781cd8c9783c50916d1380554 | refs/heads/master | 2023-09-03T22:35:50.266523 | 2023-09-03T06:31:51 | 2023-09-03T06:31:51 | 182,722,336 | 0 | 1 | null | null | null | null | GB18030 | C++ | false | false | 1,664 | cpp | LT_2023-03-03_28._Find_the_Index_of_the_First_Occurrence_in_a_String.cpp |
#include "../../header/myheader.h"
class LT
{
public:
// D D
//for (int i = 0; ; i++) {
// for (int j = 0; ; j++) {
// if (j == needle.length()) return i;
// if (i + j == haystack.length()) return -1;
// if (needle.charAt(j) != haystack.charAt(i + j)) break;
// }
//}
// 看和写差很多。。
//Runtime0 ms
// Beats
// 100 %
// Memory6.2 MB
// Beats
// 69.99 %
// kmp. sunday, bm ... but...
// hash rolling
// sunday.
int lta(string haystack, string needle)
{
int arr[123] = { 0 };
int sz1 = haystack.size();
int sz2 = needle.size();
if (sz2 > sz1)
return -1;
for (int i = 0; i < sz2; ++i)
{
//if (arr[needle[i]] == 0)
arr[needle[i]] = sz2 - i; // 最后出现的位置 到 模式串的尾巴 + 1.
}
for (int i = 'a'; i <= 'z'; ++i)
if (arr[i] == 0)
arr[i] = sz2 + 1; // 没有出现 则等于 模式串.size + 1
for (int i = 0; i < sz1; )
{
for (int j = 0; j < sz2; ++j)
{
if (haystack[i + j] != needle[j])
goto AAA;
}
return i;
AAA:
i += (i + sz2 < sz1) ? arr[haystack[i + sz2]] : 1; // 检查 i + sz2 这个 char
}
return -1;
}
};
int main()
{
LT lt;
//string s1 = "sadbutsad";
//string s2 = "but";
string s1 = "aaaaa";
string s2 = "bba";
cout << lt.lta(s1, s2) << endl;
return 0;
}
|
5c2d68d0dc1478602b99cd47db6e3bd126002bb9 | 7215052282fabbad6a4e81efd71a2a1a2c94d1f6 | /Assignments/Assignment 3/main3.cpp | a8e8d540eb332ee314cde0dc7ee6e1005274fb0f | [] | no_license | DEVANSH-DVJ/CS213-Autumn-2020 | e19dbeffaeeeec9ad3c1e2b07aa9d64e1a935d9c | fe5daa86f9aac85de0a2b594deda983d8347f139 | refs/heads/master | 2023-04-16T01:06:40.401732 | 2021-04-29T12:03:33 | 2021-04-29T12:03:33 | 300,065,499 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 375 | cpp | main3.cpp | #include "190100044_3.h"
using namespace std;
int main() {
quad_tree qt1(2);
qt1.set(0, 2, 1, 3, 1);
qt1.print();
cout << endl;
qt1.resize(3);
qt1.set(3, 7, 3, 7, 0);
qt1.print();
cout << endl;
qt1.resize(2);
qt1.print();
cout << endl;
qt1.resize(3);
qt1.print();
cout << endl;
qt1.resize(6);
qt1.print();
cout << endl;
return 0;
}
|
85de24e11663381a6357c7b96b3871310eb7554d | 2809ed9c1589d07a799d77c147a54e57ae483312 | /fluid.cpp | c93853161966f0e5a3d55edf121890f1f17d4ba1 | [] | no_license | adilijiang/SPH-1 | d460e3130206214cc15874cefdb61737f05b73dc | 443bfb2252eadb43cc7a36b1c82af4660fd20192 | refs/heads/master | 2020-04-27T07:05:12.579101 | 2018-10-31T13:48:46 | 2018-10-31T13:48:46 | 174,126,601 | 5 | 1 | null | 2019-03-06T10:48:23 | 2019-03-06T10:48:23 | null | UTF-8 | C++ | false | false | 13,838 | cpp | fluid.cpp | #include "fluid.hpp"
const float fluidVolume = 1000 * MASS / REST_DENSITY;
const float particleDiameter = powf(fluidVolume, 1.0f / 3.0f) / 10;
const float particleRadius = particleDiameter / 2;
Fluid::Fluid( void ) {
for (float x = -particleRadius * 9; x <= particleRadius * 9; x += particleDiameter) {
for (float y = -particleRadius * 9; y <= particleRadius * 9; y += particleDiameter) {
for (float z = -particleRadius * 9; z <= particleRadius * 9; z += particleDiameter)
mParticles.push_back(Particle(MASS, Vector3f(x, y, z)));
}
}
}
void Fluid::draw( void ) {
float sphereRadius = powf((3 * MASS) / (4 * M_PI * REST_DENSITY), 1.0f / 3.0f);
for (int i = 0; i < mParticles.size(); i++) {
glPushMatrix();
glTranslatef(mParticles[i].mPosition.x, mParticles[i].mPosition.y, mParticles[i].mPosition.z);
glutSolidSphere(sphereRadius, 30, 30);
glPopMatrix();
}
glDisable(GL_LIGHTING);
glColor3f(1.0f, 1.0f, 1.0f);
// Draw bottom surface edges of the box
glBegin(GL_LINE_LOOP);
glVertex3f(-BOX_SIZE / 2, -BOX_SIZE / 2, -BOX_SIZE / 2);
glVertex3f( BOX_SIZE / 2, -BOX_SIZE / 2, -BOX_SIZE / 2);
glVertex3f( BOX_SIZE / 2, -BOX_SIZE / 2, BOX_SIZE / 2);
glVertex3f(-BOX_SIZE / 2, -BOX_SIZE / 2, BOX_SIZE / 2);
glEnd();
// Draw top surface edges of the box
glBegin(GL_LINE_LOOP);
glVertex3f(-BOX_SIZE / 2, BOX_SIZE / 2, -BOX_SIZE / 2);
glVertex3f( BOX_SIZE / 2, BOX_SIZE / 2, -BOX_SIZE / 2);
glVertex3f( BOX_SIZE / 2, BOX_SIZE / 2, BOX_SIZE / 2);
glVertex3f(-BOX_SIZE / 2, BOX_SIZE / 2, BOX_SIZE / 2);
glEnd();
// Draw left surface edges of the box
glBegin(GL_LINE_LOOP);
glVertex3f(-BOX_SIZE / 2, BOX_SIZE / 2, -BOX_SIZE / 2);
glVertex3f(-BOX_SIZE / 2, BOX_SIZE / 2, BOX_SIZE / 2);
glVertex3f(-BOX_SIZE / 2, -BOX_SIZE / 2, BOX_SIZE / 2);
glVertex3f(-BOX_SIZE / 2, -BOX_SIZE / 2, -BOX_SIZE / 2);
glEnd();
// Draw right surface edges of the box
glBegin(GL_LINE_LOOP);
glVertex3f( BOX_SIZE / 2, BOX_SIZE / 2, -BOX_SIZE / 2);
glVertex3f( BOX_SIZE / 2, BOX_SIZE / 2, BOX_SIZE / 2);
glVertex3f( BOX_SIZE / 2, -BOX_SIZE / 2, BOX_SIZE / 2);
glVertex3f( BOX_SIZE / 2, -BOX_SIZE / 2, -BOX_SIZE / 2);
glEnd();
glColor3f(1.0f, 0.0f, 0.0f);
// Draw x-axis
glBegin(GL_LINES);
glVertex3f(-BOX_SIZE, 0.0f, 0.0f);
glVertex3f( BOX_SIZE, 0.0f, 0.0f);
glEnd();
// Draw y-axis
glBegin(GL_LINES);
glVertex3f(0.0f, -BOX_SIZE, 0.0f);
glVertex3f(0.0f, BOX_SIZE, 0.0f);
glEnd();
// Draw z-axis
glBegin(GL_LINES);
glVertex3f(0.0f, 0.0f, -BOX_SIZE);
glVertex3f(0.0f, 0.0f, BOX_SIZE);
glEnd();
glEnable(GL_LIGHTING);
}
void Fluid::simulate( void ) {
// Compute density and pressure
for (int i = 0; i < mParticles.size(); i++) {
mParticles[i].mDensity = calcDensity(mParticles[i].mPosition);
mParticles[i].mPressure = calcPressure(mParticles[i].mDensity);
}
// Compute internal forces
for (int i = 0; i < mParticles.size(); i++) {
mParticles[i].mPressureForce = calcPressureForce(i, mParticles[i].mDensity, mParticles[i].mPressure, mParticles[i].mPosition);
mParticles[i].mViscosityForce = calcViscosityForce(i, mParticles[i].mVelocity, mParticles[i].mPosition);
}
// Compute external forces
for (int i = 0; i < mParticles.size(); i++) {
mParticles[i].mGravitationalForce = calcGravitationalForce(mParticles[i].mDensity);
mParticles[i].mSurfaceNormal = calcSurfaceNormal(mParticles[i].mPosition);
if (mParticles[i].mSurfaceNormal.length() >= THRESHOLD)
mParticles[i].mSurfaceTensionForce = calcSurfaceTensionForce(mParticles[i].mSurfaceNormal, mParticles[i].mPosition);
else
mParticles[i].mSurfaceTensionForce = Vector3f(0.0f, 0.0f, 0.0f);
}
// Time integration and collision handling
static float time = 0.0f;
time += TIME_STEP;
Vector3f totalForce;
for (int i = 0; i < mParticles.size(); i++) {
//totalForce = mParticles[i].mPressureForce + mParticles[i].mViscosityForce + mParticles[i].mSurfaceTensionForce;
totalForce = mParticles[i].mPressureForce + mParticles[i].mViscosityForce + mParticles[i].mGravitationalForce + mParticles[i].mSurfaceTensionForce;
employEulerIntegrator(mParticles[i], totalForce);
Vector3f contactPoint;
Vector3f unitSurfaceNormal;
if (detectCollision(mParticles[i], contactPoint, unitSurfaceNormal)) {
updateVelocity(mParticles[i].mVelocity, unitSurfaceNormal, (mParticles[i].mPosition - contactPoint).length());
mParticles[i].mPosition = contactPoint;
}
}
}
float Fluid::calcDensity( Vector3f position ) {
float sum = 0.0f;
for (int j = 0; j < mParticles.size(); j++)
sum += mParticles[j].mMass * useDefaultKernel(position - mParticles[j].mPosition, SUPPORT_RADIUS);
return sum;
}
float Fluid::calcPressure( float density ) {
return GAS_STIFFNESS * (density - REST_DENSITY);
}
Vector3f Fluid::calcPressureForce( int indexOfCurrentParticle, float density, float pressure, Vector3f position ) {
Vector3f sum(0.0f, 0.0f, 0.0f);
for (int j = 0; j < mParticles.size(); j++) {
if (j == indexOfCurrentParticle)
continue;
sum += usePressureKernel_gradient(position - mParticles[j].mPosition, SUPPORT_RADIUS) * (pressure / (density * density) + mParticles[j].mPressure / (mParticles[j].mDensity * mParticles[j].mDensity)) * mParticles[j].mMass;
}
return -(sum * density);
}
Vector3f Fluid::calcViscosityForce( int indexOfCurrentParticle, Vector3f velocity, Vector3f position ) {
Vector3f sum(0.0f, 0.0f, 0.0f);
for (int j = 0; j < mParticles.size(); j++) {
if (j == indexOfCurrentParticle)
continue;
sum += (mParticles[j].mVelocity - velocity) * (mParticles[j].mMass / mParticles[j].mDensity) * useViscosityKernel_laplacian(position - mParticles[j].mPosition, SUPPORT_RADIUS);
}
return sum * VISCOSITY;
}
Vector3f Fluid::calcGravitationalForce( float density ) {
return GRAVITATIONAL_ACCELERATION * density;
}
Vector3f Fluid::calcSurfaceNormal( Vector3f position ) {
Vector3f sum(0.0f, 0.0f, 0.0f);
for (int j = 0; j < mParticles.size(); j++)
sum += useDefaultKernel_gradient(position - mParticles[j].mPosition, SUPPORT_RADIUS) * (mParticles[j].mMass / mParticles[j].mDensity);
return sum;
}
Vector3f Fluid::calcSurfaceTensionForce( Vector3f surfaceNormal, Vector3f position ) {
float sum = 0.0f;
for (int j = 0; j < mParticles.size(); j++)
sum += (mParticles[j].mMass / mParticles[j].mDensity) * useDefaultKernel_laplacian(position - mParticles[j].mPosition, SUPPORT_RADIUS);
return -(surfaceNormal.normalize() * SURFACE_TENSION * sum);
}
void Fluid::employEulerIntegrator( Particle &particle, Vector3f totalForce ) {
particle.mAcceleration = totalForce / particle.mDensity;
particle.mVelocity = particle.mVelocity + particle.mAcceleration * TIME_STEP;
particle.mPosition = particle.mPosition + particle.mVelocity * TIME_STEP;
}
bool Fluid::detectCollision( Particle particle, Vector3f &contactPoint, Vector3f &unitSurfaceNormal ) {
if (abs(particle.mPosition.x) <= BOX_SIZE / 2 && abs(particle.mPosition.y) <= BOX_SIZE / 2 && abs(particle.mPosition.z) <= BOX_SIZE / 2)
return false;
char maxComponent = 'x';
float maxValue = abs(particle.mPosition.x);
if (maxValue < abs(particle.mPosition.y)) {
maxComponent = 'y';
maxValue = abs(particle.mPosition.y);
}
if (maxValue < abs(particle.mPosition.z)) {
maxComponent = 'z';
maxValue = abs(particle.mPosition.z);
}
// 'unitSurfaceNormal' is based on the current position component with the largest absolute value
switch (maxComponent) {
case 'x':
if (particle.mPosition.x < -BOX_SIZE / 2) {
contactPoint = particle.mPosition; contactPoint.x = -BOX_SIZE / 2;
if (particle.mPosition.y < -BOX_SIZE / 2) contactPoint.y = -BOX_SIZE / 2;
else if (particle.mPosition.y > BOX_SIZE / 2) contactPoint.y = BOX_SIZE / 2;
if (particle.mPosition.z < -BOX_SIZE / 2) contactPoint.z = -BOX_SIZE / 2;
else if (particle.mPosition.z > BOX_SIZE / 2) contactPoint.z = BOX_SIZE / 2;
unitSurfaceNormal = Vector3f( 1.0f, 0.0f, 0.0f);
}
else if (particle.mPosition.x > BOX_SIZE / 2) {
contactPoint = particle.mPosition; contactPoint.x = BOX_SIZE / 2;
if (particle.mPosition.y < -BOX_SIZE / 2) contactPoint.y = -BOX_SIZE / 2;
else if (particle.mPosition.y > BOX_SIZE / 2) contactPoint.y = BOX_SIZE / 2;
if (particle.mPosition.z < -BOX_SIZE / 2) contactPoint.z = -BOX_SIZE / 2;
else if (particle.mPosition.z > BOX_SIZE / 2) contactPoint.z = BOX_SIZE / 2;
unitSurfaceNormal = Vector3f(-1.0f, 0.0f, 0.0f);
}
break;
case 'y':
if (particle.mPosition.y < -BOX_SIZE / 2) {
contactPoint = particle.mPosition; contactPoint.y = -BOX_SIZE / 2;
if (particle.mPosition.x < -BOX_SIZE / 2) contactPoint.x = -BOX_SIZE / 2;
else if (particle.mPosition.x > BOX_SIZE / 2) contactPoint.x = BOX_SIZE / 2;
if (particle.mPosition.z < -BOX_SIZE / 2) contactPoint.z = -BOX_SIZE / 2;
else if (particle.mPosition.z > BOX_SIZE / 2) contactPoint.z = BOX_SIZE / 2;
unitSurfaceNormal = Vector3f( 0.0f, 1.0f, 0.0f);
}
else if (particle.mPosition.y > BOX_SIZE / 2) {
contactPoint = particle.mPosition; contactPoint.y = BOX_SIZE / 2;
if (particle.mPosition.x < -BOX_SIZE / 2) contactPoint.x = -BOX_SIZE / 2;
else if (particle.mPosition.x > BOX_SIZE / 2) contactPoint.x = BOX_SIZE / 2;
if (particle.mPosition.z < -BOX_SIZE / 2) contactPoint.z = -BOX_SIZE / 2;
else if (particle.mPosition.z > BOX_SIZE / 2) contactPoint.z = BOX_SIZE / 2;
unitSurfaceNormal = Vector3f( 0.0f, -1.0f, 0.0f);
}
break;
case 'z':
if (particle.mPosition.z < -BOX_SIZE / 2) {
contactPoint = particle.mPosition; contactPoint.z = -BOX_SIZE / 2;
if (particle.mPosition.x < -BOX_SIZE / 2) contactPoint.x = -BOX_SIZE / 2;
else if (particle.mPosition.x > BOX_SIZE / 2) contactPoint.x = BOX_SIZE / 2;
if (particle.mPosition.y < -BOX_SIZE / 2) contactPoint.y = -BOX_SIZE / 2;
else if (particle.mPosition.y > BOX_SIZE / 2) contactPoint.y = BOX_SIZE / 2;
unitSurfaceNormal = Vector3f( 0.0f, 0.0f, 1.0f);
}
else if (particle.mPosition.z > BOX_SIZE / 2) {
contactPoint = particle.mPosition; contactPoint.z = BOX_SIZE / 2;
if (particle.mPosition.x < -BOX_SIZE / 2) contactPoint.x = -BOX_SIZE / 2;
else if (particle.mPosition.x > BOX_SIZE / 2) contactPoint.x = BOX_SIZE / 2;
if (particle.mPosition.y < -BOX_SIZE / 2) contactPoint.y = -BOX_SIZE / 2;
else if (particle.mPosition.y > BOX_SIZE / 2) contactPoint.y = BOX_SIZE / 2;
unitSurfaceNormal = Vector3f( 0.0f, 0.0f, -1.0f);
}
break;
}
return true;
}
void Fluid::updateVelocity( Vector3f &velocity, Vector3f unitSurfaceNormal, float penetrationDepth ) {
velocity = velocity - unitSurfaceNormal * (1 + RESTITUTION * penetrationDepth / (TIME_STEP * velocity.length())) * velocity.dot(unitSurfaceNormal);
}
float Fluid::useDefaultKernel( Vector3f distVector, float supportRadius ) {
float dist = distVector.length();
if (dist > supportRadius)
return 0.0f;
else
return (315 / (64 * M_PI * powf(supportRadius, 9.0f))) * powf(supportRadius * supportRadius - dist * dist, 3.0f);
}
Vector3f Fluid::useDefaultKernel_gradient( Vector3f distVector, float supportRadius ) {
float dist = distVector.length();
if (dist > supportRadius)
return Vector3f(0.0f, 0.0f, 0.0f);
else
return -(distVector * (945 / (32 * M_PI * powf(supportRadius, 9.0f))) * powf(supportRadius * supportRadius - dist * dist, 2.0f));
}
float Fluid::useDefaultKernel_laplacian( Vector3f distVector, float supportRadius ) {
float dist = distVector.length();
if (dist > supportRadius)
return 0.0f;
else
return -(945 / (32 * M_PI * powf(supportRadius, 9.0f))) * (supportRadius * supportRadius - dist * dist) * (3 * supportRadius * supportRadius - 7 * dist * dist);
}
Vector3f Fluid::usePressureKernel_gradient( Vector3f distVector, float supportRadius ) {
float dist = distVector.length();
if (dist > supportRadius)
return Vector3f(0.0f, 0.0f, 0.0f);
else if (dist < 10e-5) // If ||r|| -> 0+
return -(Vector3f(1.0f, 1.0f, 1.0f).normalize() * (45 / (M_PI * powf(supportRadius, 6.0f))) * powf(supportRadius - dist, 2.0f));
else
return -(distVector.normalize() * (45 / (M_PI * powf(supportRadius, 6.0f))) * powf(supportRadius - dist, 2.0f));
}
float Fluid::useViscosityKernel_laplacian( Vector3f distVector, float supportRadius ) {
float dist = distVector.length();
if (dist > supportRadius)
return 0.0f;
else
return (45 / (M_PI * powf(supportRadius, 6.0f))) * (supportRadius - dist);
} |
d3f0ab98fb109981334c727b1220f4ea5511d7ae | 893b49242c4e6e1c39bced06262f0b527b92f761 | /Semester_3/Programming/Task2/Task2/RB_Tree.h | f240d851e4361aba553a8b080502037c3655a03d | [] | no_license | chastis/UniversityStuff | a9e1896ef8bf63e22fc9aae8b9661dfcb5ad398a | cfc2730c9b66d287a128c822d171a8f3e384ed8e | refs/heads/master | 2022-12-09T09:17:15.762297 | 2021-04-14T17:44:50 | 2021-04-14T17:44:50 | 215,631,068 | 48 | 14 | null | 2022-12-08T08:10:37 | 2019-10-16T19:45:58 | C++ | WINDOWS-1251 | C++ | false | false | 4,728 | h | RB_Tree.h | #ifndef RBTREE_H
#define RBTREE_H
#include<stdio.h>
#include<stdlib.h>
// коды ошибок
#define ERROR_STRUCT 1
#define ERROR_BALANCE 2
#define SIZE 1000 //!< размер массива проверки
//! статистика (можно удалить для ускорения процесса)
struct stat_st {
struct st {
int max_count; //!< рекодрное количество поворотов за раз
int sum_count; //!< сумарное число поворотов
int sum_divider; //!< количество операций, для вычисления среднего
};
int max_depth; //!< глубина маскимального узла
int black_depth; //!< чёрная глубина дерева
int nodes_count; //!< количество вершин в дереве
int turn_count; //!< количество выполненых за раз поворотов (включая вложенные)
st insert; //!< статистика вставки
st remove; //!< статистика удаления
};
// value - значение
// p1,p2 - левая правая ветка
// red - цвет (true - если красный)
struct node_st { node_st *p1, *p2; int value; bool red; }; // структура узла
// класс красно-черноое дерево
class RBTree {
private:
node_st *tree_root; //!< корень
// внутрение функции
//! выделение новой вершины
node_st *NewItem(int value);
//! удаление вершины
void DelItem(node_st *node);
//! снос дерева (рекурсивная часть)
void Clear(node_st *node);
//! вывод дерева, рекурсивная часть
//! \param node узел
//! \param depth глубина
//! \param dir значёк
//! \code Show(root,0,'*'); \endcode
void Show(node_st *node, int depth, char dir);
//! вращение влево
//! \param index индеск вершины
//! \result новая вершина дерева
node_st *Rotate21(node_st *node);
//! вращение вправо
//! \param index индеск вершины
//! \result новая вершина дерева
node_st *Rotate12(node_st *node);
//! балансировка вершины
void BalanceInsert(node_st **root);
bool BalanceRemove1(node_st **root);
bool BalanceRemove2(node_st **root);
//! рекурсивная часть вставки
//! \result true если изменений небыло или балансировка в данной вершине не нужна
bool Insert(int value, node_st **root);
//! найти и убрать максимальный узел поддерева
//! \param root корень дерева в котором надо найти элемент
//! \retval res эелемент который был удалён
//! \result true если нужен баланс
bool GetMin(node_st **root, node_st **res);
//! рекурсивная часть удаления
//! \result true если нужен баланс
bool Remove(node_st **root, int value);
//проверки
//! проверка дерева (рекурсивная часть)
//! \param tree дерево
//! \param b_d текущая чёрная глубина
//! \param d текущая обычная глубина
//! \param h эталонная чёрная глубина
//! \result 0 или код ошибки
int Check(node_st *tree, int b_d, int d);
//! обход дерева и сверка значений с массивом (рекурсивная часть)
//! \param node корень дерева
//! \param array массив для сверки
//! \param size размер массива
bool TreeWalk(node_st *node, bool *array, int size);
public:
stat_st stat; //! статистика (можно удалить для ускорения процесса)
// внешние функции
// конструктор
RBTree() {
tree_root = NULL;
}
//! обновление статистики вставки/удаления
void UpdateStat(stat_st::st &item);
//! вывод дерева
void Show();
//! функция вставки
void Insert(int value);
//! удаление узла
void Remove(int value);
//! снос дерева
void Clear();
//! проверка дерева
int Check();
//! обход дерева и сверка значений с массивом
//! \param array массив для сверки
//! \param size размер массива
bool TreeWalk(bool *array, int size);
};
#endif // RBTREE_H
|
edfd63cd29ad63adbaffefcf314eb6a9ab45cc07 | 36183993b144b873d4d53e7b0f0dfebedcb77730 | /GameDevelopment/Programming AI By Example/Buckland_Chapter7 to 10_Raven/Raven_SensoryMemory.h | 447f990d9c659e2f810f5a5578e1e77774484e6d | [] | no_license | alecnunn/bookresources | b95bf62dda3eb9b0ba0fb4e56025c5c7b6d605c0 | 4562f6430af5afffde790c42d0f3a33176d8003b | refs/heads/master | 2020-04-12T22:28:54.275703 | 2018-12-22T09:00:31 | 2018-12-22T09:00:31 | 162,790,540 | 20 | 14 | null | null | null | null | UTF-8 | C++ | false | false | 3,812 | h | Raven_SensoryMemory.h | #ifndef RAVEN_SENSORY_SYSTEM_H
#define RAVEN_SENSORY_SYSTEM_H
#pragma warning (disable:4786)
//-----------------------------------------------------------------------------
//
// Name:
//
// Author: Mat Buckland (ai-junkie.com)
//
// Desc:
//
//-----------------------------------------------------------------------------
#include <map>
#include <list>
#include "2d/vector2d.h"
class Raven_Bot;
class MemoryRecord
{
public:
//records the time the opponent was last sensed (seen or heard). This
//is used to determine if a bot can 'remember' this record or not.
//(if CurrentTime() - m_dTimeLastSensed is greater than the bot's
//memory span, the data in this record is made unavailable to clients)
double fTimeLastSensed;
//it can be useful to know how long an opponent has been visible. This
//variable is tagged with the current time whenever an opponent first becomes
//visible. It's then a simple matter to calculate how long the opponent has
//been in view (CurrentTime - fTimeBecameVisible)
double fTimeBecameVisible;
//it can also be useful to know the last time an opponent was seen
double fTimeLastVisible;
//a vector marking the position where the opponent was last sensed. This can
// be used to help hunt down an opponent if it goes out of view
Vector2D vLastSensedPosition;
//set to true if opponent is within the field of view of the owner
bool bWithinFOV;
//set to true if there is no obstruction between the opponent and the owner,
//permitting a shot.
bool bShootable;
MemoryRecord():fTimeLastSensed(-999),
fTimeBecameVisible(-999),
fTimeLastVisible(0),
bWithinFOV(false),
bShootable(false)
{}
};
class Raven_SensoryMemory
{
private:
typedef std::map<Raven_Bot*, MemoryRecord> MemoryMap;
private:
//the owner of this instance
Raven_Bot* m_pOwner;
//this container is used to simulate memory of sensory events. A MemoryRecord
//is created for each opponent in the environment. Each record is updated
//whenever the opponent is encountered. (when it is seen or heard)
MemoryMap m_MemoryMap;
//a bot has a memory span equivalent to this value. When a bot requests a
//list of all recently sensed opponents this value is used to determine if
//the bot is able to remember an opponent or not.
double m_dMemorySpan;
//this methods checks to see if there is an existing record for pBot. If
//not a new MemoryRecord record is made and added to the memory map.(called
//by UpdateWithSoundSource & UpdateVision)
void MakeNewRecordIfNotAlreadyPresent(Raven_Bot* pBot);
public:
Raven_SensoryMemory(Raven_Bot* owner, double MemorySpan);
//this method is used to update the memory map whenever an opponent makes
//a noise
void UpdateWithSoundSource(Raven_Bot* pNoiseMaker);
//this removes a bot's record from memory
void RemoveBotFromMemory(Raven_Bot* pBot);
//this method iterates through all the opponents in the game world and
//updates the records of those that are in the owner's FOV
void UpdateVision();
bool isOpponentShootable(Raven_Bot* pOpponent)const;
bool isOpponentWithinFOV(Raven_Bot* pOpponent)const;
Vector2D GetLastRecordedPositionOfOpponent(Raven_Bot* pOpponent)const;
double GetTimeOpponentHasBeenVisible(Raven_Bot* pOpponent)const;
double GetTimeSinceLastSensed(Raven_Bot* pOpponent)const;
double GetTimeOpponentHasBeenOutOfView(Raven_Bot* pOpponent)const;
//this method returns a list of all the opponents that have had their
//records updated within the last m_dMemorySpan seconds.
std::list<Raven_Bot*> GetListOfRecentlySensedOpponents()const;
void RenderBoxesAroundRecentlySensed()const;
};
#endif |
6059e0e3e6970c32990e72e251f447063a47f5aa | 768ab62df6534b3071dffbbd8143cdca5bd48045 | /cacheTable/test.cpp | 0e40f4fc9ee0eec6dbab5bc8bd36665f30f2f3f7 | [] | no_license | terry-chelsea/terry | e40113cb0528ecd3f6b0a671d8b9643ec7805f71 | b2606afd87bdb79b4df25dc4e80587b252cfc9d1 | refs/heads/master | 2020-05-18T13:13:35.768997 | 2014-03-06T15:04:04 | 2014-03-06T15:04:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,571 | cpp | test.cpp | /*
* =====================================================================================
*
* Filename: test.cpp
*
* Description: tyest cache table
*
* Version: 1.0
* Created: 07/06/12 18:30:52
* Revision: none
* Compiler: gcc
*
* Author: (fengyuatad@126.com), yu
* Company: NDSL
*
* =====================================================================================
*/
#include "cacheTable.h"
#include <iostream>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <time.h>
#include <stdlib.h>
using namespace std;
#define FILE_NAME "./testFile"
#define MAXLINE 4096
#define FILE_MODE S_IRUSR | S_IWUSR
#define TEST_TIMES 10737418240
#define GLOBLE_SIZE 15904800768
long long glo_debug = 0;
int main(int argc , char *argv[])
{
long long globleSize = GLOBLE_SIZE;
long long fileSize = globleSize >> 3;
int fd = open(FILE_NAME , O_RDWR | O_CREAT | O_TRUNC , FILE_MODE);
int writeBytes = 0;
while(writeBytes < fileSize)
{
int size = fileSize - writeBytes;
size = (size > MAXLINE) ? MAXLINE : size;
char temp[MAXLINE];
memset(temp , 0 , MAXLINE);
write(fd , temp , size);
writeBytes += size;
}
CacheTable *cacheTable = new CacheTable(globleSize , fd);
srand(time(NULL));
long long i = 0;
long long times = TEST_TIMES / 1024;
for(i = 0 ; i < times ; ++ i)
{
cacheTable->appendItem(rand() % globleSize);
}
delete cacheTable;
return 0;
}
|
b8a65cbca1dad715f66bac011c80ca396ebec21e | 851cbeaa5577bf249c55263bccd4640e0f68e452 | /iCyberSecurity-master/iCyberSecurity-master/iCyberSecurity/Customer.cpp | b08e053d1e472e25d2acb78b0530ee8f857fff7c | [] | no_license | shatfield4/iCyberSecurity | 444cfee72a023a53418d54ff0fe13cc1c07ce943 | 2857ae9e3ab31de091e72f09dc094062bf5ec262 | refs/heads/master | 2020-07-24T12:19:02.479866 | 2019-10-23T22:58:06 | 2019-10-23T22:58:06 | 207,922,948 | 0 | 2 | null | 2019-10-23T22:03:20 | 2019-09-11T23:15:54 | C++ | UTF-8 | C++ | false | false | 3,202 | cpp | Customer.cpp | #include "Customer.h"
#include "order.h"
#include <string>
void Customer::setName(std::string x)
{
//setting the input value to the objects name
name=x;
};
void Customer::setKey(std::string x)
{
//setting the input value to the objects keylevel
keyLevel=x;
}
void Customer::setPamphlet(bool x)
{
//setting the input value to the objects receivedPamphlet
receivedPamphlet = x;
};
void Customer::setAddress1(std::string x)
{
//setting the input value to the objects address1
address1= x;
};
void Customer::setAddress2(std::string x)
{
//setting the input value to the objects address2
address2= x;
};
void Customer::setInterest(std::string x)
{
//setting the input value to the objects interest
interest=x;
};
order Customer::getCustomerOrder()
{
return *customersOrder;
}
//getters
std::string Customer::getName()
{
//returns the objects name
return name;
};
std::string Customer::getKey()
{
//returns the objects name
return keyLevel;
};
bool Customer::getPamphlet()
{
//returns true if the customer has received a pamphlet
return receivedPamphlet;
};
std::string Customer::getAddress1()
{
//returns the first address line
return address1;
};
std::string Customer::getAddress2()
{
//returns the second address line
return address2;
};
std::string Customer::getInterest()
{
//returns the objects interest
return interest;
};
//constructors
Customer::Customer()
{
//sets all strings to "NOT SET"
//sets that the customer has not recieved a pamphlet (false)
name="NOT SET";
keyLevel= "NOT SET";
receivedPamphlet=false;
address1="NOT SET";
address2="NOT SET";
interest="NOT SET";
customersOrder = new order;
};
Customer::Customer(std::string xname,std::string xKey,bool xpamphlet, std::string xaddress1, std::string xaddress2, std::string xinterest)
{
//sets all the variables according to the input variables
name=xname;
keyLevel = xKey;
receivedPamphlet=xpamphlet;
address1=xaddress1;
address2=xaddress2;
interest=xinterest;
customersOrder = new order;
};
//!copy constructor
Customer::Customer(const Customer &c2)
{
name=c2.name;
keyLevel = c2.keyLevel;
receivedPamphlet= c2.receivedPamphlet;
address1= c2.address1;
address2=c2.address2;
interest=c2.interest;
customersOrder= new order;
*customersOrder=*c2.customersOrder;
}
//misc
//! operator overload
Customer Customer::operator = (Customer const &c2)
{
name=c2.name;
keyLevel = c2.keyLevel;
receivedPamphlet= c2.receivedPamphlet;
address1= c2.address1;
address2=c2.address2;
interest=c2.interest;
delete customersOrder;
customersOrder= new order(*c2.customersOrder);
return *this;
};
//comparisons
bool Customer:: isMynamebigger(Customer x)
{
//returns true of the name if this objects name is greater
if(name.compare(x.name)>0)
{
return true;
}
else return false;
};
bool Customer::isMykeybigger(Customer x)
{
//returns true this objects key is greater
if(keyLevel > x.keyLevel)
{
return true;
}
else return false;
};
|
5281bc8f1bc8f3e58726ce8b86d513e895f8cd80 | b4fd892821fa86eee37d53e0c307ad610d67ed42 | /题目练习/牛客/牛客/字符串排序.cpp | 68fe9db69f895b378719621ce8ef9b6c09450a83 | [] | no_license | Empty0Qc/New-Empty | 0fcfa4e35af5bdbe173c4f092493ec127bf37e93 | a05673052fea0ef97db695d9488e12c51f6a2a75 | refs/heads/master | 2020-04-01T06:36:47.636480 | 2019-10-24T05:44:38 | 2019-10-24T05:44:38 | 150,874,112 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,681 | cpp | 字符串排序.cpp | ////#include <iostream>
////#include <string>
////#include <vector>
////#include <queue>
////using namespace std;
////
////int main()
////{
//// string s;
//// while (getline(cin, s))
//// {
//// vector<string> v(s.size(), "");
//// vector<queue<char>> vq(26);
//// for (size_t i = 0;i < s.size(); ++i)
//// {
//// if (!isupper(s[i]) && !islower(s[i]))
//// {
//// v[i] = s[i];
//// }
//// else
//// {
//// if (isupper(s[i]))
//// vq[s[i] - 'A'].push(s[i]);
//// else
//// vq[s[i] - 'a'].push(s[i]);
//// }
//// }
//// size_t i, j = 0;
//// for (i = 0;i < s.size();)
//// {
//// while (i < s.size() && v[i] != "") ++i;
//// while (j < 26 && vq[j].empty())j++;
//// if (j >= 26)
//// continue;
//// v[i] = vq[j].front();
//// vq[j].pop();
//// }
//// for (auto e : v)
//// cout << e;
//// cout << endl;
//// }
//// return 0;
////}
////
////
////#include <iostream>
////using namespace std;
////
////uint64_t ReverseBit(uint64_t num)
////{
//// uint64_t ret = 0;
//// //uint64_t tmp = 1;
////
//// int count = 63;
//// while (count--)
//// {
//// ret |= (num & 1);
//// num <<= 1;
//// ret <<= 1;
//// }
//// return ret;
////}
////
////int main()
////{
//// //cout << ReverseBit(1);
////
//// return 0;
////}
//
//
//
////#include <iostream>
////#include <vector>
////#include <algorithm>
////using namespace std;
////
////typedef struct Box {
//// int o = 0, j = 0;
////}Box;
////
////typedef struct Key {
//// int o = 0, j = 0;
////}Key;
////
////int main()
////{
//// int n, m;
//// while (cin >> n >> m)
//// {
//// Box box;
//// Key key;
//// int tmp;
//// for (int i = 0; i < n; ++i)
//// {
//// cin >> tmp;
//// if (tmp & 1)
//// ++box.j;
//// else
//// ++box.o;
//// }
//// for (int i = 0; i < m; ++i)
//// {
//// cin >> tmp;
//// if (tmp & 1)
//// ++key.j;
//// else
//// ++key.o;
//// }
//// cout << min(box.j, key.o) + min(box.o, key.j) << endl;
//// }
//// return 0;
////}
//
//
//#include <iostream>
//#include <vector>
//#include <algorithm>
//using namespace std;
//
//struct Info {
// int id,a, b;
//};
//
//int main()
//{
// int n;
// while (cin >> n)
// {
// Info info;
// int sum = 99999;
// vector<Info> v;
// for (int i = 0; i < n; ++i)
// {
// cin >> info.a >> info.b;
// info.id = i;
// v.push_back(info);
// }
// //sort(v.begin(), v.end(), [](Info& m, Info& n) {return m.a > n.a; });
// int i = 0;
// do
// {
// int tmp = 0;
// for (auto &e : v)
// {
// tmp += (e.a * e.id + e.b * (n - e.id - 1));
// e.id = (e.id + 1) % n;
// }
// sum = min(sum, tmp);
// ++i;
// } while (i % n != 0);
// cout << sum << endl;
// }
// return 0;
//} |
df20724469d249ae53b0d9fce7fa6d57fcab3a06 | 42ab733e143d02091d13424fb4df16379d5bba0d | /third_party/libassimp/include/assimp/SmoothingGroups.h | 92d65cea022349b1784d1d42a6213bf86282495a | [
"Apache-2.0",
"CC0-1.0",
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause",
"LGPL-2.0-or-later"
] | permissive | google/filament | 11cd37ac68790fcf8b33416b7d8d8870e48181f0 | 0aa0efe1599798d887fa6e33c412c09e81bea1bf | refs/heads/main | 2023-08-29T17:58:22.496956 | 2023-08-28T17:27:38 | 2023-08-28T17:27:38 | 143,455,116 | 16,631 | 1,961 | Apache-2.0 | 2023-09-14T16:23:39 | 2018-08-03T17:26:00 | C++ | UTF-8 | C++ | false | false | 3,803 | h | SmoothingGroups.h | /*
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2019, assimp team
All rights reserved.
Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the
following conditions are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
* Neither the name of the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
----------------------------------------------------------------------
*/
/** @file Defines the helper data structures for importing 3DS files.
http://www.jalix.org/ressources/graphics/3DS/_unofficials/3ds-unofficial.txt */
#ifndef AI_SMOOTHINGGROUPS_H_INC
#define AI_SMOOTHINGGROUPS_H_INC
#include <assimp/vector3.h>
#include <stdint.h>
#include <vector>
// ---------------------------------------------------------------------------
/** Helper structure representing a face with smoothing groups assigned */
struct FaceWithSmoothingGroup {
FaceWithSmoothingGroup() AI_NO_EXCEPT
: mIndices()
, iSmoothGroup(0) {
// in debug builds set all indices to a common magic value
#ifdef ASSIMP_BUILD_DEBUG
this->mIndices[0] = 0xffffffff;
this->mIndices[1] = 0xffffffff;
this->mIndices[2] = 0xffffffff;
#endif
}
//! Indices. .3ds is using uint16. However, after
//! an unique vertex set has been generated,
//! individual index values might exceed 2^16
uint32_t mIndices[3];
//! specifies to which smoothing group the face belongs to
uint32_t iSmoothGroup;
};
// ---------------------------------------------------------------------------
/** Helper structure representing a mesh whose faces have smoothing
groups assigned. This allows us to reuse the code for normal computations
from smoothings groups for several loaders (3DS, ASE). All of them
use face structures which inherit from #FaceWithSmoothingGroup,
but as they add extra members and need to be copied by value we
need to use a template here.
*/
template <class T>
struct MeshWithSmoothingGroups
{
//! Vertex positions
std::vector<aiVector3D> mPositions;
//! Face lists
std::vector<T> mFaces;
//! List of normal vectors
std::vector<aiVector3D> mNormals;
};
// ---------------------------------------------------------------------------
/** Computes normal vectors for the mesh
*/
template <class T>
void ComputeNormalsWithSmoothingsGroups(MeshWithSmoothingGroups<T>& sMesh);
// include implementations
#include "SmoothingGroups.inl"
#endif // !! AI_SMOOTHINGGROUPS_H_INC
|
12cb047fe7605c560638005acd23fa624cf8e889 | 3602bb2a59034e923f394d7b48551ffcb9852295 | /src/joke.cc | 72bc403d59a4be4c2e80e9f1b81640ecc4b705c1 | [] | no_license | tome2/tome2 | dc9ba21fd03b3ec226c57ace092d39f3878fe9ab | 2209ab83f31967b6ca0b1ba6ef298bde5a82fbd4 | refs/heads/master | 2023-06-09T02:01:42.438028 | 2023-02-10T10:48:54 | 2023-02-10T10:50:30 | 48,683,757 | 91 | 40 | null | 2023-06-03T13:53:57 | 2015-12-28T09:00:04 | C++ | UTF-8 | C++ | false | false | 729 | cc | joke.cc | #include "joke.hpp"
#include "monster2.hpp"
#include "options.hpp"
#include "util.hpp"
#include "variable.hpp"
#include "z-rand.hpp"
static void gen_joke_place_monster(int r_idx)
{
int try_;
for (try_ = 0; try_ < 1000; try_++)
{
int x = randint(cur_hgt - 4) + 2;
int y = randint(cur_wid - 4) + 2;
if (place_monster_one(y, x, r_idx, 0, false, MSTATUS_ENEMY))
{
return;
}
}
}
bool gen_joke_monsters(void *data, void *in, void *out)
{
if (options->joke_monsters)
{
if ((dungeon_type == 20) &&
(dun_level == 72))
{
int r_idx = test_monster_name("Neil, the Sorceror");
m_allow_special[r_idx] = true;
gen_joke_place_monster(r_idx);
m_allow_special[r_idx] = false;
}
}
return false;
}
|
0f3d22ac358813d69995ea91c5cd0607d19da635 | b479cf43f17746458fb71e9fc925c7436a0c89b8 | /Math/Source/Vector/Vector3Int.cpp | eaf3db5c1b4292bff9ab06802265d62cd523cdc9 | [] | no_license | nazariyb/FRTEngine | ff14b828002cfcba9fe6c7782b6a649af851d821 | 3b3de2cedd07e8f4572b608b9a9f7aa34450c83a | refs/heads/master | 2023-04-23T10:27:36.776640 | 2021-05-16T11:01:37 | 2021-05-16T11:01:37 | 312,707,014 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,469 | cpp | Vector3Int.cpp | #include "Vector3Int.h"
namespace PROJECT_NAMESPACE
{
Vector3Int::Vector3Int()
: Vector3Int(0)
{}
Vector3Int::Vector3Int(const Vector2Int& XYVector, int Z /*= 0*/)
{
_data = XYVector._data;
SetZ(Z);
}
Vector3Int::Vector3Int(int X, const Vector2Int& YZVector)
{
_data = DirectX::XMVectorSetInt(X, YZVector.GetX(), YZVector.GetY(), 0);
}
Vector3Int::Vector3Int(const Vector3Int& Other)
{
_data = Other._data;
}
Vector3Int& Vector3Int::operator=(const Vector3Int Other)
{
_data = Other._data;
return *this;
}
Vector3Int::Vector3Int(int Value)
: Vector2Int(Value)
{}
Vector3Int::Vector3Int(int X, int Y, int Z/*=0*/)
{
_data = DirectX::XMVectorSetInt(X, Y, Z, 0);
}
Vector3Int::Vector3Int(const int DataSource[])
: Vector3Int(DataSource[0], DataSource[1], DataSource[2])
{}
Vector3Int::Vector3Int(const std::pair<int, int>& XYDataSource, int Z /*= 0*/)
: Vector3Int(XYDataSource.first, XYDataSource.second, Z)
{}
Vector3Int::Vector3Int(int X, const std::pair<int, int>& YZDataSource)
: Vector3Int(X, YZDataSource.first, YZDataSource.second)
{}
Vector3Int::Vector3Int(const std::tuple<int, int>& XYDataSource, int Z /*= 0*/)
: Vector3Int(std::get<0>(XYDataSource), std::get<1>(XYDataSource), Z)
{}
Vector3Int::Vector3Int(int X, const std::tuple<int, int>& YZDataSource)
: Vector3Int(X, std::get<0>(YZDataSource), std::get<1>(YZDataSource))
{}
Vector3Int::Vector3Int(const std::tuple<int, int, int>& DataSource)
: Vector3Int(std::get<0>(DataSource), std::get<1>(DataSource), std::get<2>(DataSource))
{}
Vector3Int::Vector3Int(const std::vector<int>& DataSource)
{
// TODO: assert size of DataSource
_data = DirectX::XMVectorSetInt(DataSource[0], DataSource[1], DataSource[2], 0);
}
Vector3Int::Vector3Int(const DirectX::XMVECTOR& DataSource)
{
_data = DataSource;
}
Vector3Int::Vector3Int(const DirectX::XMINT3& DataSource)
: Vector3Int(DataSource.x, DataSource.y, DataSource.z)
{}
Vector3Int::~Vector3Int()
{}
inline int Vector3Int::GetZ() const
{
return DirectX::XMVectorGetIntZ(_data);
}
inline void Vector3Int::SetZ(int Value)
{
_data = DirectX::XMVectorSetIntZ(_data, Value);
}
inline int Vector3Int::DotProduct(const Vector3Int& Other) const
{
return GetX() * Other.GetX() + GetY() * Other.GetY() + GetZ() * Other.GetZ();
}
inline Vector3Int Vector3Int::CrossProduct(const Vector3Int& Other) const
{
return {
GetY() * Other.GetZ() - GetZ() * Other.GetY(),
GetZ() * Other.GetX() - GetX() * Other.GetZ(),
GetX() * Other.GetY() - GetY() * Other.GetX()
};
}
//inline float Vector3Int::GetMagnitudeSquared() const
//{
//
//}
//
//inline float Vector3Int::GetMagnitudeEstimated() const
//{
//
//}
inline Vector3Int Vector3Int::GetNormalized() const
{
// TODO: must return float vector
return { DirectX::XMVector3Normalize(_data) };
}
inline std::string Vector3Int::GetAsString() const
{
return "<"
+ std::to_string(GetX()) + ", "
+ std::to_string(GetY()) + ", "
+ std::to_string(GetZ()) + ">";
}
inline float Vector3Int::GetAngleInDegreesWith(const Vector3Int& Other) const
{
return DirectX::XMConvertToDegrees(GetAngleInRadiansWith(Other));
}
inline float Vector3Int::GetAngleInRadiansWith(const Vector3Int& Other) const
{
// TODO: make it work with int
return GetSingleValueFromReplicatedVector(DirectX::XMVector3AngleBetweenVectors(_data, Other._data));
}
inline int Vector3Int::DotProduct(const Vector3Int& lhs, const Vector3Int& rhs)
{
return lhs.DotProduct(rhs);
}
inline Vector3Int Vector3Int::CrossProduct(const Vector3Int& lhs, const Vector3Int& rhs)
{
return lhs.CrossProduct(rhs);
}
inline float Vector3Int::GetAngleInDegreesBetween(const Vector3Int& lhs, const Vector3Int& rhs)
{
return lhs.GetAngleInDegreesWith(rhs);
}
inline float Vector3Int::GetAngleInRadiansBetween(const Vector3Int& lhs, const Vector3Int& rhs)
{
return lhs.GetAngleInRadiansWith(rhs);
}
inline Vector3Int Vector3Int::GetZeroVector()
{
return { DirectX::XMVectorZero() };
}
inline Vector3Int Vector3Int::GetSplatOneVector()
{
return { DirectX::XMVectorSplatOne() };
}
#pragma region Operators
inline Vector3Int operator+(const Vector3Int& lhs, const Vector3Int& rhs)
{
return {
(int)(lhs._data.m128_i32[0] + rhs._data.m128_i32[0]),
(int)(lhs._data.m128_i32[1] + rhs._data.m128_i32[1]),
(int)(lhs._data.m128_i32[2] + rhs._data.m128_i32[2])
};
}
inline Vector3Int operator+(int Scalar, const Vector3Int& Vector)
{
return { DirectX::XMVectorReplicateInt(Scalar) + Vector };
}
inline Vector3Int operator+(const Vector3Int& Vector, int Scalar)
{
return Scalar + Vector;
}
inline Vector3Int operator-(const Vector3Int& lhs, const Vector3Int& rhs)
{
return {
(int)(lhs._data.m128_i32[0] - rhs._data.m128_i32[0]),
(int)(lhs._data.m128_i32[1] - rhs._data.m128_i32[1]),
(int)(lhs._data.m128_i32[2] - rhs._data.m128_i32[2])
};
}
inline Vector3Int operator-(const Vector3Int& Vector, int Scalar)
{
return { Vector - DirectX::XMVectorReplicateInt(Scalar) };
}
inline int operator*(const Vector3Int& lhs, const Vector3Int& rhs)
{
return lhs.DotProduct(rhs);
}
inline Vector3Int operator*(int Scalar, const Vector3Int& Vector)
{
return {
(int)Vector._data.m128_i32[0] * Scalar,
(int)Vector._data.m128_i32[1] * Scalar,
(int)Vector._data.m128_i32[2] * Scalar,
};
}
inline Vector3Int operator*(const Vector3Int& Vector, int Scalar)
{
return Scalar * Vector;
}
inline bool operator==(const Vector3Int& lhs, const Vector3Int& rhs)
{
return DirectX::XMVectorGetIntX(lhs._data) == DirectX::XMVectorGetIntX(rhs._data)
&& DirectX::XMVectorGetIntY(lhs._data) == DirectX::XMVectorGetIntY(rhs._data)
&& DirectX::XMVectorGetIntZ(lhs._data) == DirectX::XMVectorGetIntZ(rhs._data);
}
inline bool operator==(int Scalar, const Vector3Int& Vector)
{
return Vector3Int(DirectX::XMVectorReplicateInt(Scalar)) == Vector;
}
inline bool operator==(const Vector3Int& Vector, int Scalar)
{
return Scalar == Vector;
}
inline bool operator!=(const Vector3Int& lhs, const Vector3Int& rhs)
{
return !(lhs == rhs);
}
inline bool operator!=(int Scalar, const Vector3Int& Vector)
{
return !(Scalar == Vector);
}
inline bool operator!=(const Vector3Int& Vector, int Scalar)
{
return !(Vector == Scalar);
}
#pragma endregion
}
|
0113c738b6cef6ce136d4e2677161c3c8d69a3c9 | 2a1340292895cd8217aa297b1e0159738784615f | /源码/TankGame/MapTank.cpp | 66e1173e43a2ebe961c692c81a3e1eeaa60fff4b | [] | no_license | mountainCold/c- | 5deb7beb6733565e23a110b516187f1aa98cb08f | 7bfd39b0b160683bc36b15db47c8ff808e52244a | refs/heads/master | 2020-07-09T21:14:48.888825 | 2019-08-24T00:03:42 | 2019-08-24T00:03:42 | 204,085,726 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 4,662 | cpp | MapTank.cpp | #include "MapTank.h"
MapTank Map;
MapTank g_InitMap;
MapTank g_EditMap;
MapTank g_ReadMap;
void MapTank::SetMap(int x, int y, int val)
{
nMap[y][x] = val;
}
int MapTank::GetMapVal(int x, int y)
{
if (x < 0 || y < 0 || x>59 || y>49)
{
return -1;
}
return nMap[y][x];
}
void MapTank::WriteMap()
{
//画边界
for (int i = 59; i < 70; i++)
{
for (int j = 0; j < 50; j++)
{
if (i == 59 || i == 69 || j == 0 || j == 49)
{
WriteChar(i, j, "■");
}
}
}
for (int i = 0; i < 60; i++)
{
for (int j = 0; j < 50; j++)
{
if (nMap[j][i] == 铁墙)
{
WriteChar(i, j, "■", 7);
}
if (nMap[j][i] == 土墙)
{
WriteChar(i, j, "▓", 6);
}
if (nMap[j][i] >= 草丛)
{
WriteChar(i, j, "※", 5);
}
if (nMap[j][i] == 河流)
{
WriteChar(i, j, "∷", 5);
}
if (nMap[j][i] == 基地)
{
WriteChar(i, j, "⊙", 9);
}
}
}
}
void MapTank::InitMap()
{
for (int i = 0; i < 60; i++)
{
for (int j = 0; j < 50; j++)
{
if (i == 0 || i == 59 || j == 0 || j == 49)
{
nMap[j][i] = 铁墙;
}
}
}
for (int j = 46; j < 49; j++)
{
for (int i = 28; i < 32; i++)
{
if (i > 28 && i < 31 && j>46 && j <= 48)
{
nMap[j][i] = 基地;
}
else
{
//nMap[j][i] = 铁墙;
nMap[j][i] = 土墙;
}
}
}
}
void MapTank::WriteEditMap()
{
//画边界
for (int i = 59; i < 70; i++)
{
for (int j = 0; j < 50; j++)
{
if (i == 59 || i == 69 || j == 0 || j == 49)
{
WriteChar(i, j, "■");
}
}
}
for (int i = 0; i < 60; i++)
{
for (int j = 0; j < 50; j++)
{
if (nMap[j][i] == 铁墙)
{
WriteChar(i, j, "■", 7);
}
if (nMap[j][i] == 土墙)
{
WriteChar(i, j, "▓", 6);
}
if (nMap[j][i] >= 草丛)
{
WriteChar(i, j, "※", 5);
}
if (nMap[j][i] == 河流)
{
WriteChar(i, j, "∷", 5);
}
if (nMap[j][i] == 基地)
{
WriteChar(i, j, "⊙", 9);
}
}
}
}
void MapTank::EditMap()
{
system("cls");
g_EditMap.WriteMap();
WriteChar(63, 3, "坦克大战", 7);
WriteChar(61, 5, "编辑说明:", 7);
WriteChar(61, 7, "点击击以下图标:", 7);
WriteChar(62, 8, "选择物体:", 7);
WriteChar(61, 10, "左键绘制:", 7);
WriteChar(61, 12, "点击清空:", 4);
const char* str = "▓";
int num = 土墙;
WriteChar(61, 15, "▓▓ 土墙", 6);
WriteChar(61, 17, "■■ 铁墙", 7);
WriteChar(61, 19, "※※ 草丛", 3);
WriteChar(61, 21, "∷∷ 河流", 4);
WriteChar(61, 23, "XXXX 空地");
WriteChar(61, 26, "点击");
WriteChar(63, 26, "退出", 4);
WriteChar(61, 28, "点击");
WriteChar(63, 28, "保存本地", 4);
bool bedit = true;
int nMessage = 0;
while (bedit)
{
ShowCuror();
nMessage = MessageListener(1);
if (nMessage == 27)
{
bedit = false;
system("cls");
}
else if (nMessage == 13)
{
SaveMap();
ReadName();
}
if (MousePos.X >= 2 && MousePos.X < 118 && MousePos.Y>0 && MousePos.Y < 49)
{
if (MousePos.X > 56 && MousePos.X < 62 && MousePos.Y>46 && MousePos.Y <= 48)
{
}
else
{
if (num == 10)
{
WriteChar(MousePos.X / 2, MousePos.Y, str, 9);
}
else if (num == 30)
{
WriteChar(MousePos.X / 2, MousePos.Y, str, 5);
}
else
{
WriteChar(MousePos.X / 2, MousePos.Y, str, 8 - num);
}
g_EditMap.SetMap(MousePos.X / 2, MousePos.Y, num);
}
}
else if (MousePos.X >= 122 && MousePos.X <= 134 && MousePos.Y == 15)
{
str = "▓";
num = 土墙;
}
else if (MousePos.X >= 122 && MousePos.X <= 134 && MousePos.Y == 17)
{
str = "■";
num = 铁墙;
}
else if (MousePos.X >= 122 && MousePos.X <= 134 && MousePos.Y == 19)
{
str = "※";
num = 草丛;
}
else if (MousePos.X >= 122 && MousePos.X <= 134 && MousePos.Y == 21)
{
str = "∷";
num = 河流;
}
else if (MousePos.X >= 122 && MousePos.X <= 134 && MousePos.Y == 23)
{
str = " ";
num = 空地;
}
else if (MousePos.X >= 122 && MousePos.X <= 134 && MousePos.Y == 26)
{
bedit = false;
system("cls");
}
else if (MousePos.X >= 122 && MousePos.X <= 134 && MousePos.Y == 12)
{
g_EditMap.Clear();
}
else if (MousePos.X >= 122 && MousePos.X <= 134 && MousePos.Y == 28)
{
SaveMap();
ReadName();
bedit = false;
}
MousePos = { 0,0 };
}
system("cls");
}
void MapTank::Clear()
{
for (int i=1;i<59;++i)
{
for (int j=1;j<49;++j)
{
if (nMap[j][i]!=基地)
{
WriteChar(i, j, " ");
nMap[j][i] = 0;
}
}
}
}
bool MapTank::operator=( MapTank map)
{
for (int i = 0; i < 50; i++)
{
for (int j = 0; j < 60; j++)
{
nMap[i][j] =map.GetMapVal(j,i);
}
}
return true;
}
|
09036abb3807b8685c86e76dd2750ac0d483b593 | 861cd69248ccc4b6b03831d8d6f7e53486a13701 | /src/libsnw_compiler/grammar/snw_error_rules.cpp | afe10834b136263ebb4dd403600097009c3890fe | [
"MIT"
] | permissive | Sojourn/snowda | 410570facac441e36e807d3978eb807a5dc15b73 | 432118a9ae561b8d6119cd34d1935a08a70e49cc | refs/heads/master | 2020-04-06T07:00:06.416401 | 2016-08-05T01:13:35 | 2016-08-05T01:13:35 | 54,746,985 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 317 | cpp | snw_error_rules.cpp | #include "../snw_compiler.h"
using namespace Snowda;
using namespace Snowda::Ast;
ExprResult Snowda::errorNud(Parser &parser, Token token)
{
return ParserError(token, token.content);
}
ExprResult Snowda::errorLed(Parser &parser, const Expr *left, Token token)
{
return ParserError(token, token.content);
}
|
ca7b44aa4db62133230e5038e58210b8d5118973 | afb7006e47e70c1deb2ddb205f06eaf67de3df72 | /third_party/libwebrtc/test/pc/e2e/analyzer_helper.cc | 539db38ea560867585f441c8b67f3356d4a9c26e | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] | permissive | marco-c/gecko-dev-wordified | a66383f85db33911b6312dd094c36f88c55d2e2c | 3509ec45ecc9e536d04a3f6a43a82ec09c08dff6 | refs/heads/master | 2023-08-10T16:37:56.660204 | 2023-08-01T00:39:54 | 2023-08-01T00:39:54 | 211,297,590 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,189 | cc | analyzer_helper.cc | /
*
*
Copyright
(
c
)
2019
The
WebRTC
project
authors
.
All
Rights
Reserved
.
*
*
Use
of
this
source
code
is
governed
by
a
BSD
-
style
license
*
that
can
be
found
in
the
LICENSE
file
in
the
root
of
the
source
*
tree
.
An
additional
intellectual
property
rights
grant
can
be
found
*
in
the
file
PATENTS
.
All
contributing
project
authors
may
*
be
found
in
the
AUTHORS
file
in
the
root
of
the
source
tree
.
*
/
#
include
"
test
/
pc
/
e2e
/
analyzer_helper
.
h
"
#
include
<
string
>
#
include
<
utility
>
namespace
webrtc
{
namespace
webrtc_pc_e2e
{
AnalyzerHelper
:
:
AnalyzerHelper
(
)
{
signaling_sequence_checker_
.
Detach
(
)
;
}
void
AnalyzerHelper
:
:
AddTrackToStreamMapping
(
absl
:
:
string_view
track_id
absl
:
:
string_view
receiver_peer
absl
:
:
string_view
stream_label
absl
:
:
optional
<
std
:
:
string
>
sync_group
)
{
RTC_DCHECK_RUN_ON
(
&
signaling_sequence_checker_
)
;
track_to_stream_map_
.
insert
(
{
std
:
:
string
(
track_id
)
StreamInfo
{
.
receiver_peer
=
std
:
:
string
(
receiver_peer
)
.
stream_label
=
std
:
:
string
(
stream_label
)
.
sync_group
=
sync_group
.
has_value
(
)
?
*
sync_group
:
std
:
:
string
(
stream_label
)
}
}
)
;
}
void
AnalyzerHelper
:
:
AddTrackToStreamMapping
(
std
:
:
string
track_id
std
:
:
string
stream_label
)
{
RTC_DCHECK_RUN_ON
(
&
signaling_sequence_checker_
)
;
track_to_stream_map_
.
insert
(
{
std
:
:
move
(
track_id
)
StreamInfo
{
stream_label
stream_label
}
}
)
;
}
void
AnalyzerHelper
:
:
AddTrackToStreamMapping
(
std
:
:
string
track_id
std
:
:
string
stream_label
std
:
:
string
sync_group
)
{
RTC_DCHECK_RUN_ON
(
&
signaling_sequence_checker_
)
;
track_to_stream_map_
.
insert
(
{
std
:
:
move
(
track_id
)
StreamInfo
{
std
:
:
move
(
stream_label
)
std
:
:
move
(
sync_group
)
}
}
)
;
}
AnalyzerHelper
:
:
StreamInfo
AnalyzerHelper
:
:
GetStreamInfoFromTrackId
(
absl
:
:
string_view
track_id
)
const
{
RTC_DCHECK_RUN_ON
(
&
signaling_sequence_checker_
)
;
auto
track_to_stream_pair
=
track_to_stream_map_
.
find
(
std
:
:
string
(
track_id
)
)
;
RTC_CHECK
(
track_to_stream_pair
!
=
track_to_stream_map_
.
end
(
)
)
;
return
track_to_stream_pair
-
>
second
;
}
}
/
/
namespace
webrtc_pc_e2e
}
/
/
namespace
webrtc
|
5f39ab29f410102d92c3618f60cd55c2c55cc295 | eb518b01f6ee07565ae7b3d4d8c08036ee2c07c1 | /joystick.cpp | e7c01c1098e3cb20c1081dc2e5c42620121524f3 | [] | no_license | zsimpson/zbslib | 98928507a38f9ab8959c339f8d9082ad02bfbef0 | 431c2e8588ff0da7c91d8799c5c01a70fd6e6c01 | refs/heads/master | 2020-04-15T21:04:32.064026 | 2018-11-10T04:17:54 | 2018-11-10T04:17:54 | 10,534,718 | 3 | 2 | null | 2018-10-01T19:16:13 | 2013-06-06T19:31:00 | C++ | UTF-8 | C++ | false | false | 3,694 | cpp | joystick.cpp | #include "joystick.h"
#include "tmsg.h"
#include "string.h"
//#include "windows.h"
// The following lines duplicate the code needed from windows.h
// In case of a compile problem, comment out the following and
// uncomment the above includes.
extern "C" {
struct JOYINFO {
unsigned intwXpos;
unsigned intwYpos;
unsigned intwZpos;
unsigned intwButtons;
};
struct JOYINFOEX {
unsigned long dwSize;
unsigned long dwFlags;
unsigned long dwXpos;
unsigned long dwYpos;
unsigned long dwZpos;
unsigned long dwRpos;
unsigned long dwUpos;
unsigned long dwVpos;
unsigned long dwButtons;
unsigned long dwButtonNumber;
unsigned long dwPOV;
unsigned long dwReserved1;
unsigned long dwReserved2;
};
typedef unsigned int MMRESULT;
__declspec(dllimport) MMRESULT __stdcall joyGetNumDevs(void);
__declspec(dllimport) MMRESULT __stdcall joyGetPos(unsigned int uJoyID, JOYINFO *pji);
__declspec(dllimport) MMRESULT __stdcall joyGetPosEx(unsigned int uJoyID, JOYINFOEX *pji);
#define JOYSTICKID1 0
#define JOYSTICKID2 1
#define JOYERR_NOERROR (0)
#define JOY_RETURNX 0x00000001l
#define JOY_RETURNY 0x00000002l
#define JOY_RETURNZ 0x00000004l
#define JOY_RETURNR 0x00000008l
#define JOY_RETURNU 0x00000010l
#define JOY_RETURNV 0x00000020l
#define JOY_RETURNPOV 0x00000040l
#define JOY_RETURNBUTTONS 0x00000080l
#define JOY_RETURNCENTERED 0x00000400l
#define JOY_RETURNALL (JOY_RETURNX | JOY_RETURNY | JOY_RETURNZ | JOY_RETURNR | JOY_RETURNU | JOY_RETURNV | JOY_RETURNPOV | JOY_RETURNBUTTONS)
}
// End Windows.h duplication
// Local
int joy = 0;
int joyWhichDevice = -1;
// Public
float joyX = 0.f;
float joyY = 0.f;
float joyZ = 0.f;
float joyR = 0.f;
float joyPOV = 0.f;
int joyButtons[32] = {0,};
float joyXLast = 0.f;
float joyYLast = 0.f;
float joyZLast = 0.f;
float joyRLast = 0.f;
float joyPOVLast = 0.f;
int joyButtonsLast[32] = {0,};
int joyInit() {
joy = 0;
JOYINFO joyinfo;
int numJoysticks = joyGetNumDevs();
if( numJoysticks == 0 ) {
return 0;
}
int joy1Attached = joyGetPos(JOYSTICKID1,&joyinfo) == JOYERR_NOERROR;
int joy2Attached = numJoysticks == 2 && joyGetPos(JOYSTICKID2,&joyinfo) == JOYERR_NOERROR;
// DECIDE which joystick to use
if( joy1Attached || joy2Attached ) {
joyWhichDevice = joy1Attached ? JOYSTICKID1 : JOYSTICKID2;
joy = 1;
return 1;
}
return 0;
}
int joySample() {
if( joyWhichDevice != -1 ) {
JOYINFOEX joyInfoEx;
joyInfoEx.dwSize = sizeof(joyInfoEx);
joyInfoEx.dwFlags = JOY_RETURNALL | JOY_RETURNCENTERED;
MMRESULT ret = joyGetPosEx( joyWhichDevice, &joyInfoEx );
if( ret == JOYERR_NOERROR ) {
// SAVE the old values
joyXLast = joyX;
joyYLast = joyY;
joyZLast = joyZ;
joyRLast = joyR;
joyPOVLast = joyPOV;
memcpy( joyButtonsLast, joyButtons, sizeof(joyButtonsLast) );
// NORMALIZE the new values
joyX = (float)joyInfoEx.dwXpos / 65536.f;
joyY = (float)joyInfoEx.dwYpos / 65536.f;
joyZ = (float)joyInfoEx.dwZpos / 65536.f;
joyR = (float)joyInfoEx.dwRpos / 65536.f;
for( int i=0; i<32; i++ ) {
joyButtons[i] = joyInfoEx.dwButtons & (1 << i);
}
joyPOV = (float)joyInfoEx.dwPOV / 36000.f;
// SCAN for button changes and generate events on state changes
for( i=0; i<32; i++ ) {
if( joyButtonsLast[i] != joyButtons[i] ) {
if( joyButtons[i] ) {
tMsgQueue( "type=JoyButtonPress which=%d", i );
}
else {
tMsgQueue( "type=JoyButtonRelease which=%d", i );
}
}
}
}
return 1;
}
return 0;
}
|
6717d7fc512ef904eed53558b16483a20413ec08 | 283a140827c6df4befa331c7fa89aba882b00e45 | /Random/11995_UVA.cpp | 31c61234f2c55bab83541c76f68685ba37d02924 | [
"MIT"
] | permissive | limafabio/CompetitiveProgramming | f0c32805fcab0cc1d0a340088e44fe4bd36e3942 | cacd9d78687f5bfe77eb1eb8c6030ec1c843f0c7 | refs/heads/master | 2022-09-26T05:24:39.125498 | 2022-09-07T19:18:00 | 2022-09-07T19:18:00 | 33,583,377 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,373 | cpp | 11995_UVA.cpp | #include<stdio.h>
#include<stdlib.h>
#include<vector>
#include<algorithm>
#include<string.h>
#include<math.h>
#include<queue>
#include<stack>
#include<map>
#include<set>
#include<iostream>
using namespace std;
#define min(x,y) x < y ? x : y
#define max(x,y) x > y ? x : y
typedef pair<int, int> ii;
typedef vector<ii> vii;
int main(){
queue<int> q;
stack<int> s;
priority_queue<int> p;
int n,a,b,resp;
bool stack_out, queue_out, priority_out;
while (scanf("%d\n",&n) > 0){
stack_out = queue_out = priority_out = true;
for (int i = 0 ; i < n;i++){
scanf("%d %d\n",&a,&b);
if (1 == a){
s.push(b);
q.push(b);
p.push(b);
} else {
if (!s.empty()){
if (s.top() != b) stack_out = false;
s.pop();
if (q.front() != b) queue_out = false;
q.pop();
if (p.top() != b) priority_out = false;
p.pop();
} else stack_out = queue_out = priority_out = false;
}
}
while (!p.empty()) p.pop();
while (!s.empty()) s.pop();
while (!q.empty()) q.pop();
if ((stack_out)&&(!queue_out)&&(!priority_out)) printf("stack\n");
else if ((!stack_out)&&(priority_out)&&(!queue_out)) printf("priority queue\n");
else if ((!stack_out)&&(!priority_out)&&(queue_out)) printf("queue\n");
else if ((!stack_out)&&(!priority_out)&&(!queue_out)) printf("impossible\n");
else printf("not sure\n");
}
return 0;
}
|
c39bf7b744d1dc4235f5d84e81204dd1f4dab30a | 9264ad419b73883a69fb02688ddc3ee40c53edbd | /CF/208D.cpp | 82ff77679dea4f6f4261c6f42f0b5826abe39e44 | [] | no_license | manish1997/Competitive-Programming | 6d5e7fb6081d1a09f8658638bddcd1c72495c396 | b7048f770f7db8ac0bc871d59f1973482f79668f | refs/heads/master | 2021-01-13T04:31:13.082435 | 2020-03-22T20:32:04 | 2020-03-22T20:32:04 | 79,900,759 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,339 | cpp | 208D.cpp | //https://codeforces.com/blog/entry/15296?#comment-203606
//offiline conncetivity of a graph
#include <bits/stdc++.h>
using namespace std;
#define pi 3.1415926535897
#define ll long long
#define tr1(n) cout << n << endl
#define tr2(n1,n2) cout << n1 << " " << n2 << endl
#define mem(A,i) memset(A, i, sizeof(A))
#define rep(i, start, end) for(int i=start; i<end; i++)
#define repDown(i, start, end) for(int i=start; i>=end; i--)
#define mod 1000000007
#define MAX 55
#define INF 1+1e18
#define s second
#define f first
#define pb push_back
#define fast_in std::ios::sync_with_stdio(false);
#define fast_cin fast_in; ios_base::sync_with_stdio(false); cin.tie(NULL);
ll n;
vector<ll> V(5);
ll arr[MAX];
vector<ll> ans(5,0);
void solve(){
//solve the problem. You can and you will :) give your best shot..
cin>>n;
rep(i,0,n){
cin>>arr[i];
}
rep(i,0,5){
cin>>V[i];
}
ll curr=0;
rep(i,0,n){
curr+=arr[i];
if(curr>=V[0]){
repDown(j,4,0){
if(curr>=V[j]){
ans[j]+=curr/V[j];
curr%=V[j];
}
}
}
}
rep(i,0,5) cout<<ans[i]<<" ";
cout<<endl;
cout<<curr;
}
int main(){
fast_cin;
int t=1;
// cin >> t;
while(t--){
solve();
}
return 0;
} |
7495c951acc12b16030c39862d4bb6c21b0aed35 | 2def1b3add7510a29939b5af1c41e1e3f11d281d | /include/storm/DistributedRPCInvocations.h | f708847e3d808bb332bdb935b085b99735b6f485 | [] | no_license | ishumei/ccstorm | 594a38cda187075f665debfdeb4cfcd43a4f41d7 | 6a48a74297b85bc7fd94407c52457775660d8805 | refs/heads/master | 2020-12-25T02:50:23.641428 | 2016-03-19T10:47:54 | 2016-03-19T10:47:54 | 51,989,674 | 0 | 1 | null | 2016-02-18T13:51:59 | 2016-02-18T07:45:23 | C++ | UTF-8 | C++ | false | true | 20,789 | h | DistributedRPCInvocations.h | /**
* Autogenerated by Thrift Compiler (0.9.2)
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
#ifndef DistributedRPCInvocations_H
#define DistributedRPCInvocations_H
#include <thrift/TDispatchProcessor.h>
#include "storm_types.h"
class DistributedRPCInvocationsIf {
public:
virtual ~DistributedRPCInvocationsIf() {}
virtual void result(const std::string& id, const std::string& result) = 0;
virtual void fetchRequest(DRPCRequest& _return, const std::string& functionName) = 0;
virtual void failRequest(const std::string& id) = 0;
};
class DistributedRPCInvocationsIfFactory {
public:
typedef DistributedRPCInvocationsIf Handler;
virtual ~DistributedRPCInvocationsIfFactory() {}
virtual DistributedRPCInvocationsIf* getHandler(const ::apache::thrift::TConnectionInfo& connInfo) = 0;
virtual void releaseHandler(DistributedRPCInvocationsIf* /* handler */) = 0;
};
class DistributedRPCInvocationsIfSingletonFactory : virtual public DistributedRPCInvocationsIfFactory {
public:
DistributedRPCInvocationsIfSingletonFactory(const boost::shared_ptr<DistributedRPCInvocationsIf>& iface) : iface_(iface) {}
virtual ~DistributedRPCInvocationsIfSingletonFactory() {}
virtual DistributedRPCInvocationsIf* getHandler(const ::apache::thrift::TConnectionInfo&) {
return iface_.get();
}
virtual void releaseHandler(DistributedRPCInvocationsIf* /* handler */) {}
protected:
boost::shared_ptr<DistributedRPCInvocationsIf> iface_;
};
class DistributedRPCInvocationsNull : virtual public DistributedRPCInvocationsIf {
public:
virtual ~DistributedRPCInvocationsNull() {}
void result(const std::string& /* id */, const std::string& /* result */) {
return;
}
void fetchRequest(DRPCRequest& /* _return */, const std::string& /* functionName */) {
return;
}
void failRequest(const std::string& /* id */) {
return;
}
};
typedef struct _DistributedRPCInvocations_result_args__isset {
_DistributedRPCInvocations_result_args__isset() : id(false), result(false) {}
bool id :1;
bool result :1;
} _DistributedRPCInvocations_result_args__isset;
class DistributedRPCInvocations_result_args {
public:
static const char* ascii_fingerprint; // = "07A9615F837F7D0A952B595DD3020972";
static const uint8_t binary_fingerprint[16]; // = {0x07,0xA9,0x61,0x5F,0x83,0x7F,0x7D,0x0A,0x95,0x2B,0x59,0x5D,0xD3,0x02,0x09,0x72};
DistributedRPCInvocations_result_args(const DistributedRPCInvocations_result_args&);
DistributedRPCInvocations_result_args& operator=(const DistributedRPCInvocations_result_args&);
DistributedRPCInvocations_result_args() : id(), result() {
}
virtual ~DistributedRPCInvocations_result_args() throw();
std::string id;
std::string result;
_DistributedRPCInvocations_result_args__isset __isset;
void __set_id(const std::string& val);
void __set_result(const std::string& val);
bool operator == (const DistributedRPCInvocations_result_args & rhs) const
{
if (!(id == rhs.id))
return false;
if (!(result == rhs.result))
return false;
return true;
}
bool operator != (const DistributedRPCInvocations_result_args &rhs) const {
return !(*this == rhs);
}
bool operator < (const DistributedRPCInvocations_result_args & ) const;
uint32_t read(::apache::thrift::protocol::TProtocol* iprot);
uint32_t write(::apache::thrift::protocol::TProtocol* oprot) const;
friend std::ostream& operator<<(std::ostream& out, const DistributedRPCInvocations_result_args& obj);
};
class DistributedRPCInvocations_result_pargs {
public:
static const char* ascii_fingerprint; // = "07A9615F837F7D0A952B595DD3020972";
static const uint8_t binary_fingerprint[16]; // = {0x07,0xA9,0x61,0x5F,0x83,0x7F,0x7D,0x0A,0x95,0x2B,0x59,0x5D,0xD3,0x02,0x09,0x72};
virtual ~DistributedRPCInvocations_result_pargs() throw();
const std::string* id;
const std::string* result;
uint32_t write(::apache::thrift::protocol::TProtocol* oprot) const;
friend std::ostream& operator<<(std::ostream& out, const DistributedRPCInvocations_result_pargs& obj);
};
typedef struct _DistributedRPCInvocations_result_result__isset {
_DistributedRPCInvocations_result_result__isset() : aze(false) {}
bool aze :1;
} _DistributedRPCInvocations_result_result__isset;
class DistributedRPCInvocations_result_result {
public:
static const char* ascii_fingerprint; // = "771E7EF40B572D2BFAB12C49547ADCBF";
static const uint8_t binary_fingerprint[16]; // = {0x77,0x1E,0x7E,0xF4,0x0B,0x57,0x2D,0x2B,0xFA,0xB1,0x2C,0x49,0x54,0x7A,0xDC,0xBF};
DistributedRPCInvocations_result_result(const DistributedRPCInvocations_result_result&);
DistributedRPCInvocations_result_result& operator=(const DistributedRPCInvocations_result_result&);
DistributedRPCInvocations_result_result() {
}
virtual ~DistributedRPCInvocations_result_result() throw();
AuthorizationException aze;
_DistributedRPCInvocations_result_result__isset __isset;
void __set_aze(const AuthorizationException& val);
bool operator == (const DistributedRPCInvocations_result_result & rhs) const
{
if (!(aze == rhs.aze))
return false;
return true;
}
bool operator != (const DistributedRPCInvocations_result_result &rhs) const {
return !(*this == rhs);
}
bool operator < (const DistributedRPCInvocations_result_result & ) const;
uint32_t read(::apache::thrift::protocol::TProtocol* iprot);
uint32_t write(::apache::thrift::protocol::TProtocol* oprot) const;
friend std::ostream& operator<<(std::ostream& out, const DistributedRPCInvocations_result_result& obj);
};
typedef struct _DistributedRPCInvocations_result_presult__isset {
_DistributedRPCInvocations_result_presult__isset() : aze(false) {}
bool aze :1;
} _DistributedRPCInvocations_result_presult__isset;
class DistributedRPCInvocations_result_presult {
public:
static const char* ascii_fingerprint; // = "771E7EF40B572D2BFAB12C49547ADCBF";
static const uint8_t binary_fingerprint[16]; // = {0x77,0x1E,0x7E,0xF4,0x0B,0x57,0x2D,0x2B,0xFA,0xB1,0x2C,0x49,0x54,0x7A,0xDC,0xBF};
virtual ~DistributedRPCInvocations_result_presult() throw();
AuthorizationException aze;
_DistributedRPCInvocations_result_presult__isset __isset;
uint32_t read(::apache::thrift::protocol::TProtocol* iprot);
friend std::ostream& operator<<(std::ostream& out, const DistributedRPCInvocations_result_presult& obj);
};
typedef struct _DistributedRPCInvocations_fetchRequest_args__isset {
_DistributedRPCInvocations_fetchRequest_args__isset() : functionName(false) {}
bool functionName :1;
} _DistributedRPCInvocations_fetchRequest_args__isset;
class DistributedRPCInvocations_fetchRequest_args {
public:
static const char* ascii_fingerprint; // = "EFB929595D312AC8F305D5A794CFEDA1";
static const uint8_t binary_fingerprint[16]; // = {0xEF,0xB9,0x29,0x59,0x5D,0x31,0x2A,0xC8,0xF3,0x05,0xD5,0xA7,0x94,0xCF,0xED,0xA1};
DistributedRPCInvocations_fetchRequest_args(const DistributedRPCInvocations_fetchRequest_args&);
DistributedRPCInvocations_fetchRequest_args& operator=(const DistributedRPCInvocations_fetchRequest_args&);
DistributedRPCInvocations_fetchRequest_args() : functionName() {
}
virtual ~DistributedRPCInvocations_fetchRequest_args() throw();
std::string functionName;
_DistributedRPCInvocations_fetchRequest_args__isset __isset;
void __set_functionName(const std::string& val);
bool operator == (const DistributedRPCInvocations_fetchRequest_args & rhs) const
{
if (!(functionName == rhs.functionName))
return false;
return true;
}
bool operator != (const DistributedRPCInvocations_fetchRequest_args &rhs) const {
return !(*this == rhs);
}
bool operator < (const DistributedRPCInvocations_fetchRequest_args & ) const;
uint32_t read(::apache::thrift::protocol::TProtocol* iprot);
uint32_t write(::apache::thrift::protocol::TProtocol* oprot) const;
friend std::ostream& operator<<(std::ostream& out, const DistributedRPCInvocations_fetchRequest_args& obj);
};
class DistributedRPCInvocations_fetchRequest_pargs {
public:
static const char* ascii_fingerprint; // = "EFB929595D312AC8F305D5A794CFEDA1";
static const uint8_t binary_fingerprint[16]; // = {0xEF,0xB9,0x29,0x59,0x5D,0x31,0x2A,0xC8,0xF3,0x05,0xD5,0xA7,0x94,0xCF,0xED,0xA1};
virtual ~DistributedRPCInvocations_fetchRequest_pargs() throw();
const std::string* functionName;
uint32_t write(::apache::thrift::protocol::TProtocol* oprot) const;
friend std::ostream& operator<<(std::ostream& out, const DistributedRPCInvocations_fetchRequest_pargs& obj);
};
typedef struct _DistributedRPCInvocations_fetchRequest_result__isset {
_DistributedRPCInvocations_fetchRequest_result__isset() : success(false), aze(false) {}
bool success :1;
bool aze :1;
} _DistributedRPCInvocations_fetchRequest_result__isset;
class DistributedRPCInvocations_fetchRequest_result {
public:
static const char* ascii_fingerprint; // = "C674841F2185EEC5D93B1AC23E6C600B";
static const uint8_t binary_fingerprint[16]; // = {0xC6,0x74,0x84,0x1F,0x21,0x85,0xEE,0xC5,0xD9,0x3B,0x1A,0xC2,0x3E,0x6C,0x60,0x0B};
DistributedRPCInvocations_fetchRequest_result(const DistributedRPCInvocations_fetchRequest_result&);
DistributedRPCInvocations_fetchRequest_result& operator=(const DistributedRPCInvocations_fetchRequest_result&);
DistributedRPCInvocations_fetchRequest_result() {
}
virtual ~DistributedRPCInvocations_fetchRequest_result() throw();
DRPCRequest success;
AuthorizationException aze;
_DistributedRPCInvocations_fetchRequest_result__isset __isset;
void __set_success(const DRPCRequest& val);
void __set_aze(const AuthorizationException& val);
bool operator == (const DistributedRPCInvocations_fetchRequest_result & rhs) const
{
if (!(success == rhs.success))
return false;
if (!(aze == rhs.aze))
return false;
return true;
}
bool operator != (const DistributedRPCInvocations_fetchRequest_result &rhs) const {
return !(*this == rhs);
}
bool operator < (const DistributedRPCInvocations_fetchRequest_result & ) const;
uint32_t read(::apache::thrift::protocol::TProtocol* iprot);
uint32_t write(::apache::thrift::protocol::TProtocol* oprot) const;
friend std::ostream& operator<<(std::ostream& out, const DistributedRPCInvocations_fetchRequest_result& obj);
};
typedef struct _DistributedRPCInvocations_fetchRequest_presult__isset {
_DistributedRPCInvocations_fetchRequest_presult__isset() : success(false), aze(false) {}
bool success :1;
bool aze :1;
} _DistributedRPCInvocations_fetchRequest_presult__isset;
class DistributedRPCInvocations_fetchRequest_presult {
public:
static const char* ascii_fingerprint; // = "C674841F2185EEC5D93B1AC23E6C600B";
static const uint8_t binary_fingerprint[16]; // = {0xC6,0x74,0x84,0x1F,0x21,0x85,0xEE,0xC5,0xD9,0x3B,0x1A,0xC2,0x3E,0x6C,0x60,0x0B};
virtual ~DistributedRPCInvocations_fetchRequest_presult() throw();
DRPCRequest* success;
AuthorizationException aze;
_DistributedRPCInvocations_fetchRequest_presult__isset __isset;
uint32_t read(::apache::thrift::protocol::TProtocol* iprot);
friend std::ostream& operator<<(std::ostream& out, const DistributedRPCInvocations_fetchRequest_presult& obj);
};
typedef struct _DistributedRPCInvocations_failRequest_args__isset {
_DistributedRPCInvocations_failRequest_args__isset() : id(false) {}
bool id :1;
} _DistributedRPCInvocations_failRequest_args__isset;
class DistributedRPCInvocations_failRequest_args {
public:
static const char* ascii_fingerprint; // = "EFB929595D312AC8F305D5A794CFEDA1";
static const uint8_t binary_fingerprint[16]; // = {0xEF,0xB9,0x29,0x59,0x5D,0x31,0x2A,0xC8,0xF3,0x05,0xD5,0xA7,0x94,0xCF,0xED,0xA1};
DistributedRPCInvocations_failRequest_args(const DistributedRPCInvocations_failRequest_args&);
DistributedRPCInvocations_failRequest_args& operator=(const DistributedRPCInvocations_failRequest_args&);
DistributedRPCInvocations_failRequest_args() : id() {
}
virtual ~DistributedRPCInvocations_failRequest_args() throw();
std::string id;
_DistributedRPCInvocations_failRequest_args__isset __isset;
void __set_id(const std::string& val);
bool operator == (const DistributedRPCInvocations_failRequest_args & rhs) const
{
if (!(id == rhs.id))
return false;
return true;
}
bool operator != (const DistributedRPCInvocations_failRequest_args &rhs) const {
return !(*this == rhs);
}
bool operator < (const DistributedRPCInvocations_failRequest_args & ) const;
uint32_t read(::apache::thrift::protocol::TProtocol* iprot);
uint32_t write(::apache::thrift::protocol::TProtocol* oprot) const;
friend std::ostream& operator<<(std::ostream& out, const DistributedRPCInvocations_failRequest_args& obj);
};
class DistributedRPCInvocations_failRequest_pargs {
public:
static const char* ascii_fingerprint; // = "EFB929595D312AC8F305D5A794CFEDA1";
static const uint8_t binary_fingerprint[16]; // = {0xEF,0xB9,0x29,0x59,0x5D,0x31,0x2A,0xC8,0xF3,0x05,0xD5,0xA7,0x94,0xCF,0xED,0xA1};
virtual ~DistributedRPCInvocations_failRequest_pargs() throw();
const std::string* id;
uint32_t write(::apache::thrift::protocol::TProtocol* oprot) const;
friend std::ostream& operator<<(std::ostream& out, const DistributedRPCInvocations_failRequest_pargs& obj);
};
typedef struct _DistributedRPCInvocations_failRequest_result__isset {
_DistributedRPCInvocations_failRequest_result__isset() : aze(false) {}
bool aze :1;
} _DistributedRPCInvocations_failRequest_result__isset;
class DistributedRPCInvocations_failRequest_result {
public:
static const char* ascii_fingerprint; // = "771E7EF40B572D2BFAB12C49547ADCBF";
static const uint8_t binary_fingerprint[16]; // = {0x77,0x1E,0x7E,0xF4,0x0B,0x57,0x2D,0x2B,0xFA,0xB1,0x2C,0x49,0x54,0x7A,0xDC,0xBF};
DistributedRPCInvocations_failRequest_result(const DistributedRPCInvocations_failRequest_result&);
DistributedRPCInvocations_failRequest_result& operator=(const DistributedRPCInvocations_failRequest_result&);
DistributedRPCInvocations_failRequest_result() {
}
virtual ~DistributedRPCInvocations_failRequest_result() throw();
AuthorizationException aze;
_DistributedRPCInvocations_failRequest_result__isset __isset;
void __set_aze(const AuthorizationException& val);
bool operator == (const DistributedRPCInvocations_failRequest_result & rhs) const
{
if (!(aze == rhs.aze))
return false;
return true;
}
bool operator != (const DistributedRPCInvocations_failRequest_result &rhs) const {
return !(*this == rhs);
}
bool operator < (const DistributedRPCInvocations_failRequest_result & ) const;
uint32_t read(::apache::thrift::protocol::TProtocol* iprot);
uint32_t write(::apache::thrift::protocol::TProtocol* oprot) const;
friend std::ostream& operator<<(std::ostream& out, const DistributedRPCInvocations_failRequest_result& obj);
};
typedef struct _DistributedRPCInvocations_failRequest_presult__isset {
_DistributedRPCInvocations_failRequest_presult__isset() : aze(false) {}
bool aze :1;
} _DistributedRPCInvocations_failRequest_presult__isset;
class DistributedRPCInvocations_failRequest_presult {
public:
static const char* ascii_fingerprint; // = "771E7EF40B572D2BFAB12C49547ADCBF";
static const uint8_t binary_fingerprint[16]; // = {0x77,0x1E,0x7E,0xF4,0x0B,0x57,0x2D,0x2B,0xFA,0xB1,0x2C,0x49,0x54,0x7A,0xDC,0xBF};
virtual ~DistributedRPCInvocations_failRequest_presult() throw();
AuthorizationException aze;
_DistributedRPCInvocations_failRequest_presult__isset __isset;
uint32_t read(::apache::thrift::protocol::TProtocol* iprot);
friend std::ostream& operator<<(std::ostream& out, const DistributedRPCInvocations_failRequest_presult& obj);
};
class DistributedRPCInvocationsClient : virtual public DistributedRPCInvocationsIf {
public:
DistributedRPCInvocationsClient(boost::shared_ptr< ::apache::thrift::protocol::TProtocol> prot) {
setProtocol(prot);
}
DistributedRPCInvocationsClient(boost::shared_ptr< ::apache::thrift::protocol::TProtocol> iprot, boost::shared_ptr< ::apache::thrift::protocol::TProtocol> oprot) {
setProtocol(iprot,oprot);
}
private:
void setProtocol(boost::shared_ptr< ::apache::thrift::protocol::TProtocol> prot) {
setProtocol(prot,prot);
}
void setProtocol(boost::shared_ptr< ::apache::thrift::protocol::TProtocol> iprot, boost::shared_ptr< ::apache::thrift::protocol::TProtocol> oprot) {
piprot_=iprot;
poprot_=oprot;
iprot_ = iprot.get();
oprot_ = oprot.get();
}
public:
boost::shared_ptr< ::apache::thrift::protocol::TProtocol> getInputProtocol() {
return piprot_;
}
boost::shared_ptr< ::apache::thrift::protocol::TProtocol> getOutputProtocol() {
return poprot_;
}
void result(const std::string& id, const std::string& result);
void send_result(const std::string& id, const std::string& result);
void recv_result();
void fetchRequest(DRPCRequest& _return, const std::string& functionName);
void send_fetchRequest(const std::string& functionName);
void recv_fetchRequest(DRPCRequest& _return);
void failRequest(const std::string& id);
void send_failRequest(const std::string& id);
void recv_failRequest();
protected:
boost::shared_ptr< ::apache::thrift::protocol::TProtocol> piprot_;
boost::shared_ptr< ::apache::thrift::protocol::TProtocol> poprot_;
::apache::thrift::protocol::TProtocol* iprot_;
::apache::thrift::protocol::TProtocol* oprot_;
};
class DistributedRPCInvocationsProcessor : public ::apache::thrift::TDispatchProcessor {
protected:
boost::shared_ptr<DistributedRPCInvocationsIf> iface_;
virtual bool dispatchCall(::apache::thrift::protocol::TProtocol* iprot, ::apache::thrift::protocol::TProtocol* oprot, const std::string& fname, int32_t seqid, void* callContext);
private:
typedef void (DistributedRPCInvocationsProcessor::*ProcessFunction)(int32_t, ::apache::thrift::protocol::TProtocol*, ::apache::thrift::protocol::TProtocol*, void*);
typedef std::map<std::string, ProcessFunction> ProcessMap;
ProcessMap processMap_;
void process_result(int32_t seqid, ::apache::thrift::protocol::TProtocol* iprot, ::apache::thrift::protocol::TProtocol* oprot, void* callContext);
void process_fetchRequest(int32_t seqid, ::apache::thrift::protocol::TProtocol* iprot, ::apache::thrift::protocol::TProtocol* oprot, void* callContext);
void process_failRequest(int32_t seqid, ::apache::thrift::protocol::TProtocol* iprot, ::apache::thrift::protocol::TProtocol* oprot, void* callContext);
public:
DistributedRPCInvocationsProcessor(boost::shared_ptr<DistributedRPCInvocationsIf> iface) :
iface_(iface) {
processMap_["result"] = &DistributedRPCInvocationsProcessor::process_result;
processMap_["fetchRequest"] = &DistributedRPCInvocationsProcessor::process_fetchRequest;
processMap_["failRequest"] = &DistributedRPCInvocationsProcessor::process_failRequest;
}
virtual ~DistributedRPCInvocationsProcessor() {}
};
class DistributedRPCInvocationsProcessorFactory : public ::apache::thrift::TProcessorFactory {
public:
DistributedRPCInvocationsProcessorFactory(const ::boost::shared_ptr< DistributedRPCInvocationsIfFactory >& handlerFactory) :
handlerFactory_(handlerFactory) {}
::boost::shared_ptr< ::apache::thrift::TProcessor > getProcessor(const ::apache::thrift::TConnectionInfo& connInfo);
protected:
::boost::shared_ptr< DistributedRPCInvocationsIfFactory > handlerFactory_;
};
class DistributedRPCInvocationsMultiface : virtual public DistributedRPCInvocationsIf {
public:
DistributedRPCInvocationsMultiface(std::vector<boost::shared_ptr<DistributedRPCInvocationsIf> >& ifaces) : ifaces_(ifaces) {
}
virtual ~DistributedRPCInvocationsMultiface() {}
protected:
std::vector<boost::shared_ptr<DistributedRPCInvocationsIf> > ifaces_;
DistributedRPCInvocationsMultiface() {}
void add(boost::shared_ptr<DistributedRPCInvocationsIf> iface) {
ifaces_.push_back(iface);
}
public:
void result(const std::string& id, const std::string& result) {
size_t sz = ifaces_.size();
size_t i = 0;
for (; i < (sz - 1); ++i) {
ifaces_[i]->result(id, result);
}
ifaces_[i]->result(id, result);
}
void fetchRequest(DRPCRequest& _return, const std::string& functionName) {
size_t sz = ifaces_.size();
size_t i = 0;
for (; i < (sz - 1); ++i) {
ifaces_[i]->fetchRequest(_return, functionName);
}
ifaces_[i]->fetchRequest(_return, functionName);
return;
}
void failRequest(const std::string& id) {
size_t sz = ifaces_.size();
size_t i = 0;
for (; i < (sz - 1); ++i) {
ifaces_[i]->failRequest(id);
}
ifaces_[i]->failRequest(id);
}
};
#endif
|
a233b0c0612ed647920f84cd29382f7e01442896 | e20a146de4e61a4a062b443f22e1a5d2ec0e8fe8 | /src/GameStatePause.cpp | f81f3875188f5b79ecb3c1c1e7c868513e410c13 | [] | no_license | ferdinandjason/city-building-game | d78953dea4000b35bd4c5ff1842ba08dfdfd475e | a28b0d75b90593dbedef7a0df2ba4fbf2bb6bae5 | refs/heads/master | 2021-08-30T13:01:08.080612 | 2017-12-18T03:12:47 | 2017-12-18T03:12:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,292 | cpp | GameStatePause.cpp | #include "GameStatePause.hpp"
GameStatePause::GameStatePause(Game *game,GameStateEditor *games)
{
//ctor
this->games=games;
this->game = game;
sf::Vector2f pos = sf::Vector2f(this->game->window.getSize());
this->view.setSize(pos);
pos*=0.5f;
this->view.setCenter(pos);
this->gameStates=State::PAUSE;
pos*=2.0f;
this->guiSystem.emplace("layer",Gui(pos,0,false,this->game->styleSheets.at("layer"),
{std::make_pair("","")}));
pos*=0.5f;
this->guiSystem.at("layer").setOrigin(pos);
this->guiSystem.at("layer").setPosition(pos);
this->guiSystem.at("layer").show();
this->guiSystem.emplace("pausedState",Gui(sf::Vector2f(410,76),0,false,this->game->styleSheets.at("text2"),
{std::make_pair("PAUSED","PAUSED")}));
pos.y-=50;
this->guiSystem.at("pausedState").setOrigin(sf::Vector2f(205,38));
this->guiSystem.at("pausedState").setPosition(pos);
this->guiSystem.at("pausedState").show();
pos.y+=90;
this->guiSystem.emplace("pausedMsg",Gui(sf::Vector2f(556,30),0,false,this->game->styleSheets.at("text2"),
{std::make_pair("PRESS SPACE TO CONTINUE","pause_msg")}));
this->guiSystem.at("pausedMsg").setOrigin(sf::Vector2f(278,15));
this->guiSystem.at("pausedMsg").setPosition(pos);
this->guiSystem.at("pausedMsg").show();
}
GameStatePause::~GameStatePause()
{
//dtor
}
void GameStatePause::draw(const float dt)
{
games->draw(dt);
for(auto gui:this->guiSystem) this->game->window.draw(gui.second);
return;
}
void GameStatePause::update(const float dt)
{
}
void GameStatePause::handleinput()
{
sf::Event event;
while(this->game->window.pollEvent(event))
{
switch(event.type)
{
/* Close the window */
case sf::Event::Closed:
{
game->window.close();
break;
}
/* Resize the window */
case sf::Event::Resized:
{
this->view.setSize(event.size.width,event.size.height);
/* Setiing mouse input for guiStart */
this->game->background.setPosition(this->game->window.mapPixelToCoords(sf::Vector2i(0,0)));
sf::Vector2f pos = sf::Vector2f(event.size.width,event.size.height);
pos*=0.5f;
pos=this->game->window.mapPixelToCoords(sf::Vector2i(pos),this->view);
this->guiSystem.at("pausedState").setPosition(pos);
//this->guiSystem.at("menu").setPosition(pos);
this->game->background.setScale(
float(event.size.width)/float(this->game->background.getTexture()->getSize().x),
float(event.size.height)/float(this->game->background.getTexture()->getSize().y));
break;
}
/* Key Activate */
case sf::Event::KeyPressed:
{
if(event.key.code == sf::Keyboard::Escape) this->game->window.close();
else if(event.key.code == sf::Keyboard::Space) this->backToGame();
break;
}
default: break;
}
}
return;
}
void GameStatePause::backToGame()
{
this->games->backsound.play();
this->game->popState();
}
|
0224d0084b24de8856d3d0944358c8ba020fc4e7 | 0a7628b27fc2a2ce0e8c02f8888c63b145eefe09 | /solutions/validate-binary-search-tree.cpp | 1d9869f1488da62b5ed7f6bbfdee58adb4793ec4 | [] | no_license | VidushiGupta80/leetcode | 60c9a46fcb63e8599aafeb5ef11de56e07c86772 | 9beb84d8f8213dde888b54b213c76d395c38dc8c | refs/heads/main | 2023-02-09T09:58:45.579702 | 2021-01-02T10:39:32 | 2021-01-02T10:39:32 | 307,142,492 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,608 | cpp | validate-binary-search-tree.cpp | //Validate Binary Search Tree -> 06/07/2020 12:15
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
private:
bool isLeaf(TreeNode* root)
{
if(root->left == NULL && root->right == NULL)
return true;
return false;
}
bool check(TreeNode* root, long minimum, long maximum)
{
// if(isLeaf(root))
// return true;
bool checkRoot = false;
if(root->val > minimum && root->val < maximum)
checkRoot = true;
bool checkLeft = true;
if(root->left)
checkLeft = check(root->left, minimum, root->val);
bool checkRight = true;
if(root->right)
checkRight = check(root->right, root->val, maximum);
// if(checkLeft && checkRight)
// return true;
// return false;
return checkRoot && checkLeft && checkRight;
}
public:
bool isValidBST(TreeNode* root) {
if(root == NULL)
return true;
bool checkLeft = true;
bool checkRight = true;
if(root->left)
checkLeft = check(root->left, LONG_MIN, root->val);
if(root->right)
checkRight = check(root->right, root->val, LONG_MAX);
return checkLeft && checkRight;
}
};
|
070b05140175e1513c8f44855349bfa64280842b | 778f08e46f73cb6f48c8681b95be74858adcbada | /gis_patrol_client/src/factories/pgui/pTextEdit.cpp | 16d8b4255dcc605c579efc1bb357855398eb8dc1 | [] | no_license | YuriyRusinov/gis_patrol_rubin | 2704e2612431e9197da738ac9a860173a1127256 | 6c1344ac29fdfc28b63e737dab53900f8cab1ab1 | refs/heads/master | 2023-06-15T14:21:12.621001 | 2021-01-21T20:34:22 | 2021-01-21T20:34:22 | 265,806,283 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,394 | cpp | pTextEdit.cpp | /*
* @brief Класс-виджет для текстового поля
* pTextEdit.cpp
*
* (C) НИИ "Рубин"
* @author
* Ю.Л.Русинов
*/
#include <QFont>
#include <QGridLayout>
#include <QLabel>
#include <QTextEdit>
#include <pParamValue.h>
#include <pCatParameter.h>
#include "pTextEdit.h"
pTextEdit::pTextEdit( QSharedPointer< pParamValue > pValue, QWidget* parent, Qt::WindowFlags flags )
: pAbstractParamWidget( pValue, parent, flags ),
_lParam( new QLabel( pValue->getCatParam()->getTitle() ) ),
_pTextE( new QTextEdit( pValue->value().toString() ) ) {
setup( );
}
pTextEdit::~pTextEdit() {
delete _pTextE;
delete _lParam;
}
void pTextEdit::setup( ) {
QGridLayout* gLay = new QGridLayout( this );
gLay->addWidget( _lParam, 0, 0, 2, 1, Qt::AlignRight | Qt::AlignTop );
gLay->addWidget( _pTextE, 0, 1, 2, 1, Qt::AlignLeft | Qt::AlignVCenter );
QFont lFont = _lParam->font();
if( this->paramValue()->getCatParam()->isMandatory() ) {
lFont.setBold( true );
_lParam->setFont( lFont );
}
QObject::connect( _pTextE, &QTextEdit::textChanged, this, &pTextEdit::pTextChanged );
}
void pTextEdit::pTextChanged() {
paramValue()->setValue( QVariant( _pTextE->toPlainText() ) );
emit valueChanged( paramValue() );
}
void pTextEdit::setReadOnly( bool value ) {
_pTextE->setReadOnly( value );
}
|
25719d451db90ebab156d979701b0753249858a4 | 54da97058e1319bf0bc1c60198558aeb6b004ecd | /Geometry/Surfaces/SurfaceUtils.hpp | aabe5f6508d7a485c52a90ddc9364b214d94905f | [
"BSD-3-Clause"
] | permissive | khurrumsaleem/helios | 202021d96490bd4ad117ccc1196799c019285e7a | fe7a06992abcf495d9b09d2d172b8cc6fdd67b80 | refs/heads/master | 2022-01-24T21:45:51.088917 | 2020-06-27T05:19:10 | 2020-06-27T05:19:10 | 205,647,629 | 0 | 0 | null | 2019-09-01T08:08:19 | 2019-09-01T08:08:19 | null | UTF-8 | C++ | false | false | 3,353 | hpp | SurfaceUtils.hpp | /*
Copyright (c) 2012, Esteban Pellegrino
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the <organization> nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef SURFACEUTILS_HPP_
#define SURFACEUTILS_HPP_
#include <cmath>
#include "../Surface.hpp"
namespace Helios {
/* Calculate the intersection of a surface with calculated quadratic values. */
static inline bool quadraticIntersect(const double& a, const double& k, const double& c, const bool& sense, double& distance) {
/* Discriminant */
double disc = k*k - a*c;
if(disc >= 0.0) {
/* Particle is inside the surface (negative orientation) */
if (not sense) {
/* Headed away from the surface */
if (k <= 0) {
/* Surface is curving upward */
if (a > 0) {
distance = (std::sqrt(disc) - k)/a;
return true;
}
/* Surface curving away and headed in, never hits it */
else {
distance = 0.0;
return false;
}
}
/* Particle is heading toward the surface */
else {
distance = std::max(0.0, -c/(std::sqrt(disc) + k));
return true;
}
}
/* Particle is outside the surface */
else {
/* Headed away from the surface */
if (k >= 0) {
if (a >= 0) {
distance = 0.0;
return false;
}
else {
distance = -(std::sqrt(disc) + k)/a;
return true;
}
}
else {
distance = std::max(0.0, c/(std::sqrt(disc) - k));
return true;
}
}
}
/* No intercept */
distance = 0.0;
return false;
}
/* Dot product, ignoring the cylinder axis component */
template<int cylaxis>
static inline double dotProduct(const Coordinate& x,const Coordinate& y) {
/* Axis */
switch(cylaxis) {
case xaxis :
return (x[yaxis] * y[yaxis] + x[zaxis] * y[zaxis]);
break;
case yaxis :
return (x[xaxis] * y[xaxis] + x[zaxis] * y[zaxis]);
break;
case zaxis :
return (x[xaxis] * y[xaxis] + x[yaxis] * y[yaxis]);
break;
}
return 0;
}
}
#endif /* SURFACEUTILS_HPP_ */
|
995ceeeefb55b4c8d62cdcbd78a5f2eeb860cdc7 | b1e5b734aca8eef98b9061ed52ae5fbf6c66821f | /PB_rtc_LCD_I2C.ino | 25be44de81a87e5544ad283738ddec89402731f8 | [] | no_license | bartleph/Arduino-Stuff | a3283a4bb3ea66ceaade00182efd82824a55662a | 5807e00f056b12be8530010fcb0f00fd3692d544 | refs/heads/master | 2021-05-04T18:12:21.711806 | 2018-03-04T21:08:21 | 2018-03-04T21:08:21 | 120,102,293 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,647 | ino | PB_rtc_LCD_I2C.ino | /*
* A better Clock and LCD Solution.
*LCD Clock using a DS1307 RTC and LCD connected via I2C and Wire lib
Paul Bartlett Feb 2018
*/
#include <Wire.h>
#include "RTClib.h"
#include <LCD.h>
#include <LiquidCrystal_I2C.h>
#define I2C_ADDR 0x3F // Define I2C Address for the LCD//
#define Rs_pin 0
#define Rw_pin 1
#define En_pin 2
#define BL_pin 3
#define D4_pin 4
#define D5_pin 5
#define D6_pin 6
#define D7_pin 7
#define LED_OFF 1
#define LED_ON 0
/* Config LCD */
LiquidCrystal_I2C lcd(I2C_ADDR,En_pin,Rw_pin,Rs_pin,D4_pin,D5_pin,D6_pin,D7_pin);
RTC_DS1307 rtclock;
char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
void setup () {
lcd.begin (16,2); // initialize the lcd
// Switch on the backlight
lcd.setBacklightPin(BL_pin,NEGATIVE);
lcd.setBacklight(LED_ON);
lcd.clear();
Serial.begin(9600);
if (! rtclock.begin()) {
lcd.print("Couldn't find rtclock");
while (1);
}
if (! rtclock.isrunning()) {
lcd.print("rtclock is NOT running!");
// following line sets the RTC to the date & time of this sketch
rtclock.adjust(DateTime(F(__DATE__), F(__TIME__)));
// rtclock.adjust(DateTime(2018, 2, 20, 3, 0, 0));
}
}
void loop () {
DateTime now = rtclock.now();
char dateBuffer[12];
lcd.setCursor(3,0); //Start at character 0 on line 1
sprintf(dateBuffer,"%02u-%02u-%04u ",now.day(),now.month(),now.year());
lcd.print(dateBuffer);
lcd.setCursor(4,1); //Second Line
sprintf(dateBuffer,"%02u:%02u:%02u ",now.hour(),now.minute(),now.second());
lcd.print(dateBuffer);
delay(1000);
}
|
89510225a5e123b3bfc9c6324d18a9ce08fb01bc | 0d74161c499ac2287b1d0ecb444aa92b220cda11 | /httpserver/headerValue.cpp | 772f49446c8403d574af74d06c5cca7946a10666 | [
"MIT"
] | permissive | ondra-novak/jsonrpcserver | 70e19c7d1f269c109412764e7ac18706479f98cb | 878f5f7a981a326dcb39d43d0bb5c4eac213a65c | refs/heads/master | 2020-04-04T07:34:52.097615 | 2019-12-13T08:42:59 | 2019-12-13T08:42:59 | 27,509,171 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,350 | cpp | headerValue.cpp | /*
* headerValue.cpp
*
* Created on: Jan 20, 2016
* Author: ondra
*/
#include <string.h>
#include <ctype.h>
#include "headerValue.h"
#include "lightspeed/base/containers/constStr.h"
#include "lightspeed/base/countof.h"
using LightSpeed::countof;
namespace BredyHttpSrv {
static ConstStrA hdrfields[] = {
/*fldHost ,*/ "Host",
/*fldUserAgent,*/ "User-Agent",
/*fldServer,*/ "Server",
/*fldContentType,*/ "Content-Type",
/*fldContentLength,*/ "Content-Length",
/*fldConnection,*/ "Connection",
/*fldCookie,*/ "Cookie",
/*fldAccept, */"Accept",
/*fldCacheControl,*/"Cache-Control",
/*fldDate,*/ "Date",
/*fldReferer,*/ "Referer",
/*fldAllow,*/ "Allow",
/*fldContentDisposition,*/ "Content-Disposition",
/*fldExpires,*/ "Expires",
/*fldLastModified,*/ "Last-Modified",
/*fldLocation,*/ "Location",
/*fldPragma,*/ "Pragma",
/*fldRefresh,*/ "Referer",
/*fldSetCookie,*/ "Set-Cookie",
/*fldWWWAuthenticate,*/ "WWW-Authenticate",
/*fldAuthorization,*/ "Authorization",
/*fldWarning,*/ "Warning",
/*fldAccessControlAllowOrigin,*/ "Access-Control-Allow-Origin",
/*fldETag,*/ "ETag",
/*fldIfNoneMatch,*/ "If-None-Match",
/*fldIfModifiedSince,*/ "If-Modified-Since",
/*fldTransferEncoding,*/ "Transfer-Encoding",
/*fldExpect,*/ "Expect",
/*fldUnknown,*/ "Undefined",
/*fldUpgrade,*/ "Upgrade",
/*fldAccessControlAllowMethods,*/ "Access-Control-Allow-Methods",
/*fldAccessControlAllowHeaders,*/ "Access-Control-Allow-Headers",
/*fldXForwardedFor*/ "X-Forwarded-For",
/*fldOrigin*/ "Origin",
/*fldProxyAuthorization,*/ "Proxy-Authorization"
};
ConstStrA HeaderFieldDef::getHeaderFieldName(Field fld) {
natural idx = fld;
if (idx >= countof(hdrfields))
return ConstStrA();
return hdrfields[idx];
}
static ConstStrA methods[] = {
/*mOPTIONS,*/ "OPTIONS",
/*mGET,*/ "GET",
/*mHEAD*/ "HEAD",
/*mPOST*/ "POST",
/*mPUT*/ "PUT",
/*mDELETE*/ "DELETE",
/*mTRACE*/ "TRACE",
/*mCONNECT*/ "CONNECT"
};
ConstStrA HeaderFieldDef::getMethodName(Method fld) {
natural idx = fld;
if (idx >= countof(methods))
return ConstStrA();
return methods[idx];
}
void HeaderFieldDef::cropWhite(ConstStrA &k) {
while (!k.empty()) {
if (isspace(k[0])) k = k.crop(1,0);
else if (isspace(k[k.length()-1])) k = k.crop(0,1);
else break;
}
}
}
|
cc91ba817579f787250a0f249ce2c32a343df3b3 | 2f6e766368a6637771e8eab26ba0627c3d2b0f79 | /tests/generator/test_utilities_blaze.hpp | d9ba77e5d6893539434130323583c6623dce35a5 | [] | no_license | HPAC/MatrixGeneratorCpp | 26fcc42ff23d9250fb558b1930b14462f65e8465 | a85baafc25b39842c0a64cff7776aa71971682be | refs/heads/master | 2023-03-17T18:57:00.723993 | 2021-03-08T15:13:35 | 2021-03-08T15:13:35 | 74,408,045 | 1 | 2 | null | 2019-05-15T10:30:08 | 2016-11-21T21:36:02 | C++ | UTF-8 | C++ | false | false | 2,144 | hpp | test_utilities_blaze.hpp | // Copyright (c) 2017 Marcin Copik
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef __LINALG_TESTS_TESTS_GENERATOR_TEST_UTILITIES_BLAZE_HPP__
#define __LINALG_TESTS_TESTS_GENERATOR_TEST_UTILITIES_BLAZE_HPP__
#include <blaze/Blaze.h>
#include <blaze/math/DenseMatrix.h>
#include <blaze/math/dense/DynamicMatrix.h>
#include <generator/lapack_wrapper.hpp>
template<typename Mat, bool SO, typename... Properties>
void verify_matrix(const blaze::DenseMatrix<Mat, SO> &, const Properties &...)
{}
// Blaze llh should throw if Cholesky factorization fails on a not positive definite matrix
template<typename Mat, bool SO>
void verify_matrix(const blaze::DenseMatrix<Mat, SO> & mat, const generator::property::spd &)
{
typedef typename traits::matrix_traits<Mat>::value_t value_t;
blaze::DynamicMatrix<value_t, blaze::rowMajor> result;
ASSERT_NO_THROW( blaze::llh(mat, result); );
}
template<typename Mat, bool SO>
void verify_matrix(const blaze::DenseMatrix<Mat, SO> & mat, const generator::property::spd & spd_prop, const generator::property::positive &)
{
verify_matrix(mat, spd_prop);
}
// Blaze llh should throw if Cholesky factorization fails on a not positive definite matrix
template<typename Mat, bool SO>
void verify_matrix(const blaze::DenseMatrix<Mat, SO> & mat_, const generator::property::orthogonal &)
{
typedef typename traits::matrix_traits<Mat>::value_t value_t;
auto mat = ~mat_;
uint64_t rows = mat.rows(), cols = mat.columns();
// multiply matrix * matrix'
auto multiplication = blaze::eval(mat * blaze::trans(mat) - blaze::IdentityMatrix<double, blaze::rowMajor>(rows));
// now all elements should be quite close to zero
//auto matrix_norm = blaze::length(multiplication);
value_t sum = 0.0;
for(uint64_t i = 0; i < rows; ++i) {
for(uint64_t j = 0; j < cols; ++j) {
sum += std::pow(multiplication(i, j), 2);
}
}
EXPECT_NEAR(std::sqrt(sum), static_cast<value_t>(0.0), generator::lapack::QR<value_t>::epsilon());
}
#endif
|
14a84f6a19a34ae46359afc6a507e6d48bae8f7b | 05fe9b0653456b0b16c62fb3578edd9061029946 | /book/真相強化学習入門/program_978-4-274-22253-5/program/ch5/sec5.4/Servo_Test_Ar/Servo_Test_Ar.ino | b7478a1e0714adf7839dd124984f68276898e9c2 | [] | no_license | N-Eiki/sandbox | 3215df5b3c14fb30be82d678992bda843644bede | 13c175a78381aa71127ff964a3b3bfe0948517a9 | refs/heads/master | 2022-12-30T01:56:49.602548 | 2020-10-12T12:40:22 | 2020-10-12T12:40:22 | 286,705,291 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 270 | ino | Servo_Test_Ar.ino | #include <Servo.h>
Servo myservo;
void setup() {
Serial.begin(9600);
while (!Serial) {
;
}
myservo.attach(9);
myservo.write(60);
}
void loop() {
myservo.write(60);
delay(500);
myservo.write(30);
delay(500);
myservo.write(90);
delay(500);
}
|
4310d23534d89a612798782ce6a02d3d2cafacc1 | aa5c1a530f95d629e686ac9124caf1a49a9f23e9 | /compiler/src/iree/compiler/Modules/HAL/Loader/IR/HALLoaderDialect.cpp | 419d0cfe84897596e9297635788a9f695a0995fa | [
"Apache-2.0",
"LLVM-exception",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | openxla/iree | eacf5b239559e1d3b40c38039ac4c26315b523f7 | 13ef677e556d0a1d154e45b052fe016256057f65 | refs/heads/main | 2023-09-06T01:19:49.598662 | 2023-09-04T07:01:30 | 2023-09-04T07:01:30 | 208,145,128 | 387 | 110 | Apache-2.0 | 2023-09-14T20:48:00 | 2019-09-12T20:57:39 | C++ | UTF-8 | C++ | false | false | 2,218 | cpp | HALLoaderDialect.cpp | // Copyright 2022 The IREE Authors
//
// Licensed under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#include "iree/compiler/Modules/HAL/Loader/IR/HALLoaderDialect.h"
#include "iree/compiler/Dialect/VM/Conversion/ConversionDialectInterface.h"
#include "iree/compiler/Modules/HAL/Loader/Conversion/HALLoaderToVM/Patterns.h"
#include "iree/compiler/Modules/HAL/Loader/IR/HALLoaderOps.h"
#include "iree/compiler/Modules/HAL/Loader/hal_loader.imports.h"
#include "llvm/Support/SourceMgr.h"
#include "mlir/IR/DialectImplementation.h"
#include "mlir/IR/OpImplementation.h"
#include "mlir/Parser/Parser.h"
namespace mlir {
namespace iree_compiler {
namespace IREE {
namespace HAL {
namespace Loader {
namespace {
class HALLoaderToVMConversionInterface : public VMConversionDialectInterface {
public:
using VMConversionDialectInterface::VMConversionDialectInterface;
OwningOpRef<mlir::ModuleOp> parseVMImportModule() const override {
return mlir::parseSourceString<mlir::ModuleOp>(
StringRef(iree_hal_loader_imports_create()->data,
iree_hal_loader_imports_create()->size),
getDialect()->getContext());
}
void
populateVMConversionPatterns(SymbolTable &importSymbols,
RewritePatternSet &patterns,
ConversionTarget &conversionTarget,
TypeConverter &typeConverter) const override {
conversionTarget.addIllegalDialect<IREE::HAL::Loader::HALLoaderDialect>();
populateHALLoaderToVMPatterns(getDialect()->getContext(), conversionTarget,
typeConverter, importSymbols, patterns);
}
};
} // namespace
HALLoaderDialect::HALLoaderDialect(MLIRContext *context)
: Dialect(getDialectNamespace(), context, TypeID::get<HALLoaderDialect>()) {
addInterfaces<HALLoaderToVMConversionInterface>();
#define GET_OP_LIST
addOperations<
#include "iree/compiler/Modules/HAL/Loader/IR/HALLoaderOps.cpp.inc"
>();
}
} // namespace Loader
} // namespace HAL
} // namespace IREE
} // namespace iree_compiler
} // namespace mlir
|
113358d8c4ae7ea814ed4e006c05d0e9c4f4a13a | fc2c125ee70382499bde7f86bb0f80599e51cec2 | /http/htparse.h | 1f0c63423867c8e9ff88c971c73b7f68da8fa10b | [] | no_license | austgl/libhttp | 19219b581eebfb917ba000e4b03a4b495be565dc | 253878e650066bcd7de8192324f231a24b96d01d | refs/heads/master | 2020-05-09T14:39:50.845342 | 2012-01-30T16:12:43 | 2012-01-30T16:12:43 | 34,853,777 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 997 | h | htparse.h | #pragma once
#include <stdint.h>
#include "htp_type.h"
#include "htp_scheme.h"
#include "htp_method.h"
#include "htpparse_error.h"
#include "htparse_hooks.h"
class IHTParser{
public:
virtual size_t run( htparse_hooks *, const char *, size_t)=0;
virtual int should_keep_alive()=0;
virtual htp_scheme get_scheme()=0;
virtual HttpMethod get_method()=0;
virtual const char * get_methodstr()=0;
virtual void set_major( unsigned char)=0;
virtual void set_minor( unsigned char)=0;
virtual unsigned char get_major()=0;
virtual unsigned char get_minor()=0;
virtual unsigned int get_status()=0;
virtual uint64_t get_content_length()=0;
virtual htpparse_error get_error()=0;
virtual const char * get_strerror()=0;
virtual void * get_userdata()=0;
virtual void set_userdata( void *)=0;
virtual void init( HttpMessageType)=0;
};
IHTParser * htparser_new(void);
|
da9ebaa0b77ed69f373142a306a48e33506b4596 | d5d67dd5000a4c03c164cf27a68dc5d6ea47500e | /lab02/observer/WeatherStationDuo/CDisplay.cpp | df610db507de152447a1b6a7d63d41dff457d65f | [] | no_license | ImbaCow/OOD | db127161159eab83f440b1e9de41a0e7ff373f57 | 725a37b383265b14fe349da2efdfd1e71f2675af | refs/heads/master | 2020-07-16T14:30:34.544134 | 2019-12-30T15:59:21 | 2019-12-30T15:59:21 | 205,805,646 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 815 | cpp | CDisplay.cpp | #pragma once
#include "pch.h"
#include "CDisplay.h"
CDisplay::CDisplay(const CWeatherData& inData, const CWeatherData& outData)
: inData(inData)
, outData(outData)
{
}
void CDisplay::Update(const CWeatherData& data)
{
std::cout << "---Current Info---" << std::endl;
std::cout << "Source type " << DataTypeToStr(data) << std::endl;
std::cout << "Current Temp " << data.GetTemperature() << std::endl;
std::cout << "Current Hum " << data.GetHumidity() << std::endl;
std::cout << "Current Pressure " << data.GetPressure() << std::endl;
std::cout << "------------------" << std::endl;
}
std::string CDisplay::DataTypeToStr(const CWeatherData& data)
{
if (&data == &inData)
{
return "in";
}
else if (&data == &outData)
{
return "out";
}
throw std::invalid_argument("Unhandled wather data type");
}
|
147949742232c4a9be3c84e29f514cc7cf7a1134 | e5dc9d8142d807b87e6a7980670ecba28e4a9523 | /KsEngine/img/lib/flash/KsFlashBase.cpp | 5f6016b3d64784075b7821e55b5ecee67e919dbf | [
"MIT"
] | permissive | a567w/AriaGame | e2c692e32d0afcf3e7ec7a676456e4d4a35c19d7 | bf90f79cecd5e27e221fa0e791a784d9be5ef06f | refs/heads/master | 2020-07-01T05:03:26.856425 | 2019-11-05T13:45:56 | 2019-11-05T13:45:56 | 201,052,112 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 903 | cpp | KsFlashBase.cpp |
KsUInt32 KsFlashFixed::convertToRaw() const
{
KsUInt32 r = ((KsInt32)upperval)<<16;
r |= lowerval;
return r;
}
void KsFlashFixed::getFromRaw(KsInt32 raw)
{
upperval = raw >> 16;
lowerval = (raw & 0xffff);
}
KsReal64 KsFlashFixed::convertToDouble() const
{
return upperval + KsReal64(lowerval) / 0x10000;
}
void KsFlashFixed::getFromDouble(KsReal64 x)
{
upperval = (KsUInt16)floor(x);
lowerval = (KsUInt16)((x-floor(x))*0x10000);
}
KsUInt16 KsFlashFixed16::ConvertToRaw() const
{
KsUInt16 r = ((KsInt16)upperval)<<8;
r |= lowerval;
return r;
}
void KsFlashFixed16::GetFromRaw(KsInt16 raw)
{
upperval = raw >> 8;
lowerval = (raw & 0xff);
}
KsReal64 KsFlashFixed16::ConvertToDouble()
{
return upperval + KsReal64(lowerval) / 0x100;
}
void KsFlashFixed16::GetFromDouble(KsReal64 x)
{
upperval = (KsUInt8)floor(x);
lowerval = (KsUInt8)((x-floor(x))*0x100);
}
|
9f3b86b8a51b65c573ca709fe9ce9959a4cd51b6 | 6d292a0a7e05146454fb326dab4897ef9a977834 | /3d Sem/2. 17.09.2012/Task1/Task1/Net.cpp | 4bbc3ef1c8e60720e7e51b4d0c396c26ad34ec11 | [] | no_license | MrKuznetsov/hw-cpp | 0e52187f4195499877662fc3956edb53c59e6ac3 | 63ad463509c363bd626994ec3d90e42f8c78daf1 | refs/heads/master | 2021-03-13T00:00:23.719466 | 2013-12-10T18:42:02 | 2013-12-10T18:42:02 | 3,544,642 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,827 | cpp | Net.cpp | #include "Net.h"
Net::~Net()
{
for (int i = 0; i < comps.size(); i++)
delete comps[i];
}
void Net::init()
{
srand(time(0));
cout << "Matrix that shows connection of computers\n";
for (int i = 0; i < NUM_COMPS; i++)
{
for (int j = 0; j < NUM_COMPS; j++)
{
matrix[i][j] = rand() % 2;
if (i == j)
matrix[i][j] = 0;
cout << int(matrix[i][j]) << " ";
}
cout << endl;
}
vector<OperatingSystem *> oss;
oss.push_back((OperatingSystem *)WindowsXP::Instance());
oss.push_back((OperatingSystem *)Windows7::Instance());
oss.push_back((OperatingSystem *)Linux::Instance());
oss.push_back((OperatingSystem *)Mac::Instance());
vector<AntiVirus *> avs;
avs.push_back(NULL);
avs.push_back((AntiVirus *)Kaspersky::Instance());
avs.push_back((AntiVirus *)Nod32::Instance());
for (int i = 0; i < NUM_COMPS; i++)
{
int r = rand() % oss.size();
OperatingSystem *os = oss[r];
r = rand() % avs.size();
AntiVirus *av = avs[r];
Computer *comp = new Computer(os, av);
comp->setInfected(rand() % 2 * rand() % 2);
comps.push_back(comp);
}
}
void Net::setMatrix(char val, int x, int y)
{
matrix[x][y] = val;
}
Computer *Net::addComp(bool isInfected, OperatingSystem *pOs, AntiVirus *pAv)
{
Computer *comp = new Computer(pOs, pAv);
comp->setInfected(isInfected);
comps.push_back(comp);
return comp;
}
void Net::doStep()
{
for (int i = 0; i < comps.size(); i++)
{
Computer *comp = comps[i];
if (comp->isInfected())
comp->tryToHeal();
}
for (int i = 0; i < comps.size(); i++)
{
Computer *comp = comps[i];
if (comp->isInfected())
for (int j = 0; j < comps.size(); j++)
if (matrix[i][j] && !comps[j]->isInfected())
{
comps[j]->tryToInfect();
break;
}
}
}
void Net::showInf()
{
for (int i = 0; i < comps.size(); i++)
{
comps[i]->print();
}
} |
8c7391cab8886f0235eb17957aeb9e00a0471b72 | fa874e76fe912eabfcb6a9516d6c4141c29fdd34 | /word_pattern.cpp | df3093be872869eb337082e8fef735d88879ef54 | [] | no_license | pukumar2/ds_interview_prep | 940a4cd735083d9bae24bdcfd175d6ac12bb5909 | 09b7623dab08226625fa98e54c3bb21b05574342 | refs/heads/master | 2020-04-11T07:33:04.180969 | 2019-01-12T21:42:01 | 2019-01-12T21:42:01 | 161,614,296 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 917 | cpp | word_pattern.cpp | /* Run time 0ms, beats 100% CPP Submission
*/
class Solution {
public:
bool wordPattern(string pattern, string str) {
unordered_map<char, string> m;
unordered_set<string> wordset;
vector<string> s;
int i=0;
string temp = "";
while(i < str.size()){
if(str[i] == ' '){
s.push_back(temp);
temp = "";
}else temp += str[i];
i++;
}
if(temp.size() > 0) s.push_back(temp);
if(s.size() != pattern.size())
return false;
for(int i=0; i<pattern.size(); ++i){
if(m.find(pattern[i]) != m.end()){
if(m[pattern[i]] != s[i])
return false;
}
m[pattern[i]] = s[i];
wordset.insert(s[i]);
if(wordset.size() != m.size()) return false;
}
return true;
}
};
|
611507b3b5f81eff6b5d9bd60d5af8940124b40e | d822ffd937fae821fdc1f96369c26b8b31c0cda6 | /luogu/p1111.cpp | 584c1e92d4eb563411abac953c56e6f53a7c6299 | [
"MIT"
] | permissive | freedomDR/coding | f8bb5b43951f49cc1018132cc5c53e756a782740 | 408f0fd8d7e5dd986842746d27d4d26a8dc9896c | refs/heads/master | 2023-03-30T03:01:01.837043 | 2023-03-28T12:36:53 | 2023-03-28T12:36:53 | 183,414,292 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 905 | cpp | p1111.cpp | #include<bits/stdc++.h>
using namespace std;
int fa[100005], n, m;
int findf(int f)
{
if(f != fa[f])
fa[f] = findf(fa[f]);
return fa[f];
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cin >> n >> m;
vector<tuple<int, int, int>> a;
for(int i = 0; i < n; i++) fa[i] = i;
for(int i = 0; i < m; i++)
{
int x, y, z;
cin >> x >> y >> z;
a.push_back(make_tuple(x, y, z));
}
auto cmp = [](auto t1, auto t2)
{
return get<2>(t1) < get<2>(t2);
};
sort(a.begin(), a.end(), cmp);
int cnt = 1, t = 0;
for(auto &it:a)
{
int x = get<0>(it), y = get<1>(it);
t = get<2>(it);
if(findf(x)==findf(y)) continue;
else fa[findf(x)] = fa[findf(y)];
cnt++;
if(cnt==n) break;
}
if(cnt == n) cout << t << endl;
else cout << "-1" << endl;
return 0;
} |
d3f2acc1326b5bf1f5e96dc1d801d6960c48767a | 65476582617c63bef0d292b2e99bc7fbd137f656 | /MainServer/Controller.h | 747c4acb11be9283c966495e671f6c9384a91d55 | [] | no_license | VorkovN/Trains-DB-UDP-Linux | 756cbc73e2b82a4f419c5ac8bf59ec71f7135629 | 6ed40563e4ab693e9b90a21a0c4418d3631205d9 | refs/heads/master | 2022-12-11T13:27:33.805326 | 2020-08-23T00:22:14 | 2020-08-23T00:22:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 450 | h | Controller.h | #pragma once
#include <set>
#include <string>
#include "DB_Connector.h"
using namespace std;
class Controller {
public:
string order(string from, string to, string freight_type, int cars_count);
bool checkStations(string name);
bool checkFreight(string freight);
private:
DB_Connector db_connector;
set<string> allowed_stations = {"SPB", "MSK", "EKB"};
set<string> allowed_freight = {"liquid", "wood", "ore"};
};
|
30747c86b13be90f944068008313067fa9ed37fb | e7e497b20442a4220296dea1550091a457df5a38 | /main_project/DataSync/sync/LocalConsumer.cpp | 689a081c58923035d113f3603087d526f3171654 | [] | no_license | gunner14/old_rr_code | cf17a2dedf8dfcdcf441d49139adaadc770c0eea | bb047dc88fa7243ded61d840af0f8bad22d68dee | refs/heads/master | 2021-01-17T18:23:28.154228 | 2013-12-02T23:45:33 | 2013-12-02T23:45:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 692 | cpp | LocalConsumer.cpp | #include "LocalConsumer.h"
#include <Producer.h>
namespace com {
namespace renren {
namespace datasync {
LocalConsumer::LocalConsumer(const std::string& zkAddress, const std::string cluster,
const std::string& subject) :
xce::messagepipe::Consumer(zkAddress, cluster, subject) {
}
void LocalConsumer::onMessage(const std::vector<xce::messagepipe::MessageDataPtr>& receiveMessages) {
std::vector<xce::messagepipe::MessageDataPtr> failMessages = SyncWorker::instance().sync(receiveMessages);
if(!failMessages.empty()) {
xce::messagepipe::Producer::getInstance()->sendBatch(zk_address_, failMessages);
}
}
}
}
}
|
266b209cea7fbcbc2d0ea3fee5c9d9e9a0772b20 | 1643984fbebbf588b73d0d2d94dfc90726861c2a | /dataStructure/LinkedList.cpp | 9635ed4079a285785b436fcb0e70e441169a2156 | [] | no_license | thuynt0803/data-structures-and-object-oriented | 332aaa78bbe507be4569cca07af08396ad8f8baf | 2270baa0162277436f90297ff640611ed364d488 | refs/heads/main | 2023-04-11T08:58:09.112552 | 2021-04-19T02:50:57 | 2021-04-19T02:50:57 | 345,275,786 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,767 | cpp | LinkedList.cpp | /* Bài toán: Nhập danh sách liên kết đơn các số nguyên. Tìm giá trị lớn nhất trong danh sách */
#include <iostream>
using namespace std;
/* ======================== KHAI BÁO CẤU TRÚC DANH SÁCH LIÊN KẾT ĐƠN CÁC SỐ NGUYÊN ============================== */
// 1. Khai báo cấu trúc của 1 node
struct node
{
int data; // data chứa trong 1 cái node
struct node *pNext; // con trỏ dùng để liên kết giữa các node với nhau
};
typedef struct node NODE; // thay thế struct node thành NODE
// 2. Khai báo cấu trúc của linked list
struct list
{
NODE *pHead; // node quản lý đầu danh sách
NODE *pTail; // node quản lý cuối danh sách
};
typedef struct list LIST; // thay thế struct list thành LIST
/* ======================== KHỞI TẠO CẤU TRÚC DANH SÁCH LIÊN KẾT ĐƠN CÁC SỐ NGUYÊN ============================== */
void initList(LIST &l)
{
// cho hai node trỏ đến NULL vì dslk đơn chưa có phần tử
l.pHead = NULL;
l.pTail = NULL;
}
// Hàm khởi tạo 1 cái node
NODE *initNODE(int x)
{
NODE *p = new NODE; // Cấp phát vùng nhớ cho NODE p
if (p == NULL)
{
cout << "\nKhong du bo nho de cap phat!" << endl;
return NULL;
}
p->data = x; // truyền giá trị x vào cho data
p->pNext = NULL; // đầu tiên khai báo node thì node đó chưa có liên kết đến node nào hết ==> con trỏ của nó sẽ trỏ đến NULL
return p; // trả về NODE p vừa khởi tạo
}
// Hàm thêm node p vào đầu danh sách liên kết
void inputFirst(LIST &l, NODE *p)
{
if (l.pHead == NULL) // Danh sách đang rỗng
{
l.pHead = l.pTail = p; // node đầu là node cuối và là p
}
else // Danh sách không rỗng
{
p->pNext = l.pHead; // cho con trỏ của node cần thêm là node p liên kết đến node đầu - pHead
l.pHead = p; // cập nhật lại pHead chính là node p
}
}
// Hàm thêm node p vào cuối danh sách liên kết đơn
void inputLast(LIST &l, NODE *p)
{
if (l.pHead == NULL) // Danh sách đang rỗng
{
l.pHead = l.pTail = p; // node đầu là node cuối và là p
}
else // Danh sách không rỗng
{
l.pTail->pNext = p; // cho con trỏ của pTail liên kết với node p
l.pTail = p; // cập nhật lại p là node pTail
}
}
// Hàm thêm node p vào sau node q (node đã tồn tại trong dslk)
void inputAfterAnything(LIST &l, NODE *p)
{
int x;
cout << "\nNhap node q = ";
cin >> x;
NODE *q = initNODE(x);
// Nếu danh sách chỉ có 1 phần tử và phần tử đó cũng chính là node q ==> bài toán trở thành kỹ thuật thêm vào cuối danh sách
if (q->data == l.pHead->data && l.pHead->pNext == NULL)
{
inputLast(l, p);
}
else
{
// ================ DANH SÁCH TỒN TẠI 2 NODE Q TRỞ LÊN ===================
// Duyệt từ đầu danh sách đến cuối danh sách để tìm node q
for (NODE *k = l.pHead; k != NULL; k = k->pNext)
{
// nếu node q có tồn tại thì
if (q->data == k->data)
{
NODE *h = initNODE(p->data); // khởi tạo một node h mới để thêm vào sau node q
NODE *g = k->pNext; // cho node g trỏ đến node nằm sau node q
h->pNext = g; // Bước 1: Tạo mối liên kết từ node h đến node g <=> cũng chính là tạo mối liên kết từ node h đến node nằm sau node q
k->pNext = h; // Tạo mối liên kết từ node q đến node h <=> chính là node k đến node h
}
}
}
}
// Hàm thêm node p vào trước node q (node đã tồn tại trong dslk)
void inputFirstAnything(LIST &l, NODE *p)
{
int x;
cout << "\nNhap node q = ";
cin >> x;
NODE *q = initNODE(x);
// Nếu danh sách chỉ tồn tại duy nhất 1 phần tử và phần tử đó cũng chính là node q ==> bài toán trở thành kỹ thuật thêm vào đầu danh sách
if (q->data == l.pHead->data && l.pHead->pNext == NULL)
{
inputFirst(l, p);
}
else
{
// ================ DANH SÁCH CHỈ TỒN TẠI 1 NODE Q ===================
// NODE *g = new NODE; // node g chính là node giữ liên kết với cái node nằm trước node q trong danh sách
// // Duyệt từ đầu danh sách đến cuối danh sách để tìm node q
// for (NODE *k = l.pHead; k != NULL; k = k->pNext)
// {
// // nếu node q có tồn tại trong danh sách thì bắt đầu thêm node p vào sau node q
// if (q->data == k->data)
// {
// // thực hiện bài toán thêm node p vào sau node g <=> thêm node p vào trước node q
// p->pNext = k; // B1: Cho node p trỏ (liên kết) đến node k <=> cho node p trỏ đến node q
// g->pNext = p; // B2: Cho node g trỏ đến node p
// }
// g = k; // giữ liên kết với node nằm trước node q trong danh sách
// }
// ================ DANH SÁCH TỒN TẠI 2 NODE Q TRỞ LÊN ===================
NODE *g = new NODE; // node g chính là node giữ liên kết với cái node nằm trước node q trong danh sách
// Duyệt từ đầu danh sách đến cuối danh sách để tìm node q
for (NODE *k = l.pHead; k != NULL; k = k->pNext)
{
// nếu node q có tồn tại trong danh sách thì bắt đầu thêm node p vào sau node q
if (q->data == k->data)
{
NODE *h = initNODE(p->data); // mỗi lần phát hiện 1 node q thì ta khởi tạo 1 node p mới <=> khởi tạo node h
// thực hiện bài toán thêm node p vào sau node g <=> thêm node p vào trước node q
h->pNext = k; // B1: Cho node h trỏ (liên kết) đến node k <=> cho node h trỏ đến node q
g->pNext = h; // B2: Cho node g trỏ đến node p
}
g = k; // giữ liên kết với node nằm trước node q trong danh sách
}
}
}
// Hàm xóa node đầu danh sách
void deleteFirst(LIST &l)
{
// Neu danh sach rong
if (l.pHead == NULL)
{
return;
}
NODE *p = l.pHead; // node p la node se duoc xoa
l.pHead = l.pHead->pNext; // cap nhat lai l.pHead la phan tu ke tiep
delete p;
}
// Hàm xóa node cuối danh sách
void deleteLast(LIST &l)
{
// Neu danh sach rong
if (l.pHead == NULL)
{
return;
}
// trường hợp danh sách có 1 phần tử
if (l.pHead->pNext == NULL)
{
deleteFirst(l);
return;
}
// duyệt từ đầu danh sách đến node kế cuối
for (NODE *k = l.pHead; k != NULL; k = k->pNext)
{
// phát hiện thằng kế cuối
if (k->pNext == l.pTail)
{
delete l.pTail; // xo di phan tu cuoi
k->pNext = NULL; // cho con tro cua node ke cuoi tro den vung nho null
l.pTail = k; // Cap nhat lai l.pTail
return;
}
}
}
// Hàm xóa 1 node năm sau node q trong danh sách
void deleteLastAnything(LIST &l, NODE *q)
{
// kiem tra danh sach rong
if (l.pHead == NULL)
{
return;
}
// duyet danh sach tu dau den cuoi de tim node q
for (NODE *k = l.pHead; k != NULL; k = k->pNext)
{
// phat hien node q
if (k->data == q->data)
{
NODE *g = k->pNext; // node g la node nam sau node k <=> node duoc yeu cau xoa
k->pNext = g->pNext; // cap nhat moi lien ket giua node k (node q) voi node sau node g
delete g; // xoa node nam sau node q
}
}
}
// Hàm xóa 1 node có khóa k (so nguyen x) bất kỳ
void deleteAnyX(LIST &l, int x)
{
// kiem tra danh sach rong
if (l.pHead == NULL)
{
return;
}
// neu node can xoa nam dau danh sach
if (l.pHead->data == x)
{
deleteFirst(l);
return;
}
// neu node can xoa nam cuoi danh sach
if (l.pTail->data == x)
{
deleteLast(l);
return;
}
NODE *g = new NODE; // node g la node tro den node nam truoc node can xoa (x)
// duyet danh sach de tim x
for (NODE *k = l.pHead; k != NULL; k = k->pNext)
{
if (k->data == x)
{
g->pNext = k->pNext; // cap nhat moi lien ket giua node k voi node sau node k
delete k; // xoa node nam sau node k
return;
}
g = k; // cho node g tro den node k
}
}
// Hàm tìm giá trị lớn nhất trong danh sách
int searchMax(LIST l)
{
int max = l.pHead->data; // giả sử node đầu là node có giá trị lớn nhất
// bắt đầu duyệt từ node thứ 2 để kiểm tra
for (NODE *k = l.pHead->pNext; k != NULL; k = k->pNext)
{
if (max < k->data)
{
max = k->data; // cập nhật lại giá trị max
}
}
return max;
}
// Xuất danh sách
void outputList(LIST l)
{
for (NODE *k = l.pHead; k != NULL; k = k->pNext)
{
cout << "\t" << k->data << "\t";
}
}
void menu(LIST &l)
{
int luachon;
while (true)
{
system("cls");
cout << "\n\n\t\t==================== MENU ====================" << endl;
cout << "\n\t1. Them node vao danh sach" << endl;
cout << "\t2. Xuat danh sach lien ket don" << endl;
cout << "\t3. Them node p vao sau node q trong danh sach" << endl;
cout << "\t4. Them node p vao truoc node q trong danh sach" << endl;
cout << "\t5. Tim max trong danh sach da nhap" << endl;
cout << "\t6. Xoa node dau danh sach" << endl;
cout << "\t7. Xoa node cuoi danh sach" << endl;
cout << "\t8. Xoa 1 node sau node q danh sach" << endl;
cout << "\t9. Xoa node co khoa k bat ky" << endl;
cout << "\t0. Thoat" << endl;
cout << "\n\t\t==================== END ====================" << endl;
cout << "\nNhap lua chon cua ban: ";
cin >> luachon;
if (luachon < 0 || luachon > 9)
{
cout << "\nLua chon khong hop le, kiem tra lai!" << endl;
system("pause");
}
else if (luachon == 1)
{
int x;
cout << "\n\tx = ";
cin >> x;
NODE *p = initNODE(x); // khởi tạo 1 cái node
inputLast(l, p);
}
else if (luachon == 2)
{
cout << "\n\n==> Danh sach duoc nhap la: ";
outputList(l);
cout << endl;
system("pause");
}
else if (luachon == 3)
{
int x;
cout << "\nNhap gia tri node p can them vao sau index: p = ";
cin >> x;
NODE *p = initNODE(x);
inputAfterAnything(l, p); // Thêm node p vào sau node q trong danh sách l
}
else if (luachon == 4)
{
int x;
cout << "\nNhap gia tri node p can them vao truoc q: p = ";
cin >> x;
NODE *p = initNODE(x);
inputFirstAnything(l, p); // Thêm node p vào sau node q trong danh sách l
}
else if (luachon == 5)
{
cout << "\n==> So lon nhat trong danh sach la: " << searchMax(l) << endl;
system("pause");
}
else if (luachon == 6)
{
deleteFirst(l);
cout << "\n==> Da xoa phan tu dau danh sach" << endl;
system("pause");
}
else if (luachon == 7)
{
deleteLast(l);
cout << "\n==> Da xoa phan tu cuoi danh sach" << endl;
system("pause");
}
else if (luachon == 8)
{
int x;
cout << "\nNhap node q (node da ton tai trong danh sach): q = ";
cin >> x;
NODE *q = initNODE(x);
deleteLastAnything(l, q);
}
else if (luachon == 9)
{
int x;
cout << "\nNhap node can xoa: ";
cin >> x;
deleteAnyX(l, x);
}
else
break;
}
}
int main()
{
LIST l;
initList(l); // luôn luôn khởi tạo danh sách lk đơn trước khi thao tác với danh sách
menu(l);
system("pause");
return 0;
}
|
1938567febac085470c89c792b44ef8858b18541 | 24db1f37ea06b70e7a3889b6b619cc6f16de5966 | /NEXT_DATE_Equivalence_Class.cpp | a1b1644095bf8501a062dbfda7a74d932c8ff7e8 | [] | no_license | ruchit1131/Software_Testing | 1208a9cfa0989abd225f42b47d6a087a57e437d3 | c4c644921d38d8fca9386734167ed2b67de50cc7 | refs/heads/master | 2021-04-13T23:43:49.675844 | 2020-03-22T14:39:00 | 2020-03-22T14:39:00 | 249,195,335 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 701 | cpp | NEXT_DATE_Equivalence_Class.cpp | #include"next_date.h"
#include<ctime>
#include<cstdlib>
#define MIN -32767
int r(int l,int h);
int main()
{
srand( time(NULL) ) ;
int dl=1 ,dh=31 , ml=1,mh=12 ,yl=1000,yh=3000;
// int dm=(du+dl)/2 ,mm=(mu+ml)/2 ,ym=(yu+yl)/2 ;
cout<<"equivalence class testing \n";
int arr[7][3]= { {r(MIN,dl-1),r(ml,mh),r(yl,yh)},{r(dl,dh),r(ml,mh),r(yl,yh)},{ r(dh+1,INT_MAX),r(ml,mh),r(yl,yh) },
{r(dl,dh),r(MIN,ml-1),r(yl,yh)} , {r(dl,dh),r(mh+1,INT_MAX),r(yl,yh)},
{r(dl,dh),r(ml,mh),r(MIN,yl-1)} , {r(dl,dh),r(ml,mh),r(yh+1,INT_MAX)} };
for(int i=0;i<7;i++)
next_date(arr[i][0],arr[i][1],arr[i][2]) ;
}
int r(int l,int h)
{
return ( ( rand() % (h-l+1) ) + l );
}
|
9c1b5080d7956ddf17d7652fd4df922bd3dc662e | 08b47573efcbfee2ffeaa983b195f0e60d139407 | /data.h | 49cc44642c5a81916a252daa47fe359e79967af2 | [] | no_license | hosull01/Song-Search | 315b4aa8170c7d0ad543cf3d7f2f180cf86e6ee0 | 4dfe6c4b85db7ce847f3f711fd510adbf5fac458 | refs/heads/master | 2021-01-22T11:20:47.190825 | 2014-07-15T15:32:40 | 2014-07-15T15:32:40 | 21,865,333 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,039 | h | data.h | //
// data.h
// Name: Harry O'Sullivan
// Purpose: stores all of the data and pushes each word into a hashtable
// Date: 4/27/2014
//
#include <iostream>
#include <vector>
#include <fstream>
#include "hashtable.h"
using namespace std;
// an element in the songlist
struct song {
string title;
string artist;
vector<string> lyrics;
};
class Data {
public:
Data();
// goes through the given file and stores all words and push each word to
// a hashtable
void read_lyrics(char * filename, bool show_progress);
// displays the top ten songs with the given word
void search(string word);
private:
vector<song> songlist;
Hash thetable;
// processes each song
void process(string title, string artist, vector<string> lyrics);
// strips a word of punctuation and tolowers every letter
string alphaOnly(string word);
// prints 5 before and after of every instance of the word in a song
void print(songwithfreq song, string word);
}; |
bd0ef8132d43bbe48c81270bfcbb6c80b9626701 | d595b148172cd217a44e0b370095ee7313188c6d | /cf381_Div.2/a.cpp | aabcabb3eddd427ac91a55daf3f882e9bc2c8183 | [] | no_license | caowushang/code | 0dc255f003b83da3482f3335e0704ff6f11ac311 | 46fef8d3ddab922050b68941879d38f41a2c0287 | refs/heads/master | 2020-06-16T16:11:18.416061 | 2016-11-29T14:42:13 | 2016-11-29T14:42:13 | 75,085,726 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 710 | cpp | a.cpp | /* ************************************************************************
> File Name: a.cpp
> Author: caowushang
> Mail: 15630929347@163.com
> Created Time: 2016年11月24日 星期四 18时12分09秒
************************************************************************/
#include<bits/stdc++.h>
using namespace std;
int main()
{
//freopen("in","r",stdin);
//freopen("out","w",stdout);
long long n,a,b,c;
while(cin >> n >> a >> b >> c)
{
if(n%4==0)
{
cout << 0 << endl;
continue;
}
long long x=4-(n%4);
long long ans;
if(x==1)
ans=min(a,min(b+c,c*3));
else if(x==2)
ans=min(b,min(a*2,c*2));
else
ans=min(c,min(a*3,a+b));
cout << ans << endl;
}
return 0;
}
|
ce32155b52a7a12c4fa7554a027fc696dcb56896 | 12a5b72982291ac7c074210afc2c9dfe2c389709 | /online_judges/URI/Graphs/1669/code.cpp | 1a61acaed8580fd052db8e41e4f47bf187554a55 | [] | no_license | krantirk/Algorithms-and-code-for-competitive-programming. | 9b8c214758024daa246a1203e8f863fc76cfe847 | dcf29bf976024a9d1873eadc192ed59d25db968d | refs/heads/master | 2020-09-22T08:35:19.352751 | 2019-05-21T11:56:39 | 2019-05-21T11:56:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,325 | cpp | code.cpp | #include <bits/stdc++.h>
#define vi vector<int>
#define pb push_back
#define qi queue<int>
#define MAX 100001
using namespace std;
vi graph[MAX];
int indegree1[MAX], indegree2[MAX], n1, n2, d;
void saturate (qi q[], int indegree[], int flag){
while (q[flag].size()){
int v = q[flag].front();
q[flag].pop();
for (int i = 0; i < graph[v].size(); i++){
int u = graph[v][i];
indegree[u]--;
if (indegree[u] == 0) q[u > n1].push(u);
}
}
}
int topSort (int indegree[], int flag){
int changes = 0;
qi q[2];
for (int i = 1; i <= n1 + n2; i++)
if (indegree[i] == 0)
q[i > n1].push(i);
while (!q[0].empty() || !q[1].empty()){
if (q[flag].size()) changes++;
saturate(q, indegree, flag);
if (q[flag ^ 1].size()) changes++;
saturate(q, indegree, flag ^ 1);
}
return changes + 1;
}
int main(){
while(scanf ("%d %d %d", &n1, &n2, &d) && n1){
for(int i = 1; i <= n1 + n2; i++) graph[i].clear();
while(d--){
int x, y;
scanf("%d %d", &x, &y);
graph[y].pb(x);
indegree1[x]++;
indegree2[x]++;
}
printf ("%d\n", min (topSort(indegree1, 0), topSort(indegree2, 1)));
}
return 0;
}
|
0aa5d0bbc41856c2fdba9c1493c80e8ef33b9cf2 | aa7f5096fd8d2b697032f26231b6d70f17c2537e | /Pong/Pong/Paddle.h | 3388d3fafb650ba51901764572df7a054e4a2e52 | [
"MIT"
] | permissive | JDBucklin/Pong | 43264cf406b336f538ae322a24992a05d7161415 | a24c73ba7787d1ef60a8e55e819e15365209ae25 | refs/heads/master | 2020-12-03T00:05:07.850339 | 2017-07-19T21:27:51 | 2017-07-19T21:27:51 | 95,984,369 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 376 | h | Paddle.h | #pragma once
#include <SFML/Graphics.hpp>
class Paddle
{
public:
Paddle(float xPos, float yPos);
~Paddle();
void update(float deltaTime, float windowHeight);
void draw(sf::RenderWindow& window);
sf::Vector2f getPosition();
sf::Vector2f getSize();
private:
sf::RectangleShape paddle;
int paddleWidth;
int paddleHeight;
float halfPaddleHeight;
float paddleSpeed;
};
|
2a28aa83908a5ff4e41779c534a15280788e4da6 | da7fd6e0d9226826994261239423514f07967b85 | /__FilterRegistry/FilterRegistryWrap/FilterRegistryWrap.h | 255ef1b0e531ac3c03231ce914851b371c74bba4 | [] | no_license | dovanduy/BUGAV | a90186e456c3bb5ab1a303aa2f88c4d04ca89911 | 1baf64ba118ac4548a7ee1f42b86acc59e7ea04c | refs/heads/master | 2022-04-08T10:04:52.682512 | 2020-01-29T12:23:05 | 2020-01-29T12:23:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 685 | h | FilterRegistryWrap.h | #pragma once
#include "../FilterRegistryCtrl/FilterRegistryCtrl.h"
using namespace System;
public ref class FilterRegistryWrap {
FilterRegistryCtrl* ptr_FilterRegistryCtrl;
bool loaded;
public:
FilterRegistryWrap();
~FilterRegistryWrap();
VOID WRAP_FilterRegistryDrv_LoadDriver();
VOID WRAP_FilterRegistryDrv_UnloadDriver();
VOID WRAP_FilterRegistryDrv_OpenDevice();
VOID WRAP_FilterRegistryDrv_UpdateConfig();
VOID WRAP_FilterRegistryDrv_RegisterCallback();
VOID WRAP_FilterRegistryDrv_UnregisterCallback();
VOID WRAP_FilterRegistryDrv_GetCallbackVersion();
VOID WRAP_FilterRegistryDrv_TestCallbacks();
bool Get_loaded();
};
|
7cc24469126081f5571bd80c0a262f366de9b11e | 2779be59343d231855bbeafd087fc571d0f867dc | /Solo Competition/CF401/B.cpp | 21c769dbac95bcd97fb349d7ce888f0c411a608c | [] | no_license | frankbozar/Competitive-Programming | 4d7dbdf3db414718e77cc5afd69398b1f7f01eb8 | bcb1c363d11ada1f05ccd59bc8c93238c2503b23 | refs/heads/master | 2020-06-15T07:34:24.117330 | 2017-09-25T07:09:47 | 2017-09-25T07:09:47 | 75,315,592 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,722 | cpp | B.cpp | #include<cstdio>
#include<vector>
#include<algorithm>
using namespace std;
vector<int> read(int n)
{
vector<int> a(10, 0);
for(int i=0; i<n; i++)
{
int x;
scanf("%1d", &x);
a[x]++;
}
return a;
}
int one(vector<int> a, vector<int> b)
{
int ans=0;
for(int i=9; i>=0; i--)
{
for(; a[i]>0; a[i]--)
{
bool ok=false;
for(int j=9; j>=i; j--)
if( b[j]>0 )
{
b[j]--;
ok=true;
break;
}
if( !ok )
{
ans++;
for(int j=0; j<i; j++)
if( b[j]>0 )
{
b[j]--;
break;
}
}
}
}
return ans;
}
int two(vector<int> a, vector<int> b)
{
int ans=0;
for(int i=0; i<=9; i++)
{
for(; a[i]>0; a[i]--)
{
bool ok=false;
for(int j=i+1; j<=9; j++)
if( b[j]>0 )
{
b[j]--;
ok=true;
ans++;
break;
}
if( !ok )
for(int j=0; j<=i; j++)
if( b[j]>0 )
{
b[j]--;
break;
}
}
}
return ans;
}
int main()
{
int n;
scanf("%d", &n);
vector<int> a=read(n);
vector<int> b=read(n);
printf("%d\n%d\n", one(a, b), two(a, b));
}
|
b54db721fdd02ae1c9b6d73d21f20d59dfcd2911 | 0ae634be91566cab0e89ac6715aed12dc960cdb9 | /YCAMSpinSimple/src/YCAMSpinForce.h | e44c06e175a1416d3f54a90907e0aec536701ca4 | [] | no_license | obviousjim/YCAMSpin | 0c789b6991e133e286b29b1caf6a42e5e04e6274 | a992497c7c9a02852cc7d0bbe047a56e750699c8 | refs/heads/master | 2016-08-06T14:52:30.036263 | 2012-10-11T12:21:08 | 2012-10-11T12:21:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,135 | h | YCAMSpinForce.h | //
// YCAMSpinForce.h
// YCAMSpin
//
// Created by Jim on 9/28/12.
//
//
#ifndef YCAMSpin_YCAMSpinForce_h
#define YCAMSpin_YCAMSpinForce_h
#include "CloudInterludeForce.h"
class YCAMSpinForce : public CloudInterludeForce {
public:
ofVec3f center;
float power;
YCAMSpinForce() {
power = .1;
}
void update(){
// currentOffset += speed;
}
void applyForce(vector<CloudInterludeParticle>& particles){
//currentOffset = 0;
for(int i = 0; i < particles.size(); i++){
ofVec3f& pos = particles[i].position;
particles[i].force += (pos-center).getNormalized().getRotated(90, ofVec3f(0,1,0)) *ofVec3f(1,0,1) * power;
// particles[i].force += ofVec3f(ofSignedNoise(pos.x/density, pos.y/density, pos.z/density, currentOffset)*amplitude,
// ofSignedNoise(pos.x/density, pos.y/density, pos.z/density, currentOffset+1000)*amplitude,
// ofSignedNoise(pos.x/density, pos.y/density, pos.z/density, currentOffset+2000)*amplitude );
}
}
};
#endif
|
463c7cfea260f157a71c45155690b8ceaa806413 | 544c55e229f5f48fe0a6b096b88aba88ab9b323c | /mysql.h | 88c49d45376ffba242946839ee14a02b1d72f121 | [] | no_license | zenaki/Marine-Service | 70a75ca6f9d64b120be4a9ddebe80428407f7fc4 | 8369e69f44f6223a0384fec2d8e63cb4030f7400 | refs/heads/master | 2021-10-18T06:14:03.793139 | 2019-02-14T10:03:07 | 2019-02-14T10:03:07 | 110,666,807 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 660 | h | mysql.h | #ifndef MYSQL_H
#define MYSQL_H
#include "utama.h"
class mysql
{
public:
mysql();
QString host;
QString db_name;
QString username;
QString password;
QSqlDatabase connect_db(QString name);
void close(QSqlDatabase db);
QStringList read(QSqlDatabase db, QString query, QStringList parameter);
void write(QSqlDatabase db, QString query, QStringList parameter);
void modem_info(QSqlDatabase db, utama *marine);
void modem_getway(QSqlDatabase db, account *acc);
bool check_table_is_available(QSqlDatabase db, QString date);
void create_tabel_data_harian(QSqlDatabase db, QString date);
};
#endif // MYSQL_H
|
c29ac3544fbc19ca9b16c3ce3b9dd79bd500d65c | aa1e2f3fefe68278351964c23ab85870013670ff | /include/Menu.h | c5089b67b8724c6fc23d0595d5f14d6356470e83 | [] | no_license | CapitainePigeon/Quarto | 581b2fa95b4aff3229e3648a8e93052a708d61a9 | 64c407bad4866d0e24550e761619bce41ac8d217 | refs/heads/master | 2020-04-25T03:23:16.098735 | 2019-04-14T19:27:14 | 2019-04-14T19:27:14 | 172,474,939 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 402 | h | Menu.h | #ifndef MENU_H
#define MENU_H
#include <string>
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include "Image.h"
#define SCREEN_WIDTH 512
#define SCREEN_HEIGHT 512
using namespace std;
class Menu {
private :
char format [50];
SDL_Window * fenetre;
SDL_Renderer * renderer;
Image im_menu;
public :
Menu();
~Menu();
void MenuBoucle();
void sdlAffichage();
};
#endif // MENU_H
|
91e78d60ec94406836e07a27b8dc9d95b1c5016c | 7e22119414a68482fdc7b484d7f0ff373f68da7e | /master/interpreter/test.cpp | 4b2c9cce4aa128580c3c0e0afb7bfdfe719c1130 | [] | no_license | Winnerhust/DesignPattern | 9540efc1accd70b35c8f460d4026766d0c30bd00 | 12dc73bb55351474ec64b8f976f47af82aeb1796 | refs/heads/master | 2020-03-29T12:00:24.082691 | 2013-08-27T09:25:50 | 2013-08-27T09:25:50 | 12,081,581 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 258 | cpp | test.cpp | #include "context.h"
#include "interpreter.h"
int main(int argc, char const *argv[])
{
Context c;
Expression *te = new TerminalExpression("ter");
te->interpret(c);
Expression *nte = new NonTerminalExpression("nonter");
nte->interpret(c);
return 0;
}
|
6673c30dad31f231c86a5e1d6ef57cd9067744b0 | d99635801044ebda964af586fbd6309c42a0b978 | /binaryTreeMaximumPathSum.cpp | 206316f690bc5b60017c46ef3097198ac7478e38 | [] | no_license | wongxingjun/leetcode | 071296001bd61aaca83025290fa8e6077d000669 | 4353422fa5e1244e2e2f1809462c1a3b59784a15 | refs/heads/master | 2020-05-21T13:26:54.571148 | 2016-11-01T07:24:06 | 2016-11-01T07:24:06 | 62,566,729 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 576 | cpp | binaryTreeMaximumPathSum.cpp | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int res=INT_MIN;
int maxPathSum(TreeNode* root) {
maxPath(root);
return res;
}
int maxPath(TreeNode* node){
if(node==NULL)
return 0;
int l=max(0,maxPath(node->left));
int r=max(0,maxPath(node->right));
res=max(res,l+r+node->val);
return max(l,r)+node->val;
}
};
|
c68ed6f1b8b828008a8e84bd32931a30c1a9fd63 | 5c3839542bfe038a8c2577dd11a0a07d42e7c9bb | /iStickServer/iStickServer/MouseAction.h | 7e66c8056ad30e7e27ec2f4ec283f69dead06f7e | [] | no_license | etamar211/iStick | e025d955eb711da3fef634ad3c42cd2345bb2bb0 | 9497960b550a05fef54f897c252ee3e52e5eb101 | refs/heads/main | 2023-07-20T06:40:39.081370 | 2021-08-29T09:04:04 | 2021-08-29T09:04:04 | 400,995,500 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 367 | h | MouseAction.h | #pragma once
#include <Windows.h>
class MouseAction
{
private:
INPUT _mouseInput;
public:
MouseAction(); // constructor that initializes the INPUT structure
void MoveMouse(int,int); // Move the mouse.
void RightPress();
void LeftPress();
void MiddlePress();
void RightRelease();
void LeftRelease();
void MiddleRelease();
~MouseAction(); // destructor
};
|
d890187c7109b9ebd612a62c12c28d71944ccf49 | ef9e15db20a82b4d5e22caae4d7a5065a65cff27 | /CPP_160(std_string의 길이와 용량)/CPP_160/main.cpp | 19deea0933e0f37d8f66871e9c9f1ea53a25d3ea | [] | no_license | jinseongbe/cpp_study | 62a0b688a8f6b27f02449686a3a05dd053632f2f | 37be65a75eb33516a4b4434a05975ed61fce7194 | refs/heads/master | 2023-04-10T17:32:03.788508 | 2021-04-18T14:35:07 | 2021-04-18T14:35:07 | 354,449,067 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,228 | cpp | main.cpp | #include <iostream>
#include <string>
using namespace std;
int main()
{
string my_str("012345678");
cout << my_str.size() << endl; // <- 주의할점! c-style의 문자열에서는 마지막에 null 값을 포함해서 한글자가 더 많은 크기를 가지지만
// string의 경우는 class로써 내부적으로 포인터 말고 길이를 직접 가지고 있기 때문에 null값을 찾을 필요가 없어서 없음
cout << my_str.capacity() << endl; // <- new,delete할 시간을 줄이기 위해, 여분의 용량을 가지고 있는것! (reallocate를 줄이기 위함)
cout << my_str.max_size() << endl;
my_str.reserve(1000); // <- 최소한 이만큼의 크기는 확보해달라는 뜻, 실제는 이것보다 클 수 있음
cout << my_str.capacity() << endl;
cout << std::boolalpha; // <- 0, 1을 False, True로 출력
cout << my_str.empty() << endl; // <- 비어있냐?
string my_str2;
string my_str3("");
cout << my_str2.empty() << endl;
cout << my_str3.empty() << endl; // null값을 보관하지 않음!
return 0;
}
|
6c22bf916cdfc2a495bff96b1c6017249feb2461 | d6ae8dc5bf9f94717a243aebd9572c1289661978 | /[BOJ]4307/Source.cpp | ec2f38cc76dd37bc705c4addbaa2309c645f3e26 | [] | no_license | jinbeomdev/daily-algorithm-problems | b3ffd98626861fe670b5c9778a88c110b4654b33 | 7b1155bc9e7ad48efa490b8f88fe6b599182ee93 | refs/heads/master | 2021-06-12T09:16:32.184753 | 2019-10-21T14:41:35 | 2019-10-21T14:41:35 | 91,214,514 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 933 | cpp | Source.cpp | //#define _CRT_SECURE_NO_WARNINGS
#include <cstdio>
#include <cstdlib>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
int test_case_size;
int stick_length;
int num_ant;
scanf("%d", &test_case_size);
for (int test_case = 1; test_case <= test_case_size; test_case++) {
vector<int> ant_position;
vector<int> min_ant_position;
int min_result;
int max_result;
scanf("%d %d", &stick_length, &num_ant);
for (int i = 0; i < num_ant; i++) {
int postion;
scanf("%d", &postion);
ant_position.push_back(postion);
min_ant_position.push_back(min(postion, stick_length - postion));
}
sort(ant_position.begin(), ant_position.end());
sort(min_ant_position.begin(), min_ant_position.end());
max_result = max(stick_length - ant_position.front(), ant_position.back());
min_result = min_ant_position.back();
printf("%d %d\n", min_result, max_result);
}
//system("pause");
} |
dc0cdb73b830bcd283b142b0a36a1ef7b8c36047 | 34f222b9497336015b491d7447d383e2d46e02cf | /Source/DX9API/OcclusionQuery.h | 622cffd0bedda7a1fff53daebb1fa909232c3b1d | [] | no_license | H3D-Zoo/Lion | 77ef3f652eb324a8afd7c6f6f53bb85b71a197ee | f9b5b7deaceab93c313c1541a1e575ff9802cd97 | refs/heads/master | 2021-01-25T09:31:52.670413 | 2018-02-01T08:40:28 | 2018-02-01T08:40:28 | 93,846,183 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 461 | h | OcclusionQuery.h | #pragma once
#include "../../RenderAPI/RenderAPI.h"
#include "DX9Include.h"
#include "RefCount.hpp"
class OcclusionQuery : public RenderAPI::OcclusionQuery
{
public:
OcclusionQuery(IDirect3DQuery9*);
~OcclusionQuery();
virtual bool Begin();
virtual void End();
virtual bool Get(void* dataPtr, unsigned int length);
virtual unsigned int AddReference();
virtual void Release();
private:
RefCount m_refCount;
IDirect3DQuery9* m_pOcclusionQuery;
};
|
02fd06d43076ccef533cd41212fc38dcde074430 | ffff2a4fb72a163e4d42b01cefa1f5566784990f | /codeforces/contests/644DIV3/buying_shovels.cpp | e99b8aad7904ba8dd0551938ae59caf7ef2a8e16 | [] | no_license | sanyamdtu/competitive_programming | d5b4bb6a1b46c56ebe2fe684f4a7129fe5fb8e86 | 5a810bbbd0c2119a172305b16d7d7aab3f0ed95e | refs/heads/master | 2021-10-25T07:11:47.431312 | 2021-10-06T07:37:25 | 2021-10-06T07:37:25 | 238,703,031 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 476 | cpp | buying_shovels.cpp | #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int main(){
int t;
cin>>t;
while (t--)
{
ll n,k;
cin>>n>>k;
ll ans=INT_MAX;
ll a;
(100000>k)?a=k:a=100000;
for(ll i=a;i>=1;i--){
if(n%i==0){
ans=(min(ans,n/i));
}
}
if(n<=k)
cout<<1<<endl;
else if(ans!=INT_MAX&&n>k){
cout<<ans<<endl;
}
}
} |
cfbb2dcda8e74ac8a204c60d64e135afbf8bc8d2 | 90ed8c2f83b8db17f539428541b6a2d49a9ab999 | /PROGRAM PRACTISE/Linked list2.cpp | abef845e860468ee2e2632aa052309c2107dcc2d | [] | no_license | Piaash/UVA-Solution-Collection | 49a319330f85f2cb4e4e0f3d4c92238f08e51391 | 8eab98fd75e3d4298f047c16a5d3d7d1552ca815 | refs/heads/master | 2021-01-01T15:48:46.733192 | 2017-07-19T11:29:04 | 2017-07-19T11:29:04 | 97,708,135 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,666 | cpp | Linked list2.cpp | #include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
struct node
{
int v1;
int v2;
struct node *next;
};
int main()
{
struct node *p,*q,*r,*r2,*p2,*p1,*r1;
int m,n,x,y,z,i,j,k;
puts("No of input: ");
scanf("%d",&n);
puts("Power & Co-efficient:");
for(i=1;i<=n;i++)
{
scanf("%d %d",&x,&y);
if(i==1)
{
p=(struct node *)malloc(sizeof(struct node));
p->v1=x;
p->v2=y;
p->next=NULL;
r=p;
}
else
{
q=(struct node *)malloc(sizeof(struct node));
q->v1=x;
q->v2=y;
q->next=NULL;
p->next=q;
p=q;
}
}
p=r;
i=1;
p1=r;
while(p1!=NULL)
{
int count=0;
p2=r;
while(p2!=NULL)
{
if(p2->v1==p1->v1 && p2->v2!=NULL)
{
count+=p2->v2;
p2->v2=NULL;
}
p2=p2->next;
}
if(i==1)
{
p=(struct node *)malloc(sizeof(struct node));
p->v1=p1->v1;
p->v2=count;
p->next=NULL;
r1=p;
}
else
{
q=(struct node *)malloc(sizeof(struct node));
q->v1=p1->v1;
q->v2=count;
q->next=NULL;
p->next=q;
p=q;
}
i++;
p1=p1->next;
}
p=r1;
puts("After Ans: ");
while(p!=NULL)
{
if(p->v2!=NULL)
printf("%d %d\n",p->v1,p->v2);
p=p->next;
}
return 0;
}
|
23d561d7f2365bdd747a824416a3a7a8528bd36b | 4960d4f64928a065748fd072fc6d246e23775bbd | /hdu2807之矩阵乘法+最短路.cpp | fbf029eb325da21c8eba80c189b82622bc89fd51 | [] | no_license | Stephen1993/ACM-code | b46d75e4367387e7ca4bec6442a7b29b73594f8d | fd6c2fbad8b0dd1d5f3c90df733c8bc09070ae2a | refs/heads/master | 2020-07-28T19:44:03.076259 | 2019-11-15T15:08:12 | 2019-11-15T15:08:12 | 73,697,351 | 0 | 1 | null | null | null | null | GB18030 | C++ | false | false | 2,136 | cpp | hdu2807之矩阵乘法+最短路.cpp | #include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<string>
#include<queue>
#include<algorithm>
#include<map>
#include<iomanip>
#define INF 99999999
using namespace std;
const int MAX=80+10;
int n,m,dist[MAX][MAX],s,t;
int array[MAX][MAX][MAX],temp[MAX][MAX];
//array记录初始矩阵,temp记录array转化后的一维矩阵
void check(int a,int c){//转化为一维矩阵在此处优化大
for(int i=1;i<=m;++i){
if(temp[0][i] != temp[c][i])return;
}
dist[a][c]=1;
}
void MakeRoad(int a,int b){
for(int i=1;i<=m;++i){
temp[0][i]=0;
for(int j=1;j<=m;++j){//转化为一维矩阵在此处优化大
temp[0][i]+=array[a][i][j]*temp[b][j];//相当于array[a]*array[b]*[0,1,2,3...m];//[0...m-1]是行矩阵
}
}
for(int i=1;i<=n;++i){
if(i == a || i == b)continue;
check(a,i);
}
}
void floyd(){
for(int k=1;k<=n;++k){
for(int i=1;i<=n;++i){
for(int j=1;j<=n;++j){
if(dist[i][k]+dist[k][j]<dist[i][j]){
dist[i][j]=dist[i][k]+dist[k][j];
}
}
}
}
}
int main(){
while(cin>>n>>m,n+m){
for(int i=1;i<=n;++i){
for(int j=1;j<=m;++j){
temp[i][j]=0;
for(int k=1;k<=m;++k){
scanf("%d",&array[i][j][k]);
temp[i][j]+=array[i][j][k]*k;//array*[1,...m],[1...m]是一维行矩阵
}
}
}
for(int i=1;i<=n;++i){
for(int j=i+1;j<=n;++j)dist[i][j]=dist[j][i]=INF;
}
for(int i=1;i<=n;++i){
for(int j=1;j<=n;++j){
if(i == j)continue;
MakeRoad(i,j);//创建道路
}
}
floyd();//求每个点到其他点的距离
cin>>n;
for(int i=0;i<n;++i){
scanf("%d%d",&s,&t);
if(dist[s][t] == INF)printf("Sorry\n");
else printf("%d\n",dist[s][t]);
}
}
return 0;
} |
9427008565254fb1523d3b407c2a94a57e30a8e2 | 956b91611aa6901913d24025a45d33dfcb0abadb | /lab7/NodeList.cpp | f0e62d5cb0d8984dd79334b76228c90c0b9c938c | [] | no_license | dhruvchawla1996/ece244_labs | b72f0bb7ca6a4128edb3b2b6cf051d33e68247ae | 7568041ebeb263c2bf5d2da671ae65ef42d8a4d7 | refs/heads/master | 2016-08-11T11:24:35.245511 | 2015-12-31T14:11:50 | 2015-12-31T14:11:50 | 48,846,809 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 13,463 | cpp | NodeList.cpp | /*
* File: NodeList.cpp
*/
#include "NodeList.h"
#include "easygl.h"
extern easygl window;
using namespace std;
NodeList::NodeList() {
nodeHead = NULL;
}
NodeList::~NodeList() {
while (nodeHead != NULL) {
Node* p = nodeHead;
nodeHead = p->getNext();
p->setNext(NULL);
delete p;
}
}
Node* NodeList::findOrInsertNode(int id) {
// find node by id
Node* p = nodeHead;
while (p != NULL) {
if (p->getID() == id) {
return p;
}
p = p->getNext();
}
// at this point, the node does not exist, so we need to insert it
// start at the top again
p = nodeHead;
Node* prev = NULL;
// allocate new node
Node* newNode = new Node(id);
while (p != NULL && id > p->getID()) {
prev = p;
p = p->getNext();
}
newNode->setNext(p);
if (prev == NULL) {
nodeHead = newNode;
} else {
prev->setNext(newNode);
}
return newNode;
}
bool NodeList::resistorExists(string name) const {
// traverse through the linked list
Node *p = nodeHead;
while (p != NULL) {
if (p->findResistor(name)) // resistor found!
return true;
p = p->getNext();
}
return false; // search complete and resistor not found
}
double NodeList::changeResistance(string name, double new_resistance) {
// check if resistor exists
if (resistorExists(name)) {
int resistorsModified = 0; // counts resistors modified over the course
// of while loop, should be 2 at the end of
// the while loop
double old_resistance, temp_resistance;
Node* p = nodeHead;
while (p != NULL) {
temp_resistance = p->changeResistance(name, new_resistance);
if (temp_resistance != -1) { // -1 = resistor not found in node
old_resistance = temp_resistance;
resistorsModified++;
}
p = p->getNext();
}
if (resistorsModified == 2)
return old_resistance;
}
return -1; // resistor does not exist, hence command is not successful
}
bool NodeList::deleteResistor(string name) {
// check if resistor exists
if (resistorExists(name)) {
int resistorsDeleted = 0; // counts resistors deleted over the course
// of while loop, should be 2 at the end of
// the while loop
Node* p = nodeHead;
while (p != NULL) {
if (p->deleteResistor(name))
resistorsDeleted++;
p = p->getNext();
}
return (resistorsDeleted == 2);
}
return false; // resistor does not exist, hence command is not successful
}
void NodeList::deleteAllResistors() {
Node* p = nodeHead;
// traverse through node list
while (p != NULL) {
p->deleteAllResistors(); // delete all resistors at a node
p = p->getNext(); // go to next node
}
}
void NodeList::printResistor(string name) const {
if (resistorExists(name)) { // search for resistor
bool printed = false; // to prevent printing twice
Node *p = nodeHead;
// traverse through the node list
while (p != NULL && !printed) {
if (p->printResistor(name)) // print resistor if connected to node
printed = true; // resistor has been printed
p = p->getNext();
}
}
}
void NodeList::print(int id) const {
Node* p = nodeHead;
// traverse through node list
while (p != NULL) {
if (p->getID() == id) { // match ID
p->print(); // print details of node p
return; // since ID is unique, no need to search rest of the list
}
p = p->getNext();
}
}
void NodeList::printAll() const {
Node* p = nodeHead;
// traverse through node list
while (p != NULL) {
p->print(); // print details of node p
p = p->getNext();
}
}
bool NodeList::voltageSet() const {
Node* p = nodeHead;
while (p != NULL) {
if (p->is_voltage_set()) // has voltage been set on p?
return true;
p = p->getNext();
}
return false; // voltage has not been set on any node
}
void NodeList::solve() {
// set voltage to 0 for nodes which don't have their voltage set by user
Node* p = nodeHead;
while (p != NULL) {
p->setVoltageForSolver(0);
p = p->getNext();
}
double MIN_ITERATION_CHANGE = 0.0001;
double max_node_voltage_change = 42; // It's the answer to the ultimate
// question of the universe
while (max_node_voltage_change > MIN_ITERATION_CHANGE) {
p = nodeHead;
max_node_voltage_change = 0;
double new_voltage; // delare new voltage of p after one iteration
while (p != NULL) {
if (!p->is_voltage_set()) {
// as equation 3 consists of two terms multiplied together,
// I will calculate the two terms separately for all nodes
// connected to p and multiply them together
double first_term = 0, second_term = 0;
ResistorList& res = p->resList;
// traverse through p's resList
Resistor* r = res.getResHead();
while (r != NULL) {
double resistance = r->getResistance();
first_term += (1 / resistance);
// get voltage of other node
int other_node_id = r->getOtherNodeID(p->getID());
Node* other_node = findOrInsertNode(other_node_id);
double other_node_voltage = other_node->getVoltage();
second_term += (other_node_voltage / resistance);
r = r->getNext();
}
// calculate new voltage of p
new_voltage = (1 / first_term) * second_term;
// check if change is greater than MIN_ITERATION_CHANGE
if (fabs(p->getVoltage() - new_voltage) > \
max_node_voltage_change) {
max_node_voltage_change = \
fabs(p->getVoltage() - new_voltage);
}
// store new voltage
p->setVoltageForSolver(new_voltage);
}
p = p->getNext();
}
}
// print output
cout << "Solve:" << endl;
p = nodeHead;
while (p != NULL) {
cout << " Node " << p->getID() << ": " << setprecision(2) << fixed
<< p->getVoltage() << " V" << endl;
p = p->getNext();
}
}
void NodeList::clearNodes () {
bool clean = false;
while (!clean) {
clean = true;
if (nodeHead != NULL) {
Node* p = nodeHead;
Node* prev = NULL;
while (p != NULL) {
// check if node has no connections or no assigned voltage
if (!p->getNumberOfResistorsConnected() && !p->is_voltage_set()) {
if (prev == NULL)
nodeHead = p->getNext();
else
prev->setNext(p->getNext());
p->setNext(NULL);
delete p;
clean = false;
break;
}
prev = p;
p = p->getNext();
}
}
}
}
void NodeList::solveForDraw() {
// set voltage to 0 for nodes which don't have their voltage set by user
Node* p = nodeHead;
while (p != NULL) {
p->setVoltageForSolver(0);
p = p->getNext();
}
double MIN_ITERATION_CHANGE = 0.0001;
double max_node_voltage_change = 42; // It's the answer to the ultimate
// question of the universe
while (max_node_voltage_change > MIN_ITERATION_CHANGE) {
p = nodeHead;
max_node_voltage_change = 0;
double new_voltage; // delare new voltage of p after one iteration
while (p != NULL) {
if (!p->is_voltage_set()) {
// as equation 3 consists of two terms multiplied together,
// I will calculate the two terms separately for all nodes
// connected to p and multiply them together
double first_term = 0, second_term = 0;
ResistorList& res = p->resList;
// traverse through p's resList
Resistor* r = res.getResHead();
while (r != NULL) {
double resistance = r->getResistance();
first_term += (1 / resistance);
// get voltage of other node
int other_node_id = r->getOtherNodeID(p->getID());
Node* other_node = findOrInsertNode(other_node_id);
double other_node_voltage = other_node->getVoltage();
second_term += (other_node_voltage / resistance);
r = r->getNext();
}
// calculate new voltage of p
new_voltage = (1 / first_term) * second_term;
// check if change is greater than MIN_ITERATION_CHANGE
if (fabs(p->getVoltage() - new_voltage) > \
max_node_voltage_change) {
max_node_voltage_change = \
fabs(p->getVoltage() - new_voltage);
}
// store new voltage
p->setVoltageForSolver(new_voltage);
}
p = p->getNext();
}
}
}
void NodeList::set_draw_coords(float& xleft, float& ybottom, float& xright, float& ytop) {
xleft = 0;
ybottom = 0;
int WIDTH_BUFFER = 20;
int HEIGHT_BUFFER = 200;
int WIDTH_FOR_NODE = 100;
int HEIGHT_FOR_RESISTOR = 100;
int count_nodes = 0, count_resistors = 0;
Node* p = nodeHead;
while (p != NULL) {
count_nodes++;
count_resistors += p->getNumberOfResistorsConnected();
p = p->getNext();
}
count_resistors /= 2;
xright = WIDTH_FOR_NODE * count_nodes + WIDTH_BUFFER;
ytop = HEIGHT_FOR_RESISTOR * count_resistors + HEIGHT_BUFFER;
}
void NodeList::draw() {
window.gl_clearscreen();
int count_resistors = 0;
Node* p = nodeHead;
while (p != NULL) {
count_resistors += p->getNumberOfResistorsConnected();
p = p->getNext();
}
count_resistors /= 2;
int WIDTH_FOR_NODE = 100;
int HEIGHT_BUFFER = 200;
int HEIGHT_FOR_RESISTOR = 100;
int HEIGHT_FOR_NODE = HEIGHT_FOR_RESISTOR * count_resistors + HEIGHT_BUFFER;;
int LEFT_BUFFER = 10;
int BOTTOM_BUFFER = 50;
int x_coord = LEFT_BUFFER;
stringstream ss;
string text;
p = nodeHead;
while (p != NULL) {
window.gl_setcolor(LIGHTGREY);
window.gl_fillrect(x_coord, BOTTOM_BUFFER, x_coord + 10, HEIGHT_FOR_NODE);
window.gl_setcolor(BLACK);
ss << "Node ";
ss << p->getID() <<endl;
getline(ss,text);
window.gl_drawtext(x_coord+5, BOTTOM_BUFFER/2 + 5, text);
ss.flush();
ss << p->getID();
ss << " V"<< endl;
getline(ss,text);
window.gl_drawtext(x_coord+5, BOTTOM_BUFFER/2 - 5, text);
ss.flush();
x_coord =x_coord+ WIDTH_FOR_NODE;
p = p->getNext();
}
x_coord = 10;
int y_coord = BOTTOM_BUFFER+HEIGHT_FOR_RESISTOR;
p = nodeHead;
while (p != NULL) {
ResistorList& res = p->resList;
Resistor* r = res.getResHead();
while (r != NULL) {
if (r->getEndpointOne() > p->getID()) {
window.gl_setcolor(BLACK);
window.gl_drawline(x_coord+2.5, y_coord, x_coord+(r->getEndpointOne() - p->getID())*WIDTH_FOR_NODE+2.5, y_coord);
window.gl_setcolor(RED);
window.gl_fillrect(x_coord+2.5+(r->getEndpointOne() - p->getID())*WIDTH_FOR_NODE/2-10, y_coord-10, x_coord+2.5+(r->getEndpointOne() - p->getID())*WIDTH_FOR_NODE/2+10, y_coord+10);
ss << r->getName() << " (" << r->getResistance() << " Ohm)" << endl;
getline(ss, text);
window.gl_drawtext(x_coord+2.5+(r->getEndpointOne() - p->getID())*WIDTH_FOR_NODE/2, y_coord-20, text);
ss.flush();
y_coord += HEIGHT_FOR_RESISTOR;
} else if (r->getEndpointTwo() > p->getID()) {
window.gl_setcolor(BLACK);
window.gl_drawline(x_coord+2.5, y_coord, x_coord+( r->getEndpointTwo() - p->getID() )*WIDTH_FOR_NODE+2.5, y_coord);
window.gl_setcolor(RED);
window.gl_fillrect(x_coord+2.5+(r->getEndpointTwo() - p->getID() )*WIDTH_FOR_NODE/2-10, y_coord-10, x_coord+2.5+(r->getEndpointTwo() - p->getID() )*WIDTH_FOR_NODE/2+10, y_coord+10);
ss << r->getName() << " (" << r->getResistance() << " Ohm)" << endl;
getline(ss, text);
window.gl_drawtext(x_coord+2.5+(r->getEndpointTwo() - p->getID() )*WIDTH_FOR_NODE/2, y_coord-20, text);
ss.flush();
y_coord += HEIGHT_FOR_RESISTOR;
}
r = r->getNext();
}
x_coord += WIDTH_FOR_NODE;
p = p->getNext();
}
} |
b20c6b4cbebac385c4c6c0a12f738a9783e9b6be | d6794736f216e2dc0e8798032e0ffead2fceb874 | /models/CNE6SSM/CNE6SSM_semi_two_scale_susy_scale_constraint.hpp | e666b67f1787c0aac27811137d53adc414397ce8 | [] | no_license | azedarach/CNE6SSM-Spectrum | 02f42cd79cece6f23a32f96546415e7630e62b27 | 6c5468dc359c0e2e37afece3b939d7034d55fd04 | refs/heads/master | 2021-06-07T08:34:04.063733 | 2015-10-26T02:47:17 | 2015-10-26T02:47:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,736 | hpp | CNE6SSM_semi_two_scale_susy_scale_constraint.hpp | // ====================================================================
// Test implementation of SUSY scale constraint to be used in
// semianalytic version of the two-scale algorithm
// ====================================================================
#ifndef CNE6SSM_SEMI_TWO_SCALE_SUSY_SCALE_CONSTRAINT_H
#define CNE6SSM_SEMI_TWO_SCALE_SUSY_SCALE_CONSTRAINT_H
#include "CNE6SSM_semi_susy_scale_constraint.hpp"
#include "CNE6SSM_semi_two_scale_input_parameters.hpp"
#include "CNE6SSM_semi_two_scale_high_scale_constraint.hpp"
#include "two_scale_constraint.hpp"
namespace flexiblesusy {
template <class T>
class CNE6SSM_semianalytic;
class Two_scale;
template<>
class CNE6SSM_semianalytic_susy_scale_constraint<Two_scale> : public Constraint<Two_scale> {
public:
CNE6SSM_semianalytic_susy_scale_constraint();
CNE6SSM_semianalytic_susy_scale_constraint(CNE6SSM_semianalytic<Two_scale>*);
virtual ~CNE6SSM_semianalytic_susy_scale_constraint();
virtual void apply();
virtual double get_scale() const;
virtual void set_model(Two_scale_model*);
void clear();
double get_initial_scale_guess() const;
const CNE6SSM_semianalytic_input_parameters<Two_scale>& get_input_parameters() const;
CNE6SSM_semianalytic<Two_scale>* get_model() const;
void initialize();
CNE6SSM_semianalytic_high_scale_constraint<Two_scale>* get_input_scale_constraint() const;
void set_input_scale_constraint(CNE6SSM_semianalytic_high_scale_constraint<Two_scale>*);
protected:
void update_scale();
private:
double scale;
double initial_scale_guess;
CNE6SSM_semianalytic<Two_scale>* model;
CNE6SSM_semianalytic_high_scale_constraint<Two_scale>* high_constraint;
};
} // namespace flexiblesusy
#endif
|
45d1bfc8875dd34dfd9d3a9d3e913cbb582da011 | 7700c743875a990022d4346d6be71da1da0818dc | /cook_torrance.h | 596cce65b971ce0264116f4bd5e997b20bf16b15 | [
"MIT"
] | permissive | LuanQBarbosa/ray-tracer-university-project | 290d96304fda684459f7ebd8ecc502eb65b20332 | 9fd8ab9d8e8b98dc186e7353788ed8a93862cb2b | refs/heads/master | 2020-04-21T12:19:00.375845 | 2019-05-18T00:48:56 | 2019-05-18T00:48:56 | 169,558,170 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 232 | h | cook_torrance.h | #ifndef COOK_TORRANCE_H_
#define COOK_TORRANCE_H_
#include <glm/glm.hpp>
#include "brdf.h"
class CookTorrance : public BRDF
{
public:
CookTorrance ( glm::vec3 reflectance );
glm::vec3 fr();
};
#endif /* COOK_TORRANCE_H_ */
|
228c6199cf305a8af5ea790b54323c4392a2d4e1 | dca5683253403875ae613a45d7f3009e777165bf | /exceptions/IllegalArgumentException.cpp | 08d509a9e32af4fca61354eb83ef7d4baef5a385 | [] | no_license | markscamilleri/cps2000assignment | 387937d219e6fe232307a8dc464fb2e087dcc520 | 04098341f9c6c3a659507641c6568815f4f71e54 | refs/heads/master | 2022-04-16T14:45:14.687272 | 2017-10-17T07:36:21 | 2017-10-17T07:36:21 | 107,233,274 | 0 | 0 | null | 2020-04-09T12:39:09 | 2017-10-17T07:30:30 | Makefile | UTF-8 | C++ | false | false | 537 | cpp | IllegalArgumentException.cpp | /**
* @file
* @author Mark Said Camilleri
* @version 20170501.
*/
#include "IllegalArgumentException.h"
exceptions::IllegalArgumentException::IllegalArgumentException(const std::string message, const std::string &argument)
: argument(argument) {
Exception::message = message;
}
const std::string &exceptions::IllegalArgumentException::getArgument() const {
return argument;
}
const std::string exceptions::IllegalArgumentException::getError() const {
return getMessage() + " on argument " + getArgument();
} |
dfa9701f5c03eed8d5903fb1ce74d69c27c6313f | 77ae4e7c8252eb63e7a7337e24383a8d19c6e8c6 | /src/datastructures/KernelWrapper.hpp | 96ae24f986f6b80e30ba425abd78ad66a44ee4ce | [] | no_license | JuantAldea/trax | 32a2f3fa5604a76cf342378b04d0ce52b27b5dcc | 232f0c6491f8415f1760d43d9bdecb2dfbe547e3 | refs/heads/master | 2021-01-15T20:47:45.515275 | 2014-07-29T14:23:23 | 2014-07-29T14:23:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 854 | hpp | KernelWrapper.hpp | #pragma once
#include <boost/noncopyable.hpp>
#include <clever/clever.hpp>
#include <datastructures/Logger.h>
#include <vector>
//Curiously recurring template pattern (CRTP)
template <typename T>
class KernelWrapper : private boost::noncopyable {
public:
KernelWrapper(clever::context & ctext) : ctx(ctext) { }
protected:
clever::context & ctx;
#define PRINTF(a) printf a // print debug output
//#define PRINTF(a) // no debug output
static const std::string oclDEFINES;
public:
static std::vector<cl_event> events;
static void clearEvents() {
events.clear();
}
};
template <typename T> const std::string KernelWrapper<T>::oclDEFINES = PROLIX ? "#define PRINTF(a) printf a" :
"#define PRINTF(a)";
template <typename T> std::vector<cl_event> KernelWrapper<T>::events;
|
a99ce10ebfc61a8577758447f265fb176f853c0d | 59409fab0056c63eb8b43c6bebc46ad2320e5f3f | /MAX10/tsbs/common_sw_library/tsb/ip/software/video_dma_up_encapsulator/video_dma_up_virtual_uart.h | 4c24dcb55016446fcdb241ab28b8fe47dd0da5ee | [] | no_license | thomaslindner/xu1-max10-testing | ce96004e9ee51c927ec64fdc8d2438bc95742a46 | a44bdeff1bf533632bfaea5ab9c8cf22d0529e85 | refs/heads/master | 2022-12-22T20:14:30.665124 | 2020-05-19T22:53:52 | 2020-05-19T22:53:52 | 295,867,338 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 848 | h | video_dma_up_virtual_uart.h | /*
* video_dma_up_virtual_uart.h
*
* Created on: Feb 12, 2014
* Author: yairlinn
*/
#ifndef VIDEO_DMA_UP_VIRTUAL_UART_H_
#define VIDEO_DMA_UP_VIRTUAL_UART_H_
#include "video_dma_up_encapsulator.h"
#include "virtual_uart_register_file.h"
class video_dma_up_virtual_uart: public virtual_uart_register_file, public vdma::video_dma_up_encapsulator {
protected:
int enable_phy_register_tunneling;
public:
video_dma_up_virtual_uart(unsigned long the_base_address, std::string the_name = "undefined");
virtual unsigned long long read_control_reg(unsigned long address, unsigned long secondary_uart_address = 0, int* errorptr = NULL);
virtual void write_control_reg(unsigned long address, unsigned long long data, unsigned long secondary_uart_address = 0, int* errorptr = NULL);
};
#endif /* TSE_MAC_DEVICE_DRIVER_VIRTUAL_UART_H_ */
|
d9b2e06f3e7fac660dc290c456485635959eb2eb | 663f25816bac61647fd0ba9e4f55fe4eb6a9b292 | /source/code/programs/examples/glut/addfog/teapots.cpp | 81039f2f2f73a1c1258e77dc0a496758703af48d | [
"MIT"
] | permissive | luxe/unilang | a318e327cc642fabdcd08f3238aac47e4e65929f | 832f4bb1dc078e1f5ab5838b8e0c4bb98ba0e022 | refs/heads/main | 2023-07-25T06:32:18.993934 | 2023-07-13T02:22:06 | 2023-07-13T02:22:06 | 40,274,795 | 42 | 8 | MIT | 2023-07-19T10:36:56 | 2015-08-06T00:02:56 | Fancy | UTF-8 | C++ | false | false | 6,255 | cpp | teapots.cpp |
/* Copyright (c) Mark J. Kilgard, 1997. */
/**
* (c) Copyright 1993, Silicon Graphics, Inc.
* ALL RIGHTS RESERVED
* Permission to use, copy, modify, and distribute this software for
* any purpose and without fee is hereby granted, provided that the above
* copyright notice appear in all copies and that both the copyright notice
* and this permission notice appear in supporting documentation, and that
* the name of Silicon Graphics, Inc. not be used in advertising
* or publicity pertaining to distribution of the software without specific,
* written prior permission.
*
* THE MATERIAL EMBODIED ON THIS SOFTWARE IS PROVIDED TO YOU "AS-IS"
* AND WITHOUT WARRANTY OF ANY KIND, EXPRESS, IMPLIED OR OTHERWISE,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY OR
* FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL SILICON
* GRAPHICS, INC. BE LIABLE TO YOU OR ANYONE ELSE FOR ANY DIRECT,
* SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY
* KIND, OR ANY DAMAGES WHATSOEVER, INCLUDING WITHOUT LIMITATION,
* LOSS OF PROFIT, LOSS OF USE, SAVINGS OR REVENUE, OR THE CLAIMS OF
* THIRD PARTIES, WHETHER OR NOT SILICON GRAPHICS, INC. HAS BEEN
* ADVISED OF THE POSSIBILITY OF SUCH LOSS, HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE
* POSSESSION, USE OR PERFORMANCE OF THIS SOFTWARE.
*
* US Government Users Restricted Rights
* Use, duplication, or disclosure by the Government is subject to
* restrictions set forth in FAR 52.227.19(c)(2) or subparagraph
* (c)(1)(ii) of the Rights in Technical Data and Computer Software
* clause at DFARS 252.227-7013 and/or in similar or successor
* clauses in the FAR or the DOD or NASA FAR Supplement.
* Unpublished-- rights reserved under the copyright laws of the
* United States. Contractor/manufacturer is Silicon Graphics,
* Inc., 2011 N. Shoreline Blvd., Mountain View, CA 94039-7311.
*
* OpenGL(TM) is a trademark of Silicon Graphics, Inc.
*/
/**
* fog.c
* This program draws 5 red teapots, each at a different
* z distance from the eye, in different types of fog.
* Pressing the left mouse button chooses between 3 types of
* fog: exponential, exponential squared, and linear.
* In this program, there is a fixed density value, as well
* as fixed start and end values for the linear fog.
*/
#include <stdlib.h>
#include <math.h>
#include <GL/glut.h>
#include "addfog.hpp"
GLint fogMode;
#define TPF_LINEAR 1
#define TPF_EXP 2
#define TPF_EXP2 3
int addfog = 0;
void
selectFog(int mode)
{
switch (mode) {
case GL_LINEAR:
glFogf(GL_FOG_START, 1.0);
glFogf(GL_FOG_END, 5.0);
/* falls through */
case GL_EXP2:
case GL_EXP:
glFogi(GL_FOG_MODE, mode);
glEnable(GL_FOG);
addfog = 0;
glutPostRedisplay();
break;
case TPF_LINEAR:
afFogStartEnd(0.0, 10.0);
afFogMode(GL_LINEAR);
glDisable(GL_FOG);
addfog = 1;
glutPostRedisplay();
break;
case TPF_EXP:
afFogMode(GL_EXP);
glDisable(GL_FOG);
addfog = 1;
glutPostRedisplay();
break;
case TPF_EXP2:
afFogMode(GL_EXP2);
glDisable(GL_FOG);
addfog = 1;
glutPostRedisplay();
break;
case 0:
exit(0);
}
}
/* Initialize z-buffer, projection matrix, light source, * and lighting
model. Do not specify a material property here. */
void
myinit(void)
{
GLfloat position[] =
{0.0, 3.0, 3.0, 0.0};
GLfloat local_view[] =
{0.0};
GLfloat fogColor[4] =
{0.5, 0.5, 0.5, 1.0};
glEnable(GL_DEPTH_TEST);
glEnable(GL_FOG);
glDepthFunc(GL_LESS);
glLightfv(GL_LIGHT0, GL_POSITION, position);
glLightModelfv(GL_LIGHT_MODEL_LOCAL_VIEWER, local_view);
glFrontFace(GL_CW);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glEnable(GL_AUTO_NORMAL);
glEnable(GL_NORMALIZE);
fogMode = GL_EXP;
glFogi(GL_FOG_MODE, fogMode);
glFogfv(GL_FOG_COLOR, fogColor);
afFogColor(0.5, 0.5, 0.5);
glFogf(GL_FOG_DENSITY, 0.35);
afFogDensity(0.35);
glHint(GL_FOG_HINT, GL_DONT_CARE);
glClearColor(0.5, 0.5, 0.5, 1.0);
}
void
renderRedTeapot(GLfloat x, GLfloat y, GLfloat z)
{
float mat[4];
glPushMatrix();
glTranslatef(x, y, z);
mat[0] = 0.1745;
mat[1] = 0.01175;
mat[2] = 0.01175;
mat[3] = 1.0;
glMaterialfv(GL_FRONT, GL_AMBIENT, mat);
mat[0] = 0.61424;
mat[1] = 0.04136;
mat[2] = 0.04136;
glMaterialfv(GL_FRONT, GL_DIFFUSE, mat);
mat[0] = 0.727811;
mat[1] = 0.626959;
mat[2] = 0.626959;
glMaterialfv(GL_FRONT, GL_SPECULAR, mat);
glMaterialf(GL_FRONT, GL_SHININESS, 0.6 * 128.0);
glutSolidTeapot(1.0);
glPopMatrix();
}
int width, height;
/* display() draws 5 teapots at different z positions. */
void
display(void)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
renderRedTeapot(-4.0, -0.5, -1.0);
renderRedTeapot(-2.0, -0.5, -2.0);
renderRedTeapot(0.0, -0.5, -3.0);
renderRedTeapot(2.0, -0.5, -4.0);
renderRedTeapot(4.0, -0.5, -5.0);
if (addfog) {
afDoFinalFogPass(0, 0, width, height);
}
glFlush();
}
void
myReshape(int w, int h)
{
width = w;
height = h;
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
if (w <= (h * 3))
glOrtho(-6.0, 6.0, -2.0 * ((GLfloat) h * 3) / (GLfloat) w,
2.0 * ((GLfloat) h * 3) / (GLfloat) w, 0.0, 10.0);
else
glOrtho(-6.0 * (GLfloat) w / ((GLfloat) h * 3),
6.0 * (GLfloat) w / ((GLfloat) h * 3), -2.0, 2.0, 0.0, 10.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
afEyeNearFar(0.0, 10.0);
}
int
main(int argc, char **argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(450, 150);
glutCreateWindow("fogged teapots via post-rendering pass");
myinit();
glutReshapeFunc(myReshape);
glutDisplayFunc(display);
glutCreateMenu(selectFog);
glutAddMenuEntry("Fog EXP", GL_EXP);
glutAddMenuEntry("Fog EXP2", GL_EXP2);
glutAddMenuEntry("Fog LINEAR", GL_LINEAR);
glutAddMenuEntry("Two Pass Fog EXP", TPF_EXP);
glutAddMenuEntry("Two Pass Fog EXP2", TPF_EXP2);
glutAddMenuEntry("Two Pass Fog LINEAR", TPF_LINEAR);
glutAddMenuEntry("Quit", 0);
glutAttachMenu(GLUT_RIGHT_BUTTON);
glutMainLoop();
return 0; /* ANSI C requires main to return int. */
}
|
65b5dfe5b4a31dbedf60923519ba8888c7ee9eb6 | abe170e4959e41a1db67c110ed9842e29466897b | /src/socserver.cpp | a2de9c7d2aee59240664df473d2bef3321a868ac | [
"MIT"
] | permissive | palsbo/ESP_Servers | b7fb5fb0f8f68c858f1a3460e3bc21a8e67f6fea | 34bc5aef6eb85222c554356b0d20a0af51d2ea14 | refs/heads/master | 2020-03-16T14:54:37.843912 | 2018-05-12T09:18:24 | 2018-05-12T09:18:24 | 132,717,074 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,338 | cpp | socserver.cpp |
#ifdef ESP8266
#include <ESP8266WiFi.h>
#else
#include <WiFi.h>
#endif
#include <ArduinoJson.h>
#include <WebSocketsServer.h>
#include "socserver.h"
WebSocketsServer * sserver;
void WSSONS::add(String id, streamtype func) {
for (int i = 0; i < count; i++) {
if (ons[i].id == id) {
ons[i].func = func;
return;
}
}
if (count >= MAXONS) return;
ons[count].id = id;
ons[count].func = func;
count++;
}
void WSSONS::lookup (String id, uint8_t num, char * data) {
for (int i = 0; i < count; i++) {
if (id == ons[i].id) {
ons[i].func(num, data);
return;
}
}
}
WSSONS wssons;
static void ondata(uint8_t num, char * data) {
StaticJsonBuffer<200> jsonBuffer;
JsonObject& root = jsonBuffer.parseObject(data);
for (auto field : root) {
String value = root[field.key];
wssons.lookup(field.key, num, (char*)value.c_str());
}
};
void decode(char * json) { }
void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t length) {
String data = String((char*)payload);
char s1[length + 1];
strncpy_P(s1, (char*)payload, length);
s1[length] = 0;
switch (type) {
case WStype_DISCONNECTED:
wssons.lookup("disconnect", num, &s1[0]);
break;
case WStype_CONNECTED: {
Serial.println("Connecting");
wssons.lookup("connect", num, &s1[0]);
}
break;
case WStype_TEXT:
if (data == "__ping__") {
sserver->sendTXT(num, "__pong__");
} else {
wssons.lookup("data", num, &s1[0]);
}
break;
case WStype_BIN:
break;
default:
#ifdef DEBUG
Serial.printf("Invalid WStype [%d]\r\n", type);
#endif
break;
}
}
SOCSERVER::SOCSERVER(uint8_t port) {
sserver = new WebSocketsServer(port);
on("connect", [](uint8_t num, char * data) { });
on("disconnect", [](uint8_t num, char * data) { });
on("data", ondata);
}
IPAddress SOCSERVER::ip(uint8_t num) {
return sserver->remoteIP(num);
}
void SOCSERVER::begin() {
sserver->begin();
sserver->onEvent(webSocketEvent);
};
void SOCSERVER::on(char * id, streamtype func) {
wssons.add(id, func);
}
void SOCSERVER::broadcast(String data) {
sserver->broadcastTXT(data);
}
void SOCSERVER::send(uint8_t num, String data) {
sserver->sendTXT(num, data);
}
void SOCSERVER::loop() {
sserver->loop();
}
|
3d1de38e942456e372ba6b997eb4e2a3cd373599 | db4adde3aa38548f867fbb836f0e36aee7487479 | /decryptn.cpp | 36552480bf63ff071d4a995baecc62b9f755fe59 | [] | no_license | mengci/EC-ElGamal | 30db64f028970680204d40adbba9bdc7121d55d1 | b56a5daa160db519d298cbee4407c0bbc1fa5afb | refs/heads/master | 2021-01-10T20:50:53.293145 | 2013-12-18T05:38:26 | 2013-12-18T05:38:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,486 | cpp | decryptn.cpp | #include <gmpxx.h>
#include <iostream>
#include <gmp.h>
#include <fstream>
#include <string>
#include <sstream>
#include "ecurve.hpp"
#include "point.hpp"
using namespace std;
void decrypt(string keyPrv,string ciphertext, string plaintext) {
//get out private key parameters
ifstream keyFile(keyPrv.c_str());
if (!keyFile.is_open()) {
cout<<"***********Open key Failure*********"<<endl;
return;
}
string buffer;
string token;
mpz_class para[11];
int i=0;
//read the key parameters into array para[]
while (!keyFile.eof()) {
getline(keyFile,buffer);
stringstream iss;
iss<<buffer;
while (getline(iss, token,' ')) {
para[i].set_str(token,10);
i++;
}
}
keyFile.close();
ECurve ecurve(para[0],para[1],para[2],para[3],para[4],para[5]);
mpz_class p = ecurve.getP();
mpz_class n = ecurve.getN();
mpz_class a = ecurve.getA();
mpz_class b = ecurve.getB();
mpz_class gx = ecurve.getGx();
mpz_class gy = ecurve.getGy();
Point alpha(para[6],para[7]);
Point beta(para[8],para[9]);
mpz_class secreta = para[10];
// open file dat.ct & file dat_decrypted.pt
ofstream ptFile(plaintext.c_str());
if (!ptFile.is_open()) {
cout<<"***********Open pt Failure*********"<<endl;
return;
}
ifstream ctFile(ciphertext.c_str());
if (!ctFile.is_open()) {
cout<<"***********Open ct Failure*********"<<endl;
return;
}
mpz_class message;
Point Y1;
Point gama;
mpz_class gamaxInv;
mpz_class Y1_x;
mpz_class Y1_y;
mpz_class Y2;
// decrypt ciphertexts
while (!ctFile.eof()) {
getline(ctFile,buffer);
if (!ctFile.eof()) {
stringstream iss;
iss<<buffer;
//get Y1 & Y2
getline(iss, token,' ');
Y1_x.set_str(token,10);
getline(iss, token,' ');
Y1_y.set_str(token,10);
getline(iss, token,' ');
Y2.set_str(token,10);
Y1 = Point(Y1_x,Y1_y);
//write decrypted message into dat-num-decrypted.pt
gama.times(secreta,Y1,ecurve);
gamaxInv = ecurve.modinv(gama.getX());
message = ecurve.mod(Y2*gamaxInv);
ptFile<<message<<endl;
}
}
ptFile.close();
ctFile.close();
}
int main(int argc, char* argv[]) {
if (argc == 4) {
decrypt(argv[1],argv[2],argv[3]);
}
else {
cout<<"*******************Wrong Number of Arguments!********************\n"<<endl;
}
}
|
bcb19f5c61dc3cb1e9b66bf3d794bdf78143070e | 1d9e9d4f416607453e7c91c9dc45205bd7cb9e14 | /iqc5/instrument/BNProSpec_Parser/myProject.cpp | c4a28bb5e6d199b8a6ba743ceb6b222548a6eda9 | [] | no_license | allan1234569/iqc5 | 5542f2efe3e6eae0a59110ec2863d9beeef8c1cf | 8a026564db0128005f90d3f7ca56787a7bcbbad3 | refs/heads/master | 2020-03-29T09:17:13.715443 | 2018-09-21T10:56:01 | 2018-09-21T10:56:01 | 149,750,494 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 312 | cpp | myProject.cpp | #include "myProject.h"
MyProject::MyProject()
{
subProjectCount = 0;
}
void MyProject::clear()
{
sampleId.clear();
testTypeCode.clear();
testType.clear();
subProjectCount = 0;
}
bool MyProject::isEmpty()
{
return sampleId.isEmpty() && testTypeCode.isEmpty() && subProjectCount == 0;
}
|
02965e73d17c963e0466435459994bb3c266f032 | d09945668f19bb4bc17087c0cb8ccbab2b2dd688 | /2012-2016/2012/autumn/g.cpp | 60b4233b687d40bc45073de5fb63220ca1468db5 | [] | no_license | kmjp/procon | 27270f605f3ae5d80fbdb28708318a6557273a57 | 8083028ece4be1460150aa3f0e69bdb57e510b53 | refs/heads/master | 2023-09-04T11:01:09.452170 | 2023-09-03T15:25:21 | 2023-09-03T15:25:21 | 30,825,508 | 23 | 2 | null | 2023-08-18T14:02:07 | 2015-02-15T11:25:23 | C++ | UTF-8 | C++ | false | false | 4,048 | cpp | g.cpp | #include <cstdlib>
#include <cstring>
#include <memory>
#include <cstdio>
#include <fstream>
#include <iostream>
#include <cmath>
#include <string>
#include <sstream>
#include <stack>
#include <queue>
#include <vector>
#include <set>
#include <map>
#include <algorithm>
using namespace std;
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/time.h>
#define DEBUG
#ifdef DEBUG
#define DBG(...) cerr << #__VA_ARGS__ << ": " << __VA_ARGS__ << endl
#define DV(...) cerr << __VA_ARGS__ << endl
#define _D(fmt, ...) printf("%10s %3d : " fmt,__FUNCTION__,__LINE__,__VA_ARGS__)
#define _DE(fmt, ...) fprintf(stderr, "%10s %3d : " fmt,__FUNCTION__,__LINE__,__VA_ARGS__)
#else
#define DBG(...)
#define DV(...)
#define _D(fmt, ...)
#define _DE(fmt, ...)
#endif
typedef signed long long ll;
typedef unsigned long long ull;
#define _PE(...) { printf(__VA_ARGS__); fprintf(stderr, __VA_ARGS__); }
#define _E(...) fprintf(stderr, __VA_ARGS__)
#undef _P
#define _P(...) printf(__VA_ARGS__)
#define FOR(x,to) for(x=0;x<to;x++)
#define FOR2(x,from,to) for(x=from;x<to;x++)
#define ZERO(a) memset(a,0,sizeof(a))
void _fill_int(int* p,int val,int rep) {int i; FOR(i,rep) p[i]=val;}
#define FILL_INT(a,val) _fill_int((int*)a,val,sizeof(a)/4)
#define ZERO2(a,b) memset(a,0,b)
#define MINUS(a) _fill_int((int*)a,-1,sizeof(a)/4)
#define GETs(x) scanf("%s",x);
ll GETi() { ll i;scanf("%lld",&i); return i;}
#define GET1(x) scanf("%d",x);
#define GET2(x,y) scanf("%d%d",x,y);
#define GET3(x,y,z) scanf("%d%d%d",x,y,z);
#define EPS (1e-11)
template <class T> T sqr(T val){ return val*val;}
//-------------------------------------------------------
int N;
int func[26][2];
char str[2000];
int dofunc(char funcname, int cv,int loop) {
int v,nv,id,nl;
nl=loop;
if(nl>2) nl=nl%2+2;
v=cv;id=funcname-'a';
while(nl--) {
v = (func[id][0] & (~v)) |(func[id][1] & (v));
}
//_P("%c %d->%d(%d)\n",funcname,cv,v,loop);
return v;
}
pair<int,char*> val(char* pc, int cv) {
pair<int,char*> p;
char fn;
int v,loop,lh,rh;
//_P("%s\n",pc);
if(*pc=='x') return make_pair(cv,pc+1);
if(*pc>='0' && *pc<='9') {
v=0;
while(*pc>='0' && *pc<='9') {
v=v*10+(*pc-'0');
pc++;
}
return make_pair(v,pc);
}
if(*pc>='a' && *pc<='j') {
fn=*pc;
pc++;
loop=1;
if(*pc=='^') {
pc++;
loop=0;
while(*pc>='0' && *pc<='9') {
loop=loop*10+(*pc-'0');
pc++;
}
}
pc++; // (
p = val(pc,cv);
pc=p.second+1; // )
return make_pair(dofunc(fn,p.first,loop),pc);
}
if(*pc=='('){
p = val(pc+1,cv);
lh=p.first;
pc=p.second;
fn=*pc;
p = val(pc+1,cv);
rh=p.first;
if(*pc=='|') return make_pair(lh|rh,p.second+1);
if(*pc=='^') return make_pair(lh^rh,p.second+1);
if(*pc=='&') return make_pair(lh&rh,p.second+1);
_P("error op %s\n",pc);
}
_P("error %s\n",pc);
return make_pair(0,pc);
}
void parse() {
char* pc;
pair<int,char*> vv;
char fn = str[0]-'a';
int i,v[2][2];
pc=str+5;
vv=val(pc,0);
func[fn][0]=vv.first;
vv=val(pc,0x7FFFFFFF);
func[fn][1]=vv.first;
//_P("%c %d %d\n",str[0],func[fn][0],func[fn][1]);
_P("%c(x)=",str[0]);
ZERO(v);
FOR(i,31) {
if((func[fn][0] & (1<<i)) && (func[fn][1] & (1<<i))) v[1][1]|=1<<i;
if(((func[fn][0] & (1<<i))==0) && (func[fn][1] & (1<<i))) v[0][1]|=1<<i;
if((func[fn][0] & (1<<i)) && ((func[fn][1] & (1<<i))==0)) v[1][0]|=1<<i;
}
_P("(%d|((x&%d)^%d))\n",v[1][1],v[0][1]|v[1][0],v[1][0]);
}
void solve() {
int x,y,i,j,p,rr,TM,TTC;
N=GETi();
FOR(i,N) {
GETs(str);
parse();
}
return;
}
int main(int argc,char** argv){
long long span;
struct timeval start,end,ts;
if(argc>1) {
freopen(argv[1], "r", stdin);
}
gettimeofday(&start,NULL);
solve();
gettimeofday(&end,NULL);
span = (end.tv_sec - start.tv_sec)*1000000LL + (end.tv_usec - start.tv_usec);
//_E("**Total time: %lld ms\n",span/1000);
return 0;
}
|
47d145e2b359c7500b2d911bbc1e2e5a15fbf0d4 | 8f021f68cd0949afa8d119582c0b419b014919d8 | /Treinos16/3-Estruturas/Exemplos/struct.cpp | c98551a92529f8396ecf5b6c1e93a2b6a52d20f1 | [] | no_license | Jonatankk/codigos | b9c8426c2f33b5142460a84337480b147169b3e6 | 233ae668bdf6cdd12dbc9ef243fb4ccdab49c933 | refs/heads/master | 2022-07-22T11:09:27.271029 | 2020-05-09T20:57:42 | 2020-05-09T20:57:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 348 | cpp | struct.cpp | #include<stdio.h>
struct carro{
//char placa[8];
char nome[50];
int ano;
};
int main(void){
carro c;
//while(scanf("%s %d", c.nome, c.placa) != EOF){
while(fgets(c.nome, 50, stdin) != NULL){
scanf("%d", &c.ano);
getchar();
printf("Carro: %s", c.nome);
//printf("Placa: %s\n", c.placa);
printf("Ano: %d\n", c.ano);
}
return 0;
}
|
5b378d54b6aa59dfe065155eb382be719d4eb674 | f3bf9876c94a4295acb6d1d2bb014b790e99cad3 | /AWiFi_Tone/AWiFi_Tone.ino | 34cc5870aa818582e8a41233ce78d836ce3c5d5b | [] | no_license | godsnew2542/IOT | 4addbf6ee34bd1cb583e094dec14574c657dd292 | 2a096cd30a2c40605ecc7284284917f92c4d8657 | refs/heads/master | 2023-03-01T15:12:06.652085 | 2021-02-01T01:51:59 | 2021-02-01T01:51:59 | 295,615,424 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 396 | ino | AWiFi_Tone.ino | int pinTone = D8;
#define sw1 D0
bool sw1_state = false;
void setup()
{
pinMode(sw1, INPUT);
// analogWrite(pinTone, 255);
delay(1000);
}
void loop()
{
sw1_state = not(digitalRead(sw1));
if (sw1_state) {
analogWrite(pinTone, 255);
analogWriteFreq(600);
delay(500);
analogWriteFreq(587);
delay(200);
} else {
noTone(pinTone);
}
}
|
4ad94644e56cf3d1477c24c71e2a5defd684d445 | 4a70cc8466926407305e218a12ef5e75111e5174 | /libraries/AP_Compass/AP_Compass_QMC5883L.h | 788e0b1142e655d37da947f12f3411ac06eab1bd | [] | no_license | wanglong1107/SAGAPRO_GPS | 3069dedd402e6059d80714b273da7da152c8113c | f74aa4542756420fce54741a140d4bba02887fe1 | refs/heads/master | 2022-08-01T09:45:34.834230 | 2020-05-24T08:43:54 | 2020-05-24T08:43:54 | 266,495,494 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,793 | h | AP_Compass_QMC5883L.h | /*
* Copyright (C) 2016 Emlid Ltd. All rights reserved.
*
* This file is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This file is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <AP_Common/AP_Common.h>
#include <AP_HAL/AP_HAL.h>
#include <AP_HAL/I2CDevice.h>
#include <AP_Math/AP_Math.h>
#include "AP_Compass.h"
#include "AP_Compass_Backend.h"
#ifndef HAL_COMPASS_QMC5883L_I2C_ADDR
#define HAL_COMPASS_QMC5883L_I2C_ADDR 0x0D
#endif
class AP_Compass_QMC5883L : public AP_Compass_Backend
{
public:
static AP_Compass_Backend *probe(Compass &compass,
AP_HAL::I2CDevice *dev,
bool force_external,
enum Rotation rotation = ROTATION_NONE);
void read() override;
static constexpr const char *name = "QMC5883L";
private:
AP_Compass_QMC5883L(Compass &compass,
AP_HAL::Device *dev,
bool force_external,
enum Rotation rotation);
void _dump_registers();
bool _check_whoami();
void timer();
bool init();
AP_HAL::Device *_dev;
Vector3f _accum = Vector3f();
uint32_t _accum_count = 0;
enum Rotation _rotation;
uint8_t _instance;
bool _force_external:1;
};
|
f42aaeca3bdf7896754e4082a748779366c913bf | 9efd18379fcbba31ffca434d5dfbeedcc110075f | /src/~rvizg_main.cpp | c2911b7228a32e1658b236aa56d7ea2b604e8c82 | [] | no_license | myalfred03/rvizglabre | 22961a18fb561125de61a7db2ee2a7d5df4bd02a | dcb1c0ebac0a65f0475c43a30bd45146678fc92a | refs/heads/master | 2023-06-19T12:23:13.694543 | 2021-07-08T00:21:45 | 2021-07-08T00:21:45 | 106,970,457 | 1 | 2 | null | 2019-01-12T23:00:32 | 2017-10-14T23:35:03 | C++ | UTF-8 | C++ | false | false | 1,263 | cpp | ~rvizg_main.cpp | #include "rvizg_main.h"
#include <QSlider>
#include <QLabel>
#include <QGridLayout>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QDebug>
#include <QVariant>
#include <QPushButton>
#include <QStatusBar>
#include <QMdiArea>
rvizMain::rvizMain(QWidget* parent)
:QWidget(parent)
{
QVBoxLayout* main_layout = new QVBoxLayout(parent);
status_label_ = new QLabel("12");
status_label_->setMinimumHeight(4);
status_label_->setMinimumWidth(4);
status_label_->setMaximumHeight(18);
status_label_->setMaximumWidth(600);
status_label_->setContentsMargins(0,0,0,0);
status_label_->setAlignment(Qt::AlignRight);
// QMdiArea* showrviz = new QMdiArea();
ToolManager = new MyViz(/*showrviz*/);
// showrviz->addSubWindow(ToolManager, Qt::FramelessWindowHint);
connect (ToolManager, SIGNAL (statusUpdate(const QString&)), status_label_, SLOT( setText( const QString&)));
main_layout->addWidget(ToolManager);
main_layout->addWidget(status_label_);
// ToolManager->showMaximized();
setLayout( main_layout );
QObject::connect(this, SIGNAL(statusTool(int )),ToolManager, SLOT(setTool(int )));
}
rvizMain::~rvizMain()
{
delete ToolManager;
}
void rvizMain::setTool(int tool)
{
Q_EMIT statusTool(tool);
}
|
ff40704a57d21065be77828f69891f2c714e09e4 | 4b56fd6a601a60109b30d212ad678f43558e84c6 | /this指针/this指针.cpp | 0086d88281fa7daa9b9614e5dc0676ecbc1ee541 | [] | no_license | Pornhub-passion-video/Solution2 | 9d4984f904801c40cbab5f3cb91a6970be71e8c0 | 80e775e08ca9a22dd338a5d32808a30e72bce686 | refs/heads/master | 2021-01-09T14:03:37.498847 | 2020-02-22T11:26:55 | 2020-02-22T11:26:55 | 242,329,746 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 615 | cpp | this指针.cpp | #include<iostream>
using namespace std;
class Person
{
public:
Person(int m_age)
{
this->m_age = m_age;//this 指针永远指向当前对象
}
void getm_age()
{
cout << "wodenianling "<<m_age << endl;
}
Person & add_Age(Person &p)
{
this->m_age += p.m_age;//this 指针的永远指向当前调用函数的对象
//cout <<" 年龄相加"<<this->m_age << endl;
return *this;
}
private:
int m_age;
};
void test01()
{
Person p1(10);
p1.getm_age();
}
void test02()
{
Person p2(10);
Person p3(10);
p2.add_Age(p3).add_Age(p3);
p2.getm_age();
}
int main()
{
//test01();
test02();
} |
8731fb135561b74eef0a8d1525cb99e33718817c | a33b7e5815f6ac385ca9c455754e0c0b6efd0829 | /code_其他班级/20200410/if.cpp | e9f97db0f26ec8fcaec02dde71934495a3031fa7 | [] | no_license | yangdongzju1976/c_language | aa557f2e99e1adc93cb9c8181110516a55ea3fa0 | 3037097d66d23ac41a3de62e026cbce939b0ecc4 | refs/heads/master | 2023-02-22T08:08:25.074619 | 2021-01-31T09:39:20 | 2021-01-31T09:39:20 | 334,620,019 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 431 | cpp | if.cpp | #include <stdio.h>
int main ()
{
/* 局部变量定义 */
int a;
printf("\n输入a=");
scanf("%d",&a);
/* 检查布尔条件 */
if( a < 20 )
{
/* 如果条件为真,则输出下面的语句 */
printf("a 小于 20\n" );
}
else
{
/* 如果条件为假,则输出下面的语句 */
printf("a 大于 20\n" );
}
printf("a 的值是 %d\n", a);
return 0;
}
|
7988633f533a754b692e795b76e2dcc059347777 | 3f80cbc9a7f625eec50df39dbebcb4bb0f86b56f | /Src/Rozdzial04/SphereWorld/SphereWorld.cpp | 28581c1575c7dea3f6893f03ce3b7b2c37737f5b | [] | no_license | SharpShooter17/OpenGLBook | 0d2b5d6464033277cf63bb46a098629d17719763 | 4a274ec1056716a008423789b3324e396895cc3b | refs/heads/master | 2021-08-08T06:09:20.113037 | 2017-11-09T18:00:38 | 2017-11-09T18:00:38 | 110,148,835 | 0 | 0 | null | null | null | null | WINDOWS-1250 | C++ | false | false | 3,999 | cpp | SphereWorld.cpp | // SphereWorld.cpp
// OpenGL. Księga eksperta
// Nowy i poprawiony program SphereWorld
// Autor programu: Richard S. Wright Jr.
#include <GLTools.h>
#include <GLShaderManager.h>
#include <GLFrustum.h>
#include <GLBatch.h>
#include <GLMatrixStack.h>
#include <GLGeometryTransform.h>
#include <StopWatch.h>
#include <math.h>
#include <stdio.h>
#ifdef __APPLE__
#include <glut/glut.h>
#else
#define FREEGLUT_STATIC
#include <GL/glut.h>
#endif
GLShaderManager shaderManager; // Menedżer shaderów
GLMatrixStack modelViewMatrix; // Macierz model-widok
GLMatrixStack projectionMatrix; // Macierz rzutowania
GLFrustum viewFrustum; // Frusta widoku
GLGeometryTransform transformPipeline; // Potok przekształcania geometrii
GLTriangleBatch torusBatch;
GLBatch floorBatch;
//////////////////////////////////////////////////////////////////
// Ta funkcja wykonuje wszystkie działania związane z inicjalizowaniem w kontekście renderowania.
void SetupRC()
{
// Inicjalizacja menedżera shaderów
shaderManager.InitializeStockShaders();
glEnable(GL_DEPTH_TEST);
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
// Tworzenie torusa
gltMakeTorus(torusBatch, 0.4f, 0.15f, 30, 30);
floorBatch.Begin(GL_LINES, 324);
for(GLfloat x = -20.0; x <= 20.0f; x+= 0.5) {
floorBatch.Vertex3f(x, -0.55f, 20.0f);
floorBatch.Vertex3f(x, -0.55f, -20.0f);
floorBatch.Vertex3f(20.0f, -0.55f, x);
floorBatch.Vertex3f(-20.0f, -0.55f, x);
}
floorBatch.End();
}
///////////////////////////////////////////////////
// Zmienił się rozmiar okna lub okno zostało właśnie zainicjalizowane.
void ChangeSize(int nWidth, int nHeight)
{
glViewport(0, 0, nWidth, nHeight);
// Tworzenie macierzy rzutowania i wstawienie jej na stos macierzy rzutowania.
viewFrustum.SetPerspective(35.0f, float(nWidth)/float(nHeight), 1.0f, 100.0f);
projectionMatrix.LoadMatrix(viewFrustum.GetProjectionMatrix());
// Ustawienie dwóch stosów macierzy w potoku przekształcania.
transformPipeline.SetMatrixStacks(modelViewMatrix, projectionMatrix);
}
// Rysowanie sceny
void RenderScene(void)
{
// Wartości kolorów
static GLfloat vFloorColor[] = { 0.0f, 1.0f, 0.0f, 1.0f};
static GLfloat vTorusColor[] = { 1.0f, 0.0f, 0.0f, 1.0f };
// Animacja czasowa
static CStopWatch rotTimer;
float yRot = rotTimer.GetElapsedSeconds() * 60.0f;
// Czyszczenie bufora kolorów i głębi
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Zapisanie bieżącej macierzy model-widok (macierz jednostkowa)
modelViewMatrix.PushMatrix();
// Rysowanie tła
shaderManager.UseStockShader(GLT_SHADER_FLAT,
transformPipeline.GetModelViewProjectionMatrix(),
vFloorColor);
floorBatch.Draw();
// Rysowanie obracającego się torusa
modelViewMatrix.Translate(0.0f, 0.0f, -2.5f);
modelViewMatrix.Rotate(yRot, 0.0f, 1.0f, 0.0f);
shaderManager.UseStockShader(GLT_SHADER_FLAT, transformPipeline.GetModelViewProjectionMatrix(),
vTorusColor);
torusBatch.Draw();
// Przywrócenie poprzedniej macierzy model-widok (macierz jednostkowa)
modelViewMatrix.PopMatrix();
// Zamiana buforów
glutSwapBuffers();
// Ponowne wyświetlenie za pomocą funkcji z biblioteki GLUT
glutPostRedisplay();
}
int main(int argc, char* argv[])
{
gltSetWorkingDirectory(argv[0]);
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(800,600);
glutCreateWindow("SphereWorld OpenGL");
glutReshapeFunc(ChangeSize);
glutDisplayFunc(RenderScene);
GLenum err = glewInit();
if (GLEW_OK != err) {
fprintf(stderr, "Błąd GLEW: %s\n", glewGetErrorString(err));
return 1;
}
SetupRC();
glutMainLoop();
return 0;
}
|
ab725e27e404988b05c8a3bac45db655a6f1cba1 | 6dab0456d13f9f5b8b2e205002108cadbd0b4f5a | /Strategy/Strategy/Request.h | 98b1adfe5594201a7f9a42155defdd54d0d28a26 | [] | no_license | fredred375/Strategy_by_RDOGS | 77eede19c90272361bd6d6666f0c088de9ab195f | 57c01662d324b2588abb2782c2dbec74487fbaed | refs/heads/master | 2022-12-24T02:36:08.076545 | 2020-09-11T15:57:13 | 2020-09-11T15:57:13 | 281,888,945 | 2 | 1 | null | 2020-09-11T15:57:14 | 2020-07-23T07:58:34 | C++ | UTF-8 | C++ | false | false | 1,148 | h | Request.h | #pragma once
#include "PacketProperties.h"
#include "Player.h"
#include "Point.h"
class Player;
class Point;
class Communicator;
enum class RequestStatus
{
NA,
PENDING, // not yet sent
SENT, // sent (entered buffer)...
RESPONDED, // response received
TIMEOUT // timeout exceeded
};
class Request
{
friend Communicator;
protected:
// Properties
RequestStatus status;
sf::Clock clock;
sf::Time timeout;
PacketProperties sendProperties, receiveProperties;
// Components
sf::Packet sendPacket, receivePacket;
// Setter
//void setReturnPacket(sf::Packet);
public:
// Constructors/Destruector
Request();
Request(PacketProperties properties);
Request(PacketProperties properties, sf::Time timeout);
virtual ~Request();
// Update
virtual void update();
// Queries
RequestStatus getStatus() { return this->status; };
sf::Time getElapsedTime() { return this->clock.getElapsedTime(); };
sf::Packet getResponsePacket() { return this->receivePacket; };
};
sf::Packet& operator <<(sf::Packet& packet, const PacketProperties& t);
sf::Packet& operator >>(sf::Packet& packet, PacketProperties& t); |
54e26f0821cb1cce8cd4b077ee747964292fcc48 | 709dbd149a14efeeb9a9806e0292a92bf6fec1bc | /finufft_write_truesol.cpp | 4b572a62dc568d783286ee6c8bde6018589b61be | [] | no_license | MelodyShih/cuFINUFFT-bench | 02bce0c63c5fe9e51beae2ce0c8c8099084e3237 | be00924fe2a02c794b906b6721dc69f9de7bc34d | refs/heads/master | 2021-06-26T03:20:53.097526 | 2021-03-08T15:31:06 | 2021-03-08T15:31:06 | 212,201,625 | 7 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,201 | cpp | finufft_write_truesol.cpp | // this is all you must include for the finufftf lib...
#include <finufft.h>
#include "create_data.cpp"
#include "utils.h"
// also needed for this example...
#include <stdio.h>
#include <stdlib.h>
using namespace std;
int main(int argc, char *argv[]){
int ier;
int N1, N2, N3, M, N;
if (argc<4) {
fprintf(stderr,"Usage: finufftf [nupts_distr [dim [N1 N2 N3 [M [tol]]]]\n");
return 1;
}
double w;
int nupts_distr;
int dim;
sscanf(argv[1],"%d" ,&nupts_distr);
sscanf(argv[2],"%d" ,&dim);
sscanf(argv[3],"%lf",&w); N1 = (int)w; // so can read 1e6 right!
sscanf(argv[4],"%lf",&w); N2 = (int)w;
sscanf(argv[5],"%lf",&w); N3 = (int)w;
N = N1*N2*N3;
M = 8*N1*N2*N3;// let density always be 1
if(argc>6){
sscanf(argv[6],"%lf",&w); M = (int)w;
}
float tol=6e-8;// desired accuracy
printf("[info ] (N1,N2,N3)=(%d,%d,%d), M=%d, tol=%3.1e\n", N1,N2,N3,M,tol);
nufft_opts opts;
finufftf_default_opts(&opts);
if(N3 == 1){
opts.upsampfac = 2;// some timing results
}
float *x, *y, *z;
complex<float> *c, *F;
x = (float *)malloc(sizeof(float)*M);
if(dim>1)
y = (float *)malloc(sizeof(float)*M);
if(dim>2)
z = (float *)malloc(sizeof(float)*M);
c = (complex<float>*)malloc(sizeof(complex<float>)*M);
F = (complex<float>*)malloc(sizeof(complex<float>)*N);
create_data_type1(nupts_distr, dim, M, x, y, z, 1, 1, 1, c, M_PI, N1, N2, N3);
int64_t nmodes[3];
nmodes[0] = N1;
nmodes[1] = N2;
nmodes[2] = N3;
int type=1,ntrans=1;
float totaltime=0;
CNTime timer; timer.start();
finufftf_plan plan;
ier = finufftf_makeplan(type,dim,nmodes,+1,ntrans,tol,&plan,&opts);
finufftf_setpts(plan,M,x,y,z,0,NULL,NULL,NULL);
finufftf_execute(plan,c,F);
finufftf_destroy(plan);
write_sol(type, nupts_distr, dim, N1, N2, N3, M, c, F);
memset(c, 0, sizeof(complex<float>)*M);
type = 2;
int n[3];
n[0] = N1;
n[1] = N2;
n[2] = N3;
create_data_type2(nupts_distr, dim, M, x, y, z, 1, 1, 1, n, F, M_PI, N1, N2, N3);
ier = finufftf_makeplan(type,dim,nmodes,-1,ntrans,tol,&plan,&opts);
finufftf_setpts(plan,M,x,y,z,0,NULL,NULL,NULL);
finufftf_execute(plan,c,F);
finufftf_destroy(plan);
write_sol(type, nupts_distr, dim, N1, N2, N3, M, c, F);
return ier;
}
|
b2ccbe8f384628720d9791c3a5a9599ffdc269d1 | b1fb4f85cac5d9f7b944f2d78b68697523374948 | /MarioSDL/GameScreenManager.h | a798dd40072ad881a1682f30469c10a8c9551a1d | [] | no_license | Sadzony/MarioSDL | bbbfc03661f12a1d5639e84c98b53f1ec52c7ecb | 0a138fb2dd1a2b38d2c24818097418b70ee2ea8e | refs/heads/main | 2023-04-05T09:46:08.711933 | 2021-04-08T02:59:11 | 2021-04-08T02:59:11 | 332,512,473 | 0 | 0 | null | 2021-04-08T02:59:19 | 2021-01-24T17:34:55 | C | UTF-8 | C++ | false | false | 539 | h | GameScreenManager.h | #pragma once
#include <SDL.h>
#include <SDL_image.h>
#include <SDL_mixer.h>
#include <iostream>
#include "Commons.h"
#include "Texture2D.h"
#ifndef _GAMESCREENMANAGER_H
#define _GAMESCREENMANAGER_H
class GameScreen;
class GameScreenLevel1;
class GameScreenManager
{
private:
SDL_Renderer* m_renderer;
GameScreen* m_current_screen;
public:
GameScreenManager(SDL_Renderer* renderer, SCREENS startScreen);
~GameScreenManager();
void Render();
void Update(float deltaTime, SDL_Event e);
void ChangeScreen(SCREENS newScreen);
};
#endif
|
eb167da80d37960cb4432a79b01ed5ab1c0dad80 | 786de89be635eb21295070a6a3452f3a7fe6712c | /PSHist/tags/V00-02-00/include/HManager.h | 481f814c71d5f660f8406147534b18254c038c4e | [] | no_license | connectthefuture/psdmrepo | 85267cfe8d54564f99e17035efe931077c8f7a37 | f32870a987a7493e7bf0f0a5c1712a5a030ef199 | refs/heads/master | 2021-01-13T03:26:35.494026 | 2015-09-03T22:22:11 | 2015-09-03T22:22:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 25,563 | h | HManager.h | #ifndef PSHIST_HMANAGER_H
#define PSHIST_HMANAGER_H
//--------------------------------------------------------------------------
// File and Version Information:
// $Id$
//
// Description:
// Class HManager.
//
//------------------------------------------------------------------------
//-----------------
// C/C++ Headers --
//-----------------
#include <vector>
#include <string>
#include <boost/utility.hpp>
//----------------------
// Base Class Headers --
//----------------------
//-------------------------------
// Collaborating Class Headers --
//-------------------------------
#include "PSHist/Axis.h"
#include "PSHist/H1.h"
#include "PSHist/H2.h"
#include "PSHist/Profile.h"
#include "PSHist/Tuple.h"
//------------------------------------
// Collaborating Class Declarations --
//------------------------------------
// ---------------------
// -- Class Interface --
// ---------------------
namespace PSHist {
/**
* @defgroup PSHist PSHist package
*
* @brief Package defining interfaces for histogramming services.
*
* This package contains interfaces (abstract classes) for
* histogramming services used by psana framework.
*/
/**
* @ingroup PSHist
*
* @brief Interface for histogram/tuple manager class.
*
* HManager is an empty base class which holds information about ntuples/histograms.
* The main reason is to be able to create and hold new histograms or/and ntuples
* without knowing without knowing what the underlying system is. For example,
* it might be root, hbook, hyppo etc.
*
* Usage:
* @code
* #include "RootHist/RootHManager.h"
* #include "PSHist/HManager.h"
* #include "PSHist/Axis.h"
* #include "PSHist/H1.h"
* #include "PSHist/H2.h"
* #include "PSHist/Profile.h"
* #include "PSHist/Tuple.h"
* @endcode
*
* 1. Create a HManager with specific constructor (root for example):
*
* @code
* PSHist::HManager *hMan = new RootHist::RootHManager("my-output-file.root", "RECREATE");
* @endcode
*
* 2. Create histograms
*
* @code
* PSHist::H1 *pHis1f = hMan->hist1f("His1 float title",100,0.,1.);
* PSHist::H2 *pHis2d = hMan->hist2d("His2 double title",100,0.,1.,100,0.,1.);
* @endcode
*
* Create ntuples
*
* @code
* PSHist::Tuple *nt = hMan->ntuple("EXP Data");
* @endcode
*
* and define the ntuple parameters by names:
*
* @code
* nt->parameter("beamEnergy");
* nt->parameter("beamCurrent");
* @endcode
*
* or by pointers:
*
* @code
* PSHist::TupleParameter *p_beamEnergy = nt->parameter("beamEnergy");
* PSHist::TupleParameter *p_beamCurrent = nt->parameter("beamCurrent");
* @endcode
*
* 3. Fill histograms
*
* @code
* pHis1f->fill(x,[weight]); // once per event
* pHis2d->fill(x,y,[weight]);
* @endcode
*
* Fill ntuple by name:
*
* @code
* nt->fill("beamEnergy", E); // once per event
* nt->fill("beamCurrent", I);
* @endcode
*
* or by pointers:
*
* @code
* p_beamEnergy->fill(E); // once per event
* p_beamCurrent->fill(I);
*
* nt->addRow(); // once per event
* @endcode
*
*
* 4. Write the data into a file:
*
* @code
* hMan->write(); // at the end of job
* delete hMan;
* @endcode
*
* This software was developed for the LCLS project. If you use all or
* part of it, please give an appropriate acknowledgment.
*
* @see H1
* @see H2
* @see Profile
* @see Tuple
*
* @version $Id$
*
* @author Mikhail S. Dubrovin
*/
class HManager : boost::noncopyable {
public:
// Destructor
virtual ~HManager () {}
// 1-d histograms
/**
* @brief Create new 1-dimensional histogram and return pointer to it.
*
* This method creates new 1-dimensional histogram with same-width bins.
* Internal storage of the created histogram will consists of 32-bit
* integer per histogram bin.
* The name of the histogram must be unique, otherwise exception is thrown.
*
* <b>Returned pointer should never be deleted by client code.</b>
*
* @param[in] name Histogram name, unique string.
* @param[in] title Title of the histogram, arbitrary string.
* @param[in] nbins Number of bins.
* @param[in] xlow Low edge of the first bin.
* @param[in] xhigh High edge of the last bin.
* @return Pointer to a newly created histogram, do not delete.
*
* @throw ExceptionDuplicateName thrown if histogram or tuple with
* identical name exists already
*/
virtual H1* hist1i(const std::string& name, const std::string& title,
int nbins, double xlow, double xhigh) = 0;
/**
* @brief Create new 1-dimensional histogram and return pointer to it.
*
* This method creates new 1-dimensional histogram with same-width bins.
* Internal storage of the created histogram will consists of 32-bit
* floating number per histogram bin.
* The name of the histogram must be unique, otherwise exception is thrown.
*
* <b>Returned pointer should never be deleted by client code.</b>
*
* @param[in] name Histogram name, unique string.
* @param[in] title Title of the histogram, arbitrary string.
* @param[in] nbins Number of bins.
* @param[in] xlow Low edge of the first bin.
* @param[in] xhigh High edge of the last bin.
* @return Pointer to a newly created histogram, do not delete.
*
* @throw ExceptionDuplicateName thrown if histogram or tuple with
* identical name exists already
*/
virtual H1* hist1f(const std::string& name, const std::string& title,
int nbins, double xlow, double xhigh) = 0;
/**
* @brief Create new 1-dimensional histogram and return pointer to it.
*
* This method creates new 1-dimensional histogram with same-width bins.
* Internal storage of the created histogram will consists of 64-bit
* floating number per histogram bin.
* The name of the histogram must be unique, otherwise exception is thrown.
*
* <b>Returned pointer should never be deleted by client code.</b>
*
* @param[in] name Histogram name, unique string.
* @param[in] title Title of the histogram, arbitrary string.
* @param[in] nbins Number of bins.
* @param[in] xlow Low edge of the first bin.
* @param[in] xhigh High edge of the last bin.
* @return Pointer to a newly created histogram, do not delete.
*
* @throw ExceptionDuplicateName thrown if histogram or tuple with
* identical name exists already
*/
virtual H1* hist1d(const std::string& name, const std::string& title,
int nbins, double xlow, double xhigh) = 0;
/**
* @brief Create new 1-dimensional histogram and return pointer to it.
*
* This method creates new 1-dimensional histogram with variable-width bins.
* Internal storage of the created histogram will consists of 32-bit
* integer per histogram bin.
* The name of the histogram must be unique, otherwise exception is thrown.
*
* <b>Returned pointer should never be deleted by client code.</b>
*
* @param[in] name Histogram name, unique string.
* @param[in] title Title of the histogram, arbitrary string.
* @param[in] nbins Number of bins.
* @param[in] xbinedges Array of the histogram edges, size of the array
* is @c nbins+1, it should contain ordered values for
* low edges of all bins plus high edge of last bin.
* @return Pointer to a newly created histogram, do not delete.
*
* @throw ExceptionDuplicateName thrown if histogram or tuple with
* identical name exists already
*/
virtual H1* hist1i(const std::string& name, const std::string& title,
int nbins, const double *xbinedges) = 0;
/**
* @brief Create new 1-dimensional histogram and return pointer to it.
*
* This method creates new 1-dimensional histogram with variable-width bins.
* Internal storage of the created histogram will consists of 32-bit
* floating number per histogram bin.
* The name of the histogram must be unique, otherwise exception is thrown.
*
* <b>Returned pointer should never be deleted by client code.</b>
*
* @param[in] name Histogram name, unique string.
* @param[in] title Title of the histogram, arbitrary string.
* @param[in] nbins Number of bins.
* @param[in] xbinedges Array of the histogram edges, size of the array
* is @c nbins+1, it should contain ordered values for
* low edges of all bins plus high edge of last bin.
* @return Pointer to a newly created histogram, do not delete.
*
* @throw ExceptionDuplicateName thrown if histogram or tuple with
* identical name exists already
*/
virtual H1* hist1f(const std::string& name, const std::string& title,
int nbins, const double *xbinedges) = 0;
/**
* @brief Create new 1-dimensional histogram and return pointer to it.
*
* This method creates new 1-dimensional histogram with variable-width bins.
* Internal storage of the created histogram will consists of 64-bit
* floating number per histogram bin.
* The name of the histogram must be unique, otherwise exception is thrown.
*
* <b>Returned pointer should never be deleted by client code.</b>
*
* @param[in] name Histogram name, unique string.
* @param[in] title Title of the histogram, arbitrary string.
* @param[in] nbins Number of bins.
* @param[in] xbinedges Array of the histogram edges, size of the array
* is @c nbins+1, it should contain ordered values for
* low edges of all bins plus high edge of last bin.
* @return Pointer to a newly created histogram, do not delete.
*
* @throw ExceptionDuplicateName thrown if histogram or tuple with
* identical name exists already
*/
virtual H1* hist1d(const std::string& name, const std::string& title,
int nbins, const double *xbinedges) = 0;
/**
* @brief Create new 1-dimensional histogram and return pointer to it.
*
* This method creates new 1-dimensional histogram, number of bins and
* their edges are determined by separate object (Axis class).
* Internal storage of the created histogram will consists of 32-bit
* integer per histogram bin.
* The name of the histogram must be unique, otherwise exception is thrown.
*
* <b>Returned pointer should never be deleted by client code.</b>
*
* @param[in] name Histogram name, unique string.
* @param[in] title Title of the histogram, arbitrary string.
* @param[in] axis Axis definition.
* @return Pointer to a newly created histogram, do not delete.
*
* @throw ExceptionDuplicateName thrown if histogram or tuple with
* identical name exists already
*/
virtual H1* hist1i(const std::string& name, const std::string& title,
const PSHist::Axis& axis) = 0;
/**
* @brief Create new 1-dimensional histogram and return pointer to it.
*
* This method creates new 1-dimensional histogram, number of bins and
* their edges are determined by separate object (Axis class).
* Internal storage of the created histogram will consists of 32-bit
* floating number per histogram bin.
* The name of the histogram must be unique, otherwise exception is thrown.
*
* <b>Returned pointer should never be deleted by client code.</b>
*
* @param[in] name Histogram name, unique string.
* @param[in] title Title of the histogram, arbitrary string.
* @param[in] axis Axis definition.
* @return Pointer to a newly created histogram, do not delete.
*
* @throw ExceptionDuplicateName thrown if histogram or tuple with
* identical name exists already
*/
virtual H1* hist1f(const std::string& name, const std::string& title,
const PSHist::Axis& axis) = 0;
/**
* @brief Create new 1-dimensional histogram and return pointer to it.
*
* This method creates new 1-dimensional histogram, number of bins and
* their edges are determined by separate object (Axis class).
* Internal storage of the created histogram will consists of 64-bit
* floating number per histogram bin.
* The name of the histogram must be unique, otherwise exception is thrown.
*
* <b>Returned pointer should never be deleted by client code.</b>
*
* @param[in] name Histogram name, unique string.
* @param[in] title Title of the histogram, arbitrary string.
* @param[in] axis Axis definition.
* @return Pointer to a newly created histogram, do not delete.
*
* @throw ExceptionDuplicateName thrown if histogram or tuple with
* identical name exists already
*/
virtual H1* hist1d(const std::string& name, const std::string& title,
const PSHist::Axis& axis) = 0;
// 2-d histograms
/**
* @brief Create new 2-dimensional histogram and return pointer to it.
*
* This method creates new 2-dimensional histogram, number of bins and
* their edges are determined by separate objects (Axis class).
* Internal storage of the created histogram will consists of 32-bit
* integer per histogram bin.
* The name of the histogram must be unique, otherwise exception is thrown.
*
* <b>Returned pointer should never be deleted by client code.</b>
*
* @param[in] name Histogram name, unique string.
* @param[in] title Title of the histogram, arbitrary string.
* @param[in] xaxis X axis definition.
* @param[in] yaxis Y axis definition.
* @return Pointer to a newly created histogram, do not delete.
*
* @throw ExceptionDuplicateName thrown if histogram or tuple with
* identical name exists already
*/
virtual H2* hist2i(const std::string& name, const std::string& title,
const PSHist::Axis& xaxis, const PSHist::Axis& yaxis ) = 0;
/**
* @brief Create new 2-dimensional histogram and return pointer to it.
*
* This method creates new 2-dimensional histogram, number of bins and
* their edges are determined by separate objects (Axis class).
* Internal storage of the created histogram will consists of 32-bit
* floating number per histogram bin.
* The name of the histogram must be unique, otherwise exception is thrown.
*
* <b>Returned pointer should never be deleted by client code.</b>
*
* @param[in] name Histogram name, unique string.
* @param[in] title Title of the histogram, arbitrary string.
* @param[in] xaxis X axis definition.
* @param[in] yaxis Y axis definition.
* @return Pointer to a newly created histogram, do not delete.
*
* @throw ExceptionDuplicateName thrown if histogram or tuple with
* identical name exists already
*/
virtual H2* hist2f(const std::string& name, const std::string& title,
const PSHist::Axis& xaxis, const PSHist::Axis& yaxis ) = 0;
/**
* @brief Create new 2-dimensional histogram and return pointer to it.
*
* This method creates new 2-dimensional histogram, number of bins and
* their edges are determined by separate objects (Axis class).
* Internal storage of the created histogram will consists of 64-bit
* floating number per histogram bin.
* The name of the histogram must be unique, otherwise exception is thrown.
*
* <b>Returned pointer should never be deleted by client code.</b>
*
* @param[in] name Histogram name, unique string.
* @param[in] title Title of the histogram, arbitrary string.
* @param[in] xaxis X axis definition.
* @param[in] yaxis Y axis definition.
* @return Pointer to a newly created histogram, do not delete.
*
* @throw ExceptionDuplicateName thrown if histogram or tuple with
* identical name exists already
*/
virtual H2* hist2d(const std::string& name, const std::string& title,
const PSHist::Axis& xaxis, const PSHist::Axis& yaxis ) = 0;
// 1-d profile histograms
/**
* @brief Create new 1-dimensional profile histogram and return pointer to it.
*
* This method creates new 1-dimensional profile histogram with same-width bins.
* The name of the histogram must be unique, otherwise exception is thrown.
* Option string determines what value is returned for the bin error,
* possible values are "" (default) for error-of-mean and "s"
* for standard deviation.
*
* <b>Returned pointer should never be deleted by client code.</b>
*
* @param[in] name Histogram name, unique string.
* @param[in] title Title of the histogram, arbitrary string.
* @param[in] nbinsx Number of bins.
* @param[in] xlow Low edge of the first bin.
* @param[in] xhigh High edge of the last bin.
* @param[in] option Option string.
* @return Pointer to a newly created histogram, do not delete.
*
* @throw ExceptionDuplicateName thrown if histogram or tuple with
* identical name exists already
*/
virtual Profile* prof1(const std::string& name, const std::string& title,
int nbinsx, double xlow, double xhigh, const std::string& option="") = 0;
/**
* @brief Create new 1-dimensional profile histogram and return pointer to it.
*
* This method creates new 1-dimensional profile histogram with variable-width bins.
* The name of the histogram must be unique, otherwise exception is thrown.
* Option string determines what value is returned for the bin error,
* possible values are "" (default) for error-of-mean and "s"
* for standard deviation.
*
* <b>Returned pointer should never be deleted by client code.</b>
*
* @param[in] name Histogram name, unique string.
* @param[in] title Title of the histogram, arbitrary string.
* @param[in] nbins Number of bins.
* @param[in] xbinedges Array of the histogram edges, size of the array
* is @c nbins+1, it should contain ordered values for
* low edges of all bins plus high edge of last bin.
* @param[in] option Option string.
* @return Pointer to a newly created histogram, do not delete.
*
* @throw ExceptionDuplicateName thrown if histogram or tuple with
* identical name exists already
*/
virtual Profile* prof1(const std::string& name, const std::string& title,
int nbins, const double *xbinedges, const std::string& option="") = 0;
/**
* @brief Create new 1-dimensional profile histogram and return pointer to it.
*
* This method creates new 1-dimensional profile histogram, number of bins and
* their edges are determined by separate object (Axis class).
* The name of the histogram must be unique, otherwise exception is thrown.
* Option string determines what value is returned for the bin error,
* possible values are "" (default) for error-of-mean and "s"
* for standard deviation.
*
* <b>Returned pointer should never be deleted by client code.</b>
*
* @param[in] name Histogram name, unique string.
* @param[in] title Title of the histogram, arbitrary string.
* @param[in] axis X axis definition.
* @param[in] option Option string.
* @return Pointer to a newly created histogram, do not delete.
*
* @throw ExceptionDuplicateName thrown if histogram or tuple with
* identical name exists already
*/
virtual Profile* prof1(const std::string& name, const std::string& title,
const PSHist::Axis& axis, const std::string& option="") = 0;
/**
* @brief Create new 1-dimensional profile histogram and return pointer to it.
*
* This method creates new 1-dimensional profile histogram with same-width bins.
* The name of the histogram must be unique, otherwise exception is thrown.
* Option string determines what value is returned for the bin error,
* possible values are "" (default) for error-of-mean and "s"
* for standard deviation.
* Values of y ouside of range (ylow-yhigh) will be ignored.
*
* <b>Returned pointer should never be deleted by client code.</b>
*
* @param[in] name Histogram name, unique string.
* @param[in] title Title of the histogram, arbitrary string.
* @param[in] nbinsx Number of bins.
* @param[in] xlow Low edge of the first bin.
* @param[in] xhigh High edge of the last bin.
* @param[in] ylow Lowest possible value for Y values.
* @param[in] yhigh Highest possible value for Y values.
* @param[in] option Option string.
* @return Pointer to a newly created histogram, do not delete.
*
* @throw ExceptionDuplicateName thrown if histogram or tuple with
* identical name exists already
*/
virtual Profile* prof1(const std::string& name, const std::string& title,
int nbinsx, double xlow, double xhigh, double ylow, double yhigh,
const std::string& option="") = 0;
/**
* @brief Create new 1-dimensional profile histogram and return pointer to it.
*
* This method creates new 1-dimensional profile histogram with variable-width bins.
* The name of the histogram must be unique, otherwise exception is thrown.
* Option string determines what value is returned for the bin error,
* possible values are "" (default) for error-of-mean and "s"
* for standard deviation.
* Values of y ouside of range (ylow-yhigh) will be ignored.
*
* <b>Returned pointer should never be deleted by client code.</b>
*
* @param[in] name Histogram name, unique string.
* @param[in] title Title of the histogram, arbitrary string.
* @param[in] nbins Number of bins.
* @param[in] xbinedges Array of the histogram edges, size of the array
* is @c nbins+1, it should contain ordered values for
* low edges of all bins plus high edge of last bin.
* @param[in] ylow Lowest possible value for Y values.
* @param[in] yhigh Highest possible value for Y values.
* @param[in] option Option string.
* @return Pointer to a newly created histogram, do not delete.
*
* @throw ExceptionDuplicateName thrown if histogram or tuple with
* identical name exists already
*/
virtual Profile* prof1(const std::string& name, const std::string& title,
int nbins, const double *xbinedges, double ylow, double yhigh,
const std::string& option="") = 0;
/**
* @brief Create new 1-dimensional profile histogram and return pointer to it.
*
* This method creates new 1-dimensional profile histogram, number of bins and
* their edges are determined by separate object (Axis class).
* The name of the histogram must be unique, otherwise exception is thrown.
* Option string determines what value is returned for the bin error,
* possible values are "" (default) for error-of-mean and "s"
* for standard deviation.
* Values of y ouside of range (ylow-yhigh) will be ignored.
*
* <b>Returned pointer should never be deleted by client code.</b>
*
* @param[in] name Histogram name, unique string.
* @param[in] title Title of the histogram, arbitrary string.
* @param[in] axis X axis definition.
* @param[in] ylow Lowest possible value for Y values.
* @param[in] yhigh Highest possible value for Y values.
* @param[in] option Option string.
* @return Pointer to a newly created histogram, do not delete.
*
* @throw ExceptionDuplicateName thrown if histogram or tuple with
* identical name exists already
*/
virtual Profile* prof1(const std::string& name, const std::string& title,
const PSHist::Axis& axis, double ylow, double yhigh,
const std::string& option="") = 0;
/**
* @brief Create new tuple and return pointer to it.
*
* The name of the tuple must be unique, otherwise exception is thrown.
*
* <b>Returned pointer should never be deleted by client code.</b>
*
* @param[in] name Tuple name, unique string.
* @param[in] title Title of the tuple, arbitrary string.
* @return Pointer to a newly created tuple, do not delete.
*
* @throw ExceptionDuplicateName thrown if histogram or tuple with
* identical name exists already
*/
virtual Tuple* tuple(const std::string& name, const std::string& title) = 0;
/**
* @brief Store all booked histograms and tuples to a permanent storage.
*
* This method should be called once before deleting manager object.
*
* @throw ExceptionStore thrown if write operation fails.
*/
virtual void write() = 0;
};
} // namespace PSHist
#endif // PSHIST_HMANAGER_H
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.