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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
d052095a27344cda9162516ff57fff3e7936c774 | ae0247be1c758efb09b1a862cc85754c7ae95f23 | /src/DaliParser/ddl_stmts.c | 91148b92d35e9fee30b5298caf8abdb5d0002826 | [] | no_license | rathodsachin20/mubase | 562680093dea13a5d0d2df71687be7e4cfa78c5f | 91bad1d9666d6a6f4a01caad1021f633b83217d8 | refs/heads/master | 2021-01-10T05:00:12.792001 | 2016-03-03T05:01:23 | 2016-03-03T05:01:23 | 48,962,359 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,714 | c | ddl_stmts.c | /* -*- c++ -*- */
#include "sql_parse.h"
/**************************************************************************/
/**
FIX: All the create functions below will later change to return DaliPtr's
**/
template<class T>
void printList(FILE *file_a, List<T> &list_a)
{
putc('(', file_a);
Listiter<T> listIter(list_a);
while(true)
{
T *temp;
listIter.next(temp);
temp->print(file_a);
if(listIter.at_end())
break;
fprintf(file_a, ", ");
}
putc(')', file_a);
return;
}
void
InsertTable::Constructor(const char *relName_a, Tuple *argList_a,
RelExpr *tableExpr_a)
{
NonRelExpr::Constructor(D_INSERT);
strcpy(relName, relName_a);
argList = argList_a;
tableExpr = tableExpr_a;
return;
}
InsertTable *
InsertTable::create(const char *relName, Tuple *argList,
RelExpr *tableExpr)
{
InsertTable *v = (InsertTable *) new char[sizeof(InsertTable)];
v->Constructor(relName, argList, tableExpr);
return v;
}
bool
InsertTable::typeCheck(TransID &tid_a)
{
if(tableExpr->typeCheck(0, tid_a) < 0)
return false;
if(GetRelInfo(relName, tid_a, resultInfo) == false)
SQLErrAR("Invalid table name %s in Insert stmt\n", relName, false);
bool typeCheckingFailed = false;
if(argList)
{
if(argList->numAttrs != tableExpr->resultInfo.numArgs)
typeCheckingFailed = true;
for(int sourceFieldNum = 0; (sourceFieldNum < argList->numAttrs) &&
!typeCheckingFailed; ++sourceFieldNum)
typeCheckingFailed = (typeCheckingFailed ||
(argList->attrs[sourceFieldNum]->exprType != Expr::D_REL_ARG_REF)
|| !ArgType::IsAsgCompatible(argList->attrs[sourceFieldNum]->
typeCheck(resultInfo), tableExpr->
resultInfo.args[sourceFieldNum].argType));
}
else
{
if(resultInfo.numArgs != tableExpr->resultInfo.numArgs)
typeCheckingFailed = true;
for(int sourceFieldNum = 0; (sourceFieldNum < resultInfo.numArgs)
&& !typeCheckingFailed; ++sourceFieldNum)
typeCheckingFailed = (typeCheckingFailed ||
!ArgType::IsAsgCompatible(resultInfo.args[sourceFieldNum].argType,
tableExpr->resultInfo.args[sourceFieldNum].argType));
}
if(typeCheckingFailed)
SQLErrR("type checking of insert-table failed", false)
else
return true;
}
bool
InsertTable::rewrite()
{
bool retVal = tableExpr->rewrite();
if(argList)
for(int i = 0; i < argList->numAttrs; ++i)
{
Expr *newExpr;
if(((newExpr = argList->attrs[i]->rewrite(resultInfo, RESULT))
!= argList->attrs[i]) && ((argList->attrs[i] = newExpr) == NULL))
SQLErrR("rewriting of insert-table failed", false)
}
return retVal;
}
/***************/
void
DeleteTable::Constructor(const char *relName_a, Expr *where_a)
{
NonRelExpr::Constructor(D_DELETE);
relScan = RelScanExpr::create(relName_a, where_a);
return;
}
DeleteTable *
DeleteTable::create(const char *relName_a, Expr *whereCond_a)
{
DeleteTable * v = (DeleteTable *) new char[sizeof(DeleteTable)];
v->Constructor(relName_a, whereCond_a);
return v;
}
bool
DeleteTable::print(FILE *file)
{
fprintf(file, " DELETE FROM %s ", relScan->name);
if(relScan->cond) {
fprintf(file, " WHERE ");
relScan->cond->print(file);
}
fprintf(file, "\n");
return true;
}
/***************/
void
UpdateExpr::print(FILE *out_a)
{
attribute->print(out_a);
fprintf(out_a, " := ");
rhs->print(out_a);
return;
}
bool
UpdateExpr::typeCheck(TupleDef &bindings_a)
{
if(attribute->exprType != Expr::D_REL_ARG_REF)
return false;
if(((attribute->typeCheck(bindings_a)).type == D_UnknownType) ||
((rhs->typeCheck(bindings_a)).type == D_UnknownType))
return false;
return ArgType::IsAsgCompatible(attribute->type, rhs->type);
}
bool
UpdateExpr::rewrite(TupleDef &bindings_a, ArgSource source_a)
{
bool retVal =
((attribute = attribute->rewrite(bindings_a, source_a)) != NULL);
Expr *newExpr;
if((newExpr = rhs->rewrite(bindings_a, source_a)) != rhs)
retVal = (retVal && ((rhs = newExpr) != NULL));
return retVal;
}
/***************/
void
UpdateTable::Constructor(const char *relName_a, UpdateExprList *avl_a,
Expr *where_a)
{
NonRelExpr::Constructor(D_UPDATE);
relScan = RelScanExpr::create(relName_a, where_a);
attrValList.numUpdateExprs = avl_a->length();
attrValList.updateExprs = new UpdateExpr[attrValList.numUpdateExprs];
Listiter<UpdateExpr> attrValIter(*avl_a);
for(int i = 0; !attrValIter.at_end(); ++i)
attrValIter.next(attrValList.updateExprs[i]);
delete avl_a;
return;
}
UpdateTable *
UpdateTable::create(const char *relName, UpdateExprList *avl,
Expr *whereCond)
{
UpdateTable *v = (UpdateTable *) new char[sizeof(UpdateTable)];
v->Constructor(relName, avl, whereCond);
return v;
}
bool
UpdateTable::print(FILE *out_a)
{
fprintf(out_a, " UPDATE %s SET (", relScan->name);
for(int i = 0; i < attrValList.numUpdateExprs - 1; ++i)
{
attrValList.updateExprs[i].print(out_a);
fprintf(out_a, ", ");
}
if(attrValList.numUpdateExprs > 0)
attrValList.updateExprs[i].print(out_a);
if(relScan->cond) {
fprintf(out_a, ") WHERE ");
relScan->cond->print(out_a);
}
fprintf(out_a, "\n");
return true;
}
bool
UpdateTable::typeCheck(TransID &tid_a)
{
if(((RelExpr *)relScan)->typeCheck(0, tid_a) < 0)
return false;
resultInfo = ((RelExpr *)relScan)->resultInfo;
for(int i = 0; i < attrValList.numUpdateExprs; ++i)
if(!attrValList.updateExprs[i].typeCheck(resultInfo))
SQLErrR("Type checking of update-expr failed", false);
return true;
}
bool
UpdateTable::rewrite()
{
for(int i = 0; i < attrValList.numUpdateExprs; ++i)
if(!attrValList.updateExprs[i].rewrite(resultInfo, RESULT))
SQLErrR("Re-writing of $UpdateExpr$ failed", false);
return ((RelExpr *)relScan)->rewrite();
}
/***************/
#define QUANTUM (50)
Table_descriptor::~Table_descriptor()
{
if(name)
free(name);
name = 0;
if(dbfile_name)
free(dbfile_name);
dbfile_name = 0;
schema.destroy();
}
View_descriptor::~View_descriptor()
{
if(name)
free(name);
if(sourceName)
free(sourceName);
schema.destroy();
}
MTM_descriptor::MTM_descriptor()
: name(0), fromTableName(0), toTableName(0), addPointers(0),
oneToManyFlag(0)
{
fromAttrList.destroy();
toAttrList.destroy();
}
MTM_descriptor::~MTM_descriptor()
{
if(name)
free(name);
if(fromTableName)
free(fromTableName);
if(toTableName)
free(toTableName);
fromAttrList.destroy();
toAttrList.destroy();
}
RI_descriptor::RI_descriptor()
: name(0), fromTableName(0), toTableName(0)
{
fromTableList.destroy();
toTableList.destroy();
}
RI_descriptor::~RI_descriptor()
{
if(name)
free(name);
if(fromTableName)
free(fromTableName);
if(toTableName)
free(toTableName);
fromTableList.destroy();
toTableList.destroy();
}
Index_descriptor::Index_descriptor()
: name(0), tableName(0)
{
attrList.destroy();
}
Index_descriptor::~Index_descriptor()
{
if(name)
free(name);
attrList.destroy();
}
/***************************/
int MultiTableSchema::addTable(Table_descriptor *ntable)
{
if(tableCount>= tableMax) {
tableMax += QUANTUM;
tableList = (Table_descriptor **) realloc(tableList,
tableMax * sizeof(Table_descriptor));
}
tableList[tableCount] = ntable;
tableCount++;
return 1;
}
int MultiTableSchema::addView(View_descriptor *nview)
{
if(viewCount>= viewMax) {
viewMax += QUANTUM;
viewList = (View_descriptor **) realloc(viewList,
viewMax * sizeof(View_descriptor));
}
viewList[viewCount] = nview;
viewCount++;
return 1;
}
int MultiTableSchema::addMTM(MTM_descriptor *nmtm)
{
if(mtmCount>= mtmMax) {
mtmMax += QUANTUM;
mtmList = (MTM_descriptor **) realloc(mtmList,
mtmMax * sizeof(MTM_descriptor));
}
mtmList[mtmCount] = nmtm;
mtmCount++;
return 1;
}
int MultiTableSchema::addRI(RI_descriptor *nri)
{
if(riCount>= riMax) {
riMax += QUANTUM;
riList = (RI_descriptor **) realloc(riList,
riMax * sizeof(RI_descriptor));
}
riList[riCount] = nri;
riCount++;
return 1;
}
int MultiTableSchema::addIndex(Index_descriptor *nindex)
{
if(indexCount>= indexMax) {
indexMax += QUANTUM;
indexList = (Index_descriptor **) realloc(indexList,
indexMax * sizeof(Index_descriptor));
}
indexList[indexCount] = nindex;
indexCount++;
return 1;
}
void
PrintIndexType(DaliIndexType indexType_a, FILE *out_a)
{
switch(indexType_a)
{
case DALI_HASH:
fprintf(out_a, "hash"); break;
case DALI_TTREE:
fprintf(out_a, "ttree"); break;
case DALI_UNIQUE_HASH:
fprintf(out_a, "unique hash"); break;
case DALI_UNIQUE_TTREE:
fprintf(out_a, "unique ttree"); break;
default:
fprintf(out_a, "<unknown index type>");
}
}
bool
MultiTableSchema::evaluate(TransID &tid)
{
int err;
for(int i = 0; i < tableCount; i++)
{
Table_descriptor *td = tableList[i];
err = DaliRelMgr::createTable(tid,td->name, td->schema,
td->dbfile_name);
if(err >= 0)
fprintf(stdout, "Created table %s in statement no: %d\n\n",
td->name, stmtCount);
else
SQLErrAR("Cannot create table %s", td->name, false)
}
for(i = 0; i < indexCount; i++)
{
Index_descriptor *id = indexList[i];
err = DaliRelMgr::createIndex(tid,id->name, id->tableName,
id->attrList,id->type);
if(err >= 0)
{
fprintf(stdout, "Created ");
PrintIndexType(id->type, stdout);
fprintf(stdout, " index %s on table %s in statement no: "
"%d\n\n", id->name, id->tableName, stmtCount);
}
else
SQLErrAAR("Cannot create index %s on table %s", id->name,
id->tableName, false)
}
#if 0
for(i = 0; i < viewCount; i++) {
View_descriptor *td = viewList[i];
printf("Creating view %s\n",td->name);
// td->sch.print(stdout);
err = DaliRelMgr::createView(tid,td->name, td->sourceName,
td->sch);
if(err < 0) {
printf("Cannot create view %s: %d\n",td->name,err);
return -1;
}
/*
DaliTableHandle newtab;
DaliRelMgr::openTable(tid,$3,newtab);
cout << * newtab.schemaInfo;
*/
}
for(i = 0; i < mtmCount; i++) {
MTM_descriptor *md = mtmList[i];
printf("Creating inter-table mapping %s\n",md->name);
err = DaliRelMgr::createOneToMany(tid,md->name,
md->fromTableName,
md->fromAttrList,
md->toTableName,
md->toAttrList,
md->addPointers,
md->oneToManyFlag
);
if(err < 0) {
printf("Cannot create mapping %s: %d\n",md->name,err);
return -1;
}
}
for(i = 0; i < riCount; i++) {
RI_descriptor *rd = riList[i];
if(rd->name == 0) {
char buf[1000];
sprintf(buf,"TC_%d",i);
rd->name = strdup(buf);
}
printf("Creating integrity constraint %s\n",rd->name);
err = DaliRelMgr::createReferentialIntegrity(tid,
/* ri->name, */
rd->fromTableName,
rd->fromTableList,
rd->toTableName,
rd->toTableList);
if(err < 0) {
printf("Cannot create integrity constraint %s: %d\n",rd->name,err);
return -1;
}
}
#endif
return true;
}
MultiTableSchema::~MultiTableSchema()
{
for(int i = 0; i < tableCount; i++)
delete tableList[i];
free(tableList); // called realloc above, so using free here
for(i = 0; i < viewCount; i++)
delete viewList[i];
free(viewList); // called realloc above, so using free here
for(i = 0; i < mtmCount; i++)
delete mtmList[i];
free(mtmList);
for(i = 0; i < riCount; i++)
delete riList[i];
free(riList);
for(i = 0; i < indexCount; i++)
delete indexList[i];
free(indexList);
}
/********************/
bool
CreateTableSpace::evaluate(TransID &)
{
DbInitInfo info;
if(size > 0)
info.max_db_size = size;
DaliDB *db= DaliDB::open(name, _DB_CREAT, &info);
if(db)
{
db->close();
fprintf(stdout, "Created table-space:%s in statement no:%d\n",
name, stmtCount);
return true;
}
else
SQLErrAE("Unable to create table-space:%s", name, -1)
}
/********************/
bool
DropDataBase::evaluate(TransID &)
{
if((DaliDB::unlink("CatalogDB") < 0) || (DaliDB::unlink("REL_DB") < 0))
SQLErrE("Unable to drop database", -1)
else
{
fprintf(stdout, "Dropped Data Base in statement no:%d\n", stmtCount);
return true;
}
}
/********************/
bool
DropTableSpace::evaluate(TransID &)
{
/*FIX: these checks can be fooled with simple path name changes. */
if(!strcmp(name, "CatalogDB"))
SQLErrR("Cannot drop CatalogDB, use DROP DATABASE", false)
if(!strcmp(name, "REL_DB"))
SQLErrR("Cannot drop REL_DB, use DROP DATABASE", false)
if(!strcmp(name, SysDB::sysdb_start->name()))
SQLErrR("Cannot drop the system database!!!", false)
DALI_R_ASSERT(DaliDB::unlink(name) >= 0);
fprintf(stdout, "Dropped table-space:%s in statement no:%d\n",
name, stmtCount);
return true;
}
/********************/
|
3ff30cb0d840a3bcb7ad3cc479f051c113331c33 | 2eebe8877c3927dbc6e6dda8920093510e81ee81 | /bixecamp-2019/aula8-pd/lcs/lcs.cpp | e4478a5038b3b6560318bb0a69b62c5f7b642f70 | [] | no_license | maratonusp/Caderno-dos-bixes | 9445cb6e25995bd38ed317d087f966f7d6e9e1a9 | c4e0f5768600103b33339b224fa1375530295969 | refs/heads/master | 2022-05-31T11:52:33.645319 | 2022-05-14T17:43:55 | 2022-05-14T17:43:55 | 168,978,559 | 41 | 14 | null | 2020-06-05T22:58:11 | 2019-02-03T18:31:01 | C++ | UTF-8 | C++ | false | false | 1,197 | cpp | lcs.cpp | #include "bits/stdc++.h"
using namespace std;
//https://www.hackerrank.com/challenges/dynamic-programming-classics-the-longest-common-subsequence/problem
#define dbg(x) cout << #x << " = " << x << endl
int a[1010], b[1010];
int memo[1010][1010];
vector<int> bestSequence;
int n, m;
const int INF = 0x3f3f3f3f;
int pd(int i, int j){
if(i==n || j==m)
return 0;
int& pdm = memo[i][j];
if(pdm!=-1) return pdm;
pdm=0;
if(a[i]==b[j])
pdm=max(pdm, 1 + pd(i+1,j+1));
return pdm = max({pdm, pd(i+1,j), pd(i,j+1)});
}
void recover(int i, int j){
if(i==n || j==m) return;
int passa1 = pd(i+1, j);
int passa2 = pd(i, j+1);
int pega = (a[i]==b[j] ? 1 + pd(i+1, j+1) : -INF);
if(pega>=passa1 && pega>=passa2)
bestSequence.push_back(a[i]), recover(i+1,j+1);
else if(passa1>=passa2)
recover(i+1, j);
else
recover(i, j+1);
}
int main(){
cin >> n >> m;
for(int i=0;i<n;i++)
cin >> a[i];
for(int i=0;i<m;i++)
cin >> b[i];
memset(memo, -1, sizeof(memo));
recover(0, 0);
for(auto x : bestSequence)
cout << x << " ";
cout << "\n";
} |
3c6571b89f95ea078c6cfd66452b0351dfea7856 | 60bd79d18cf69c133abcb6b0d8b0a959f61b4d10 | /libraries/Gauss/test/unit_test_001.cpp | dd936ccff163e98e77f578a548098cff7fdb919c | [
"MIT"
] | permissive | RobTillaart/Arduino | e75ae38fa6f043f1213c4c7adb310e91da59e4ba | 48a7d9ec884e54fcc7323e340407e82fcc08ea3d | refs/heads/master | 2023-09-01T03:32:38.474045 | 2023-08-31T20:07:39 | 2023-08-31T20:07:39 | 2,544,179 | 1,406 | 3,798 | MIT | 2022-10-27T08:28:51 | 2011-10-09T19:53:59 | C++ | UTF-8 | C++ | false | false | 4,418 | cpp | unit_test_001.cpp | //
// FILE: unit_test_001.cpp
// AUTHOR: Rob Tillaart
// DATE: 2023-07-07
// PURPOSE: unit tests for the Gauss library
// https://github.com/RobTillaart/Gauss
// https://github.com/Arduino-CI/arduino_ci/blob/master/REFERENCE.md
//
// supported assertions
// ----------------------------
// assertEqual(expected, actual)
// assertNotEqual(expected, actual)
// assertLess(expected, actual)
// assertMore(expected, actual)
// assertLessOrEqual(expected, actual)
// assertMoreOrEqual(expected, actual)
// assertTrue(actual)
// assertFalse(actual)
// assertNull(actual)
#include <ArduinoUnitTests.h>
#include "Arduino.h"
#include "Gauss.h"
unittest_setup()
{
fprintf(stderr, "GAUSS_LIB_VERSION: %s\n", (char *) GAUSS_LIB_VERSION);
}
unittest_teardown()
{
}
unittest(test_constructor)
{
Gauss G;
assertEqualFloat(0.0, G.getMean(), 0.0001);
assertEqualFloat(1.0, G.getStdDev(), 0.0001);
assertEqualFloat(0.5, G.P_smaller(0), 0.0001);
G.begin(10, 3);
assertEqualFloat(10.0, G.getMean(), 0.0001);
assertEqualFloat(3.0, G.getStdDev(), 0.0001);
}
unittest(test_P_smaller)
{
Gauss G;
G.begin(0, 1);
assertEqualFloat(0.0000, G.P_smaller(-6.0), 0.0001);
assertEqualFloat(0.0001, G.P_smaller(-4.0), 0.0001);
assertEqualFloat(0.0013, G.P_smaller(-3.0), 0.0001);
assertEqualFloat(0.0228, G.P_smaller(-2.0), 0.0001);
assertEqualFloat(0.1587, G.P_smaller(-1.0), 0.0001);
assertEqualFloat(0.5000, G.P_smaller(0.0), 0.0001);
assertEqualFloat(0.8413, G.P_smaller(1.0), 0.0001);
assertEqualFloat(0.9772, G.P_smaller(2.0), 0.0001);
assertEqualFloat(0.9987, G.P_smaller(3.0), 0.0001);
assertEqualFloat(0.9999, G.P_smaller(4.0), 0.0001);
assertEqualFloat(1.0000, G.P_smaller(6.0), 0.0001);
}
unittest(test_P_larger)
{
Gauss G;
G.begin(0, 1);
assertEqualFloat(0.9987, G.P_larger(-3.0), 0.0001);
assertEqualFloat(0.9772, G.P_larger(-2.0), 0.0001);
assertEqualFloat(0.8413, G.P_larger(-1.0), 0.0001);
assertEqualFloat(0.5000, G.P_larger(0.0), 0.0001);
assertEqualFloat(0.1587, G.P_larger(1.0), 0.0001);
assertEqualFloat(0.0228, G.P_larger(2.0), 0.0001);
assertEqualFloat(0.0013, G.P_larger(3.0), 0.0001);
}
unittest(test_P_between)
{
Gauss G;
G.begin(0, 1);
assertEqualFloat(0.4987, G.P_between(-3.0, 0.0), 0.0001);
assertEqualFloat(0.4772, G.P_between(-2.0, 0.0), 0.0001);
assertEqualFloat(0.3413, G.P_between(-1.0, 0.0), 0.0001);
assertEqualFloat(0.0000, G.P_between(0.0, 0.0), 0.0001);
assertEqualFloat(0.3413, G.P_between(0.0, 1.0), 0.0001);
assertEqualFloat(0.4772, G.P_between(0.0, 2.0), 0.0001);
assertEqualFloat(0.4987, G.P_between(0.0, 3.0), 0.0001);
}
unittest(test_P_outside)
{
Gauss G;
G.begin(0, 1);
assertEqualFloat(0.5013, G.P_outside(-3.0, 0.0), 0.0001);
assertEqualFloat(0.5228, G.P_outside(-2.0, 0.0), 0.0001);
assertEqualFloat(0.6587, G.P_outside(-1.0, 0.0), 0.0001);
assertEqualFloat(1.0000, G.P_outside(0.0, 0.0), 0.0001);
assertEqualFloat(0.6587, G.P_outside(0.0, 1.0), 0.0001);
assertEqualFloat(0.5228, G.P_outside(0.0, 2.0), 0.0001);
assertEqualFloat(0.5013, G.P_outside(0.0, 3.0), 0.0001);
}
unittest(test_P_equal)
{
Gauss G;
G.begin(0, 1);
assertEqualFloat(0.004432, G.P_equal(-3.0), 0.0001);
assertEqualFloat(0.053991, G.P_equal(-2.0), 0.0001);
assertEqualFloat(0.241971, G.P_equal(-1.0), 0.0001);
assertEqualFloat(0.398942, G.P_equal(0.0), 0.0001);
assertEqualFloat(0.241971, G.P_equal(1.0), 0.0001);
assertEqualFloat(0.053991, G.P_equal(2.0), 0.0001);
assertEqualFloat(0.004432, G.P_equal(3.0), 0.0001);
}
unittest(test_normailze)
{
Gauss G;
G.begin(100, 25);
assertEqualFloat(-3.0, G.normalize(25), 0.0001);
assertEqualFloat(-2.0, G.normalize(50), 0.0001);
assertEqualFloat(-1.0, G.normalize(75), 0.0001);
assertEqualFloat(0.0, G.normalize(100), 0.0001);
assertEqualFloat(1.0, G.normalize(125), 0.0001);
assertEqualFloat(2.0, G.normalize(150), 0.0001);
assertEqualFloat(3.0, G.normalize(175), 0.0001);
assertEqualFloat(25, G.denormalize(-3.0), 0.0001);
assertEqualFloat(50, G.denormalize(-2.0), 0.0001);
assertEqualFloat(75, G.denormalize(-1.0), 0.0001);
assertEqualFloat(100, G.denormalize(0.0), 0.0001);
assertEqualFloat(125, G.denormalize(1.0), 0.0001);
assertEqualFloat(150, G.denormalize(2.0), 0.0001);
assertEqualFloat(175, G.denormalize(3.0), 0.0001);
}
unittest_main()
// -- END OF FILE --
|
349f332d229f42c114203792309629bba0a76598 | d1bc08bc30eaba4bf1bf7f5bb242b9780aff41ee | /hll/test/CouponListTest.cpp | 5f65150263c0a88233bc25963832835eb517f077 | [] | no_license | frankgrimes97/sketches-core-cpp | 5480bc054bef950636de8b9d9a0ffd12ab505de9 | 34215550df36877ec66ba2c9f18b5a0a2c41bfe0 | refs/heads/master | 2020-04-01T14:27:19.437671 | 2018-11-19T19:51:30 | 2018-11-19T19:51:30 | 153,294,881 | 0 | 0 | null | 2018-10-16T13:57:53 | 2018-10-16T13:57:53 | null | UTF-8 | C++ | false | false | 3,637 | cpp | CouponListTest.cpp | /*
* Copyright 2018, Oath Inc. Licensed under the terms of the
* Apache License 2.0. See LICENSE file at the project root for terms.
*/
#include "hll.hpp"
#include "HllSketch.hpp"
#include "HllUnion.hpp"
#include "HllUtil.hpp"
#include <cppunit/TestFixture.h>
#include <cppunit/extensions/HelperMacros.h>
#include <ostream>
#include <cmath>
#include <string>
namespace datasketches {
class CouponListTest : public CppUnit::TestFixture {
CPPUNIT_TEST_SUITE(CouponListTest);
CPPUNIT_TEST(checkIterator);
CPPUNIT_TEST(checkDuplicatesAndMisc);
CPPUNIT_TEST(checkSerializeDeserialize);
CPPUNIT_TEST_SUITE_END();
void println_string(std::string str) {
//std::cout << str << "\n";
}
void checkIterator() {
int lgConfigK = 8;
HllSketch* sk = HllSketch::newInstance(lgConfigK);
for (int i = 0; i < 7; ++i) { sk->update(i); }
std::unique_ptr<PairIterator> itr = static_cast<HllSketchPvt*>(sk)->getIterator();
println_string(itr->getHeader());
while (itr->nextAll()) {
int key = itr->getKey();
int val = itr->getValue();
int idx = itr->getIndex();
int slot = itr->getSlot();
std::ostringstream oss;
oss << "Idx: " << idx << ", Key: " << key << ", Val: " << val
<< ", Slot: " << slot;
println_string(oss.str());
}
delete sk;
}
void checkDuplicatesAndMisc() {
int lgConfigK = 8;
HllSketch* skContainer = HllSketch::newInstance(lgConfigK);
HllSketchPvt* sk = static_cast<HllSketchPvt*>(skContainer);
for (int i = 1; i <= 7; ++i) {
sk->update(i);
sk->update(i);
}
CPPUNIT_ASSERT_EQUAL(sk->getCurrentMode(), CurMode::LIST);
CPPUNIT_ASSERT_DOUBLES_EQUAL(sk->getCompositeEstimate(), 7.0, 7 * 0.1);
sk->update(8);
sk->update(8);
CPPUNIT_ASSERT_EQUAL(sk->getCurrentMode(), CurMode::SET);
CPPUNIT_ASSERT_DOUBLES_EQUAL(sk->getCompositeEstimate(), 8.0, 8 * 0.1);
for (int i = 9; i <= 25; ++i) {
sk->update(i);
sk->update(i);
}
CPPUNIT_ASSERT_EQUAL(sk->getCurrentMode(), CurMode::HLL);
CPPUNIT_ASSERT_DOUBLES_EQUAL(sk->getCompositeEstimate(), 25.0, 25 * 0.1);
double relErr = sk->getRelErr(true, true, 4, 1);
CPPUNIT_ASSERT(relErr < 0.0);
delete sk;
}
std::string dumpAsHex(const char* data, int len) {
constexpr uint8_t hexmap[] = {'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
std::string s(len * 2, ' ');
for (int i = 0; i < len; ++i) {
s[2 * i] = hexmap[(data[i] & 0xF0) >> 4];
s[2 * i + 1] = hexmap[(data[i] & 0x0F)];
}
return s;
}
void serializeDeserialize(const int lgK) {
HllSketch* sk1 = HllSketch::newInstance(lgK);
int u = (lgK < 8) ? 7 : (((1 << (lgK - 3))/ 4) * 3);
for (int i = 0; i < u; ++i) {
sk1->update(i);
}
double est1 = sk1->getEstimate();
CPPUNIT_ASSERT_DOUBLES_EQUAL(est1, u, u * 1e-4);
std::stringstream ss(std::ios::in | std::ios::out | std::ios::binary);
sk1->serializeCompact(ss);
HllSketch* sk2 = HllSketch::deserialize(ss);
double est2 = sk2->getEstimate();
CPPUNIT_ASSERT_DOUBLES_EQUAL(est2, est1, 0.0);
delete sk2;
ss.str(std::string());
ss.clear();
sk1->serializeUpdatable(ss);
sk2 = HllSketch::deserialize(ss);
est2 = sk2->getEstimate();
CPPUNIT_ASSERT_DOUBLES_EQUAL(est2, est1, 0.0);
delete sk1;
delete sk2;
}
void checkSerializeDeserialize() {
serializeDeserialize(7);
serializeDeserialize(21);
}
};
CPPUNIT_TEST_SUITE_REGISTRATION(CouponListTest);
} /* namespace datasketches */
|
d6af8643d295fd39299d35d1d6c0eed7969839e2 | 170ab6daedec4a8f107203b6eb5cd8bed1f4ed81 | /OJ-51nod/1127 最短的包含字符串.cpp | e825059c1d3a858fb161b75c32eeebf73aa79a7a | [] | no_license | sfailsthy/ACM-ICPC | 4a15930c06c5ba35ca54a5ecb0acd7de63ebe7f7 | 7e32bfc49010c55d24b68c074c800a2d492abbfd | refs/heads/master | 2021-01-11T06:07:58.598819 | 2017-01-18T13:04:23 | 2017-01-18T13:04:23 | 71,685,224 | 3 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 845 | cpp | 1127 最短的包含字符串.cpp | //created by sfailsthy 2016/12/12 1:16
#include <iostream>
#include <set>
#include <cstdio>
#include <string>
#include <cstring>
#include <algorithm>
#include <map>
using namespace std;
const int maxn =100000+10;
char str[maxn];
void solve(){
set<char> all;
for(int i=0;str[i]!='\0';i++){
all.insert(str[i]);
}
if(all.size()<26){
printf("No Solution\n");
return;
}
int n=strlen(str);
int s=0,t=0,res=n+1,num=0;
map<char,int> cnt;
for(;;){
while(t<n&&num<26){
if(cnt[str[t++]]++==0){
num++;
}
}
if(num<26){
break;
}
res=min(res,t-s);
if(--cnt[str[s++]]==0){
num--;
}
}
printf("%d\n",res);
}
int main(){
scanf("%s",str);
solve();
return 0;
}
|
e03fb190632920cae532f35b279e1706836c3af6 | c542fa61ff421b5da5bfae287329798294f3dfd8 | /bubble_sort.cpp | 64f7a5ea433d75a88e3392ae352175170c643994 | [] | no_license | Poorab-Shenoy/DATA-STRUCTURES | 125d17f732122495b95318ee8cbaf7798dc038a7 | edf37bb56d2681295d4fd45f36203d14e77fce30 | refs/heads/master | 2023-05-10T14:18:54.571238 | 2021-06-11T12:31:48 | 2021-06-11T12:31:48 | 376,015,655 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,015 | cpp | bubble_sort.cpp | #include <bits/stdc++.h>
using namespace std;
void bubble_Sort(int a[], int n)
{
int flag = 0;
for(int i =0; i<n-1; i++)
{
for(int j=0; j<n-1-i; j++) // we want to eliminate that comparison
{
if(a[j]>a[j+1]) /// bubble sort compares two element 1st one and second one
///second one and third so on so the largest element will be at the end of the array in the first parse
{ // bubble sort is also stable means if there are duplicate it can be used to identify
flag =1;
swap(a[j],a[j+1]);
}
}
if(flag = 0)
{
cout << "the list is already sorted";
}
}
}
int main(){
int a[] = {3,2,4,1,6};
int n = sizeof(a)/sizeof(a[0]);
bubble_Sort(a,n);
for(int i=0; i<n; i++)
{
cout << a[i];
}
} |
ee4d65c2c0ba9aad068bb6cef65bb0f7dfdb8563 | 3874989396b41ec423b2878253633f303edd5656 | /src/actors/FlyingMonster.h | fd42681ed3053d9957a5590805171a93f6d3932c | [] | no_license | joetde/SuperBadbar | 7477e2fb6d662676ce70795f9d1287df65eb6023 | 7f0e09a57bc9754522588f1015363b1f1d0e046e | refs/heads/master | 2021-01-01T17:05:43.711037 | 2014-02-20T13:17:09 | 2014-02-20T13:17:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 861 | h | FlyingMonster.h | /**
* @file WalkingMonster.h
* @brief Header de la classe FlyingMonster
*
* @author Guillaume Berard & Benoit Morel
* @date decembre 2010
*
*/
#ifndef _FlyingMonster_
#define _FlyingMonster_
#include <actors/Monster.h>
class Analyser;
/**
* @class FlyingMonster
* @brief Monstre qui vole
*
*/
class FlyingMonster : public Monster
{
private:
int m_high_min;
public:
/**
* @brief Constructeur
* @param name Le nom du monstre
* @param posx Position initiale
* @param posy Position initiale
*/
FlyingMonster (std::string name, int posx, int posy);
/**
* @brief Constructeur
* @param analyserLevel Analyseur du level avec curseur devant le monstre a ajouter
*/
FlyingMonster (Analyser *analyserLevel);
/**
* @brief Destructeur
*/
~FlyingMonster();
};
#endif
|
0e90ac67e90089bf9f36437190ecfe777aeae835 | 89c5fac3c3eb3cc7cfcc22424ec2c565a09f9fc8 | /src/crypto/keccak256.cpp | 514ecb71b7c6a29c65931cdad12aef12d00c46d9 | [
"MIT"
] | permissive | harkal/dash | 5745acd4a47a198da4f0fa147e0d15c35127c2ff | d871d02f99a151e4e1195ccb1e85be563612b5d8 | refs/heads/master | 2021-05-08T09:52:03.410289 | 2018-01-11T22:30:50 | 2018-01-11T22:44:15 | 107,180,062 | 2 | 0 | null | 2017-10-16T20:35:13 | 2017-10-16T20:35:12 | null | UTF-8 | C++ | false | false | 727 | cpp | keccak256.cpp | // Copyright (c) 2017 Harry Kalogirou (harkal@gmail.com)
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "crypto/keccak256.h"
#include "crypto/common.h"
CKeccak256::CKeccak256()
{
sph_keccak256_init(&cc);
}
CKeccak256& CKeccak256::Write(const Byte* data, size_t len)
{
sph_keccak256(&cc, data, len);
return *this;
}
void CKeccak256::Finalize(Byte hash[OUTPUT_SIZE])
{
sph_keccak256_close(&cc, hash);
}
H256 CKeccak256::Finalize()
{
Byte hash[OUTPUT_SIZE];
Finalize(hash);
H256 ret(hash);
return ret;
}
CKeccak256& CKeccak256::Reset()
{
sph_keccak256_init(&cc);
return *this;
}
|
958872e3370f56f2d1f2d536682c7f75cd82ba28 | 059ee9205cfe4ed153b873870d82ebd43ddfea38 | /BOJ7576.cpp | cfbbe845da8bae0034051d2c264f1ce536bbb575 | [] | no_license | muzee99/Baekjoon_cpp | c09befd3f8d2b1a575645cac153d11ada38adf8c | 2d8b4ef234f848f192df37cc04d3443dc5b1f1eb | refs/heads/master | 2023-08-31T02:14:10.921211 | 2021-09-15T08:24:13 | 2021-09-15T08:24:13 | 345,878,300 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 395 | cpp | BOJ7576.cpp | #include <bits/stdc++.h>
using namespace std;
int N,M;
int box[1001][1001];
int chk[1001][1001];
int isInBox(int r, int c);
int main() {
ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
cin >> N >> M;
for(int i=0; i<N; i++) {
for(int j=0; j<M; j++) {
cin >> box[i][j];
}
}
}
int isInBox(int r, int c) {
return r>=0 && r<N && c>=0 && c<M;
}
|
18196196b7facd817e6ae6a6d871f797a7edc56c | c48ec32b65ec2a83ee3502e1aed3028f1544b08d | /3DHomeEngine/src/main/jni/src/ParticleSystem/SE_ParticleIterator.h | 9ce09739089bddb786a2a6723ac7cccc781fbc13 | [] | no_license | 3DHome/3DHome | 76e915b0dc4a9861b9dd0928d63a0cfb451f00d5 | bb8cafc233e672029f68da103d9c236457940f43 | refs/heads/master | 2021-01-20T00:56:49.582553 | 2019-03-09T09:34:11 | 2019-03-13T13:53:26 | 26,866,756 | 34 | 23 | null | 2014-12-09T10:30:15 | 2014-11-19T15:09:55 | C++ | UTF-8 | C++ | false | false | 961 | h | SE_ParticleIterator.h | #ifndef __ParticleIterator_H__
#define __ParticleIterator_H__
#include <list>
class Particle;
/** Convenience class to make it easy to step through all particles in a ParticleSystem.
*/
class SE_ENTRY ParticleIterator
{
friend class ParticleSystem;
protected:
std::list<Particle*>::iterator mPos;
std::list<Particle*>::iterator mStart;
std::list<Particle*>::iterator mEnd;
// Protected constructor, only available from ParticleSystem::getIterator
ParticleIterator(std::list<Particle*>::iterator start, std::list<Particle*>::iterator end)
{
mStart = mPos = start;
mEnd = end;
}
public:
// Returns true when at the end of the particle list
bool end(void)
{
return (mPos == mEnd);
}
/** Returns a pointer to the next particle, and moves the iterator on by 1 element. */
Particle* getNext(void)
{
return static_cast<Particle*>(*mPos++);
}
};
#endif
|
ff421fe976bd4c674fe1f9513ed67d37a1cdec40 | 6597f190861529d9de1dedbffefd9a7886feac46 | /bsafile/srbsafolder.h | ed1c06a5c85511a78ecb3eebcc49a1912bf0294d | [
"MIT"
] | permissive | Blitz54/tes5lib | 87923c1f4675d0de36a038081e327bd8e2a5734a | 07b052983f2e26b9ba798f234ada00f83c90e9a4 | refs/heads/master | 2023-03-16T00:32:31.592231 | 2020-04-02T18:21:19 | 2020-04-02T18:21:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,688 | h | srbsafolder.h | /*===========================================================================
*
* File: Srbsafolder.H
* Author: Dave Humphrey (dave@uesp.net)
* Created On: 26 November 2011
*
* Description
*
*=========================================================================*/
#ifndef __SRBSAFOLDER_H
#define __SRBSAFOLDER_H
/*===========================================================================
*
* Begin Required Includes
*
*=========================================================================*/
#include "srbsafilerecord.h"
/*===========================================================================
* End of Required Includes
*=========================================================================*/
/*===========================================================================
*
* Begin Type Definitions
*
*=========================================================================*/
#pragma pack(push, 1)
/* BSA file header */
struct srbsafolderheader_t
{
int64 NameHash;
dword FileCount;
dword Offset;
};
#pragma pack(pop)
/* Used to iterate through files */
struct BSAPOSITION
{
int FolderIndex;
int FileIndex;
};
/*===========================================================================
* End of Type Definitions
*=========================================================================*/
/*===========================================================================
*
* Begin Class CSrBsaFolder Definition
*
*=========================================================================*/
class CSrBsaFolder {
/*---------- Begin Protected Class Members --------------------*/
protected:
srbsafolderheader_t m_Header;
CSString m_FolderName;
CSrBsaFileRecArray m_Files;
CSrBsaFile* m_pBsaFile; /* Parent file */
/*---------- Begin Protected Class Methods --------------------*/
protected:
/* Helper input/output methods */
bool ReadHeader (CSrFile& File);
bool WriteHeader (CSrFile& File);
bool ReadFiles (CSrFile& File);
bool WriteFiles (CSrFile& File);
/*---------- Begin Public Class Methods -----------------------*/
public:
/* Class Constructors/Destructors */
CSrBsaFolder();
virtual ~CSrBsaFolder() { Destroy(); }
virtual void Destroy (void);
/* Get class members */
dword GetOffset (void) { return (m_Header.Offset); }
const char* GetFolderName (void) { return (m_FolderName); }
dword GetFolderNameSize (void) { return (m_FolderName.GetLength()); }
CSrBsaFile* GetBsaFile (void) { return (m_pBsaFile); }
dword64 GetFiletime (void);
/* Iterate through records */
CSrBsaFileRecord* GetNextFile (BSAPOSITION& Position);
/* Set class members */
void SetOffset (const dword Value) { m_Header.Offset = Value; }
void SetBsaFile (CSrBsaFile* pFile) { m_pBsaFile = pFile; }
/* Input/output the folder data */
bool Read (CSrFile& File);
bool Write (CSrFile& File);
bool ReadContents (CSrFile& File);
bool WriteContents (CSrFile& File);
};
/* Array of folder pointers */
typedef CSrPtrArray<CSrBsaFolder> CSrBsaFolderRecord;
/*===========================================================================
* End of Class CSrBsaFolder Definition
*=========================================================================*/
#endif
/*===========================================================================
* End of File Srbsafolder.H
*=========================================================================*/
|
4354ae4b6d5ff40f871c3b8f781ee48ea8d71381 | ef187d259d33e97c7b9ed07dfbf065cec3e41f59 | /work/atcoder/arc/arc089/D/answers/000259_errym.cpp | 65de05cbfd0deb61aef1d0d87b0b8d02d1bbf673 | [] | no_license | kjnh10/pcw | 847f7295ea3174490485ffe14ce4cdea0931c032 | 8f677701bce15517fb9362cc5b596644da62dca8 | refs/heads/master | 2020-03-18T09:54:23.442772 | 2018-07-19T00:26:09 | 2018-07-19T00:26:09 | 134,586,379 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 740 | cpp | 000259_errym.cpp | #include <bits/stdc++.h>
using namespace std;
int cnt[4005][4005];
int n, k, ans;
int main()
{
scanf("%d%d", &n, &k);
for (int i = 0;i < n;i++)
{
int x, y; char c; scanf("%d%d %c", &x, &y, &c);
if (c == 'B') y += k;
x %= (2*k); y %= (2*k);
cnt[x][y]++;
}
for (int i = 0;i < 2*k;i++) for (int j = 0;j < 2*k;j++) cnt[i+2*k][j] = cnt[i][j+2*k] = cnt[i+2*k][j+2*k] = cnt[i][j];
for (int i = 0;i < 4*k;i++) for (int j = 0;j < 4*k;j++) cnt[i][j] += (i?cnt[i-1][j]:0)+(j?cnt[i][j-1]:0)-(i&&j?cnt[i-1][j-1]:0);
for (int i = 0;i < 2*k;i++) for (int j = 0;j < 2*k;j++) ans = max(ans, cnt[i+2*k][j+2*k]-cnt[i+k][j+2*k]-cnt[i+2*k][j+k]+cnt[i+k][j+k]+cnt[i+k][j+k]-cnt[i][j+k]-cnt[i+k][j]+cnt[i][j]);
printf("%d\n", ans);
return 0;
}
|
b9bc4e84dcdc66c100996ce51ef9a7384d352a75 | f39fbc00e7584a3e93f92534ca016fd951110cf1 | /src/v/kafka/server/handlers/describe_transactions.cc | b80a23ca52842c4d72332d84ba8c72e6231b6ed7 | [] | no_license | redpanda-data/redpanda | 93234ff70348d3ed131bdc2d121fc8dcb7bffca9 | bee41676303c0e5fb161256b844bb14a135de8cd | refs/heads/dev | 2023-08-27T21:40:47.107399 | 2023-08-26T11:45:30 | 2023-08-26T11:45:30 | 309,512,982 | 4,297 | 308 | null | 2023-09-14T20:36:21 | 2020-11-02T22:43:36 | C++ | UTF-8 | C++ | false | false | 5,027 | cc | describe_transactions.cc | // Copyright 2020 Redpanda Data, Inc.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.md
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0
#include "kafka/server/handlers/describe_transactions.h"
#include "cluster/errc.h"
#include "cluster/tx_gateway_frontend.h"
#include "kafka/protocol/errors.h"
#include "kafka/protocol/schemata/describe_transactions_request.h"
#include "kafka/protocol/types.h"
#include "kafka/server/handlers/details/security.h"
#include "kafka/server/request_context.h"
#include "kafka/server/response.h"
#include "model/fundamental.h"
#include "model/namespace.h"
#include "resource_mgmt/io_priority.h"
#include <seastar/core/coroutine.hh>
#include <seastar/core/when_all.hh>
#include <chrono>
#include <unordered_map>
namespace kafka {
namespace {
ss::future<> fill_info_about_tx(
cluster::tx_gateway_frontend& tx_frontend,
describe_transactions_response& response,
kafka::transactional_id tx_id) {
describe_transaction_state tx_info_resp;
tx_info_resp.transactional_id = tx_id;
auto tx_info = co_await tx_frontend.describe_tx(tx_id);
if (tx_info.has_value()) {
auto tx = tx_info.value();
tx_info_resp.producer_id = kafka::producer_id(tx.pid.id);
tx_info_resp.producer_epoch = tx.pid.get_epoch();
tx_info_resp.transaction_state = ss::sstring(tx.get_kafka_status());
tx_info_resp.transaction_timeout_ms = tx.get_timeout() / 1ms;
// RP doesn't store transaction_start_time so we use last_update
// insteadget_timeout
tx_info_resp.transaction_start_time_ms
= tx.last_update_ts.time_since_epoch() / 1ms;
std::unordered_map<model::topic, std::vector<model::partition_id>>
partitions;
for (const auto& ntp : tx.partitions) {
partitions[ntp.ntp.tp.topic].push_back(ntp.ntp.tp.partition);
}
for (const auto& [topic, partitions] : partitions) {
topic_data topic_info;
topic_info.topic = topic;
for (auto& partition : partitions) {
topic_info.partitions.push_back(partition);
}
tx_info_resp.topics.push_back(std::move(topic_info));
}
} else {
switch (tx_info.error()) {
case cluster::tx_errc::not_coordinator:
case cluster::tx_errc::partition_not_found:
case cluster::tx_errc::stm_not_found:
tx_info_resp.error_code = kafka::error_code::not_coordinator;
break;
case cluster::tx_errc::tx_id_not_found:
tx_info_resp.error_code
= kafka::error_code::transactional_id_not_found;
break;
default:
vlog(
klog.warn,
"Can not find transaction with tx_id:({}) for "
"describe_transactions request. Got error (tx_errc): {}",
tx_id,
tx_info.error());
tx_info_resp.error_code = kafka::error_code::unknown_server_error;
break;
}
}
response.data.transaction_states.push_back(std::move(tx_info_resp));
}
ss::future<> fill_info_about_transactions(
cluster::tx_gateway_frontend& tx_frontend,
describe_transactions_response& response,
std::vector<kafka::transactional_id> tx_ids) {
return ss::max_concurrent_for_each(
tx_ids, 32, [&response, &tx_frontend](const auto tx_id) -> ss::future<> {
return fill_info_about_tx(tx_frontend, response, tx_id);
});
}
} // namespace
template<>
ss::future<response_ptr> describe_transactions_handler::handle(
request_context ctx, ss::smp_service_group) {
describe_transactions_request request;
request.decode(ctx.reader(), ctx.header().version);
log_request(ctx.header(), request);
describe_transactions_response response;
auto unauthorized_it = std::partition(
request.data.transactional_ids.begin(),
request.data.transactional_ids.end(),
[&ctx](const kafka::transactional_id& tx_id) {
return ctx.authorized(security::acl_operation::describe, tx_id);
});
std::vector<kafka::transactional_id> unauthorized(
std::make_move_iterator(unauthorized_it),
std::make_move_iterator(request.data.transactional_ids.end()));
request.data.transactional_ids.erase(
unauthorized_it, request.data.transactional_ids.end());
auto& tx_frontend = ctx.tx_gateway_frontend();
co_await fill_info_about_transactions(
tx_frontend, response, std::move(request.data.transactional_ids));
for (auto& tx_id : unauthorized) {
response.data.transaction_states.push_back(describe_transaction_state{
.error_code = error_code::transactional_id_authorization_failed,
.transactional_id = tx_id,
});
}
co_return co_await ctx.respond(std::move(response));
}
} // namespace kafka
|
fd3c0523a35bcb777db006c248f3fe57cb76a21c | 3ff1fe3888e34cd3576d91319bf0f08ca955940f | /cvm/include/tencentcloud/cvm/v20170312/model/InstanceFamilyConfig.h | 8c72d77e27810e17df8f13655c381d46979c74a2 | [
"Apache-2.0"
] | permissive | TencentCloud/tencentcloud-sdk-cpp | 9f5df8220eaaf72f7eaee07b2ede94f89313651f | 42a76b812b81d1b52ec6a217fafc8faa135e06ca | refs/heads/master | 2023-08-30T03:22:45.269556 | 2023-08-30T00:45:39 | 2023-08-30T00:45:39 | 188,991,963 | 55 | 37 | Apache-2.0 | 2023-08-17T03:13:20 | 2019-05-28T08:56:08 | C++ | UTF-8 | C++ | false | false | 4,159 | h | InstanceFamilyConfig.h | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef TENCENTCLOUD_CVM_V20170312_MODEL_INSTANCEFAMILYCONFIG_H_
#define TENCENTCLOUD_CVM_V20170312_MODEL_INSTANCEFAMILYCONFIG_H_
#include <string>
#include <vector>
#include <map>
#include <tencentcloud/core/utils/rapidjson/document.h>
#include <tencentcloud/core/utils/rapidjson/writer.h>
#include <tencentcloud/core/utils/rapidjson/stringbuffer.h>
#include <tencentcloud/core/AbstractModel.h>
namespace TencentCloud
{
namespace Cvm
{
namespace V20170312
{
namespace Model
{
/**
* 描述实例的机型族配置信息
形如:{'InstanceFamilyName': '标准型S1', 'InstanceFamily': 'S1'}、{'InstanceFamilyName': '网络优化型N1', 'InstanceFamily': 'N1'}、{'InstanceFamilyName': '高IO型I1', 'InstanceFamily': 'I1'}等。
*/
class InstanceFamilyConfig : public AbstractModel
{
public:
InstanceFamilyConfig();
~InstanceFamilyConfig() = default;
void ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const;
CoreInternalOutcome Deserialize(const rapidjson::Value &value);
/**
* 获取机型族名称的中文全称。
* @return InstanceFamilyName 机型族名称的中文全称。
*
*/
std::string GetInstanceFamilyName() const;
/**
* 设置机型族名称的中文全称。
* @param _instanceFamilyName 机型族名称的中文全称。
*
*/
void SetInstanceFamilyName(const std::string& _instanceFamilyName);
/**
* 判断参数 InstanceFamilyName 是否已赋值
* @return InstanceFamilyName 是否已赋值
*
*/
bool InstanceFamilyNameHasBeenSet() const;
/**
* 获取机型族名称的英文简称。
* @return InstanceFamily 机型族名称的英文简称。
*
*/
std::string GetInstanceFamily() const;
/**
* 设置机型族名称的英文简称。
* @param _instanceFamily 机型族名称的英文简称。
*
*/
void SetInstanceFamily(const std::string& _instanceFamily);
/**
* 判断参数 InstanceFamily 是否已赋值
* @return InstanceFamily 是否已赋值
*
*/
bool InstanceFamilyHasBeenSet() const;
private:
/**
* 机型族名称的中文全称。
*/
std::string m_instanceFamilyName;
bool m_instanceFamilyNameHasBeenSet;
/**
* 机型族名称的英文简称。
*/
std::string m_instanceFamily;
bool m_instanceFamilyHasBeenSet;
};
}
}
}
}
#endif // !TENCENTCLOUD_CVM_V20170312_MODEL_INSTANCEFAMILYCONFIG_H_
|
8d6b545a9adfca31ceee16244bb88e9d1d4f6732 | 2933025b55b34ccf0242de29c41c71a119bfb819 | /1. Placements/1. Misc/44. StoneGame.cpp | 74aedd0028c0e796ec77ea83d3d8a15950a0d493 | [] | no_license | rohitshakya/CodeBucket | 460050cf3cb5ae29eac0b92fb15ddc7a5a9d9d80 | 5c3632d5860873c74cce850eb33bd89fdd77ce0a | refs/heads/master | 2022-01-25T09:55:58.151327 | 2022-01-11T06:55:05 | 2022-01-11T06:55:05 | 253,870,196 | 2 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 459 | cpp | 44. StoneGame.cpp | /*
* Author : Rohit Shakya
* Date : June-2020
* Compiler : g++ 4.9.2
* Flags : -std=c++14
* Time complexity : O(1)
* Title : StoneGame
*/
#include<iostream>
using namespace std;
int main()
{
int t;
cout<<"enter the number of test cases"<<endl;
cin>>t;
while(t--)
{
int n;
cout<<"enter the number of stones"<<endl;
cin>>n;
if(n%5==0||n%5==2)
{
cout<<"NO"<<endl;
}
else
cout<<"Yes"<<endl;
}
}
|
d3e2c7369c87e147fced2ef64d3b0b570fbe9d2a | ba2b37e3be216c87877e212b13639f839cc857f5 | /src/LCM/evaluators/MechanicsResidual_Def.hpp | dfc2b0878711719c9a4abd70d152bf006d72ba78 | [
"BSD-2-Clause"
] | permissive | stvsun/Albany | ac1e8dbb27823f9a5b357aa041a37b1eca494548 | 7971bb6951b868f7029fe11cbb0898d351ae4a1d | refs/heads/master | 2022-04-29T20:51:55.453554 | 2022-03-26T21:22:21 | 2022-03-26T21:22:21 | 19,159,626 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,897 | hpp | MechanicsResidual_Def.hpp | //*****************************************************************//
// Albany 2.0: Copyright 2012 Sandia Corporation //
// This Software is released under the BSD license detailed //
// in the file "license.txt" in the top-level Albany directory //
//*****************************************************************//
#include <Intrepid_MiniTensor_Mechanics.h>
#include <Teuchos_TestForException.hpp>
#include <Phalanx_DataLayout.hpp>
#include <Sacado_ParameterRegistration.hpp>
namespace LCM
{
//------------------------------------------------------------------------------
template<typename EvalT, typename Traits>
MechanicsResidual<EvalT, Traits>::
MechanicsResidual(Teuchos::ParameterList& p,
const Teuchos::RCP<Albany::Layouts>& dl) :
stress_(p.get<std::string>("Stress Name"), dl->qp_tensor),
w_grad_bf_(p.get<std::string>("Weighted Gradient BF Name"),
dl->node_qp_vector),
w_bf_(p.get<std::string>("Weighted BF Name"), dl->node_qp_scalar),
residual_(p.get<std::string>("Residual Name"), dl->node_vector),
have_body_force_(false),
density_(p.get<RealType>("Density", 1.0))
{
this->addDependentField(stress_);
this->addDependentField(w_grad_bf_);
this->addDependentField(w_bf_);
this->addEvaluatedField(residual_);
if (p.isType<bool>("Disable Dynamics"))
enable_dynamics_ = !p.get<bool>("Disable Dynamics");
else enable_dynamics_ = true;
if (enable_dynamics_) {
PHX::MDField<ScalarT,Cell,QuadPoint,Dim> tmp
(p.get<std::string>("Acceleration Name"), dl->qp_vector);
acceleration_ = tmp;
this->addDependentField(acceleration_);
}
this->setName("MechanicsResidual" + PHX::TypeString<EvalT>::value);
if (have_body_force_) {
// grab the pore pressure
PHX::MDField<ScalarT, Cell, QuadPoint, Dim>
tmp(p.get<std::string>("Body Force Name"), dl->qp_vector);
body_force_ = tmp;
this->addDependentField(body_force_);
}
std::vector<PHX::DataLayout::size_type> dims;
w_grad_bf_.fieldTag().dataLayout().dimensions(dims);
num_nodes_ = dims[1];
num_pts_ = dims[2];
num_dims_ = dims[3];
Teuchos::RCP<ParamLib> paramLib =
p.get<Teuchos::RCP<ParamLib> >("Parameter Library");
}
//------------------------------------------------------------------------------
template<typename EvalT, typename Traits>
void MechanicsResidual<EvalT, Traits>::
postRegistrationSetup(typename Traits::SetupData d,
PHX::FieldManager<Traits>& fm)
{
this->utils.setFieldData(stress_, fm);
this->utils.setFieldData(w_grad_bf_, fm);
this->utils.setFieldData(w_bf_, fm);
this->utils.setFieldData(residual_, fm);
if (have_body_force_) {
this->utils.setFieldData(body_force_, fm);
}
if (enable_dynamics_) {
this->utils.setFieldData(acceleration_, fm);
}
}
//------------------------------------------------------------------------------
template<typename EvalT, typename Traits>
void MechanicsResidual<EvalT, Traits>::
evaluateFields(typename Traits::EvalData workset)
{
//std::cout.precision(15);
// initilize Tensors
// Intrepid::Tensor<ScalarT> F(num_dims_), P(num_dims_), sig(num_dims_);
// Intrepid::Tensor<ScalarT> I(Intrepid::eye<ScalarT>(num_dims_));
// for large deformation, map Cauchy stress to 1st PK stress
for (std::size_t cell = 0; cell < workset.numCells; ++cell) {
for (std::size_t node = 0; node < num_nodes_; ++node) {
for (std::size_t dim = 0; dim < num_dims_; ++dim) {
residual_(cell, node, dim) = 0.0;
}
}
for (std::size_t pt = 0; pt < num_pts_; ++pt) {
for (std::size_t node = 0; node < num_nodes_; ++node) {
for (std::size_t i = 0; i < num_dims_; ++i) {
for (std::size_t j = 0; j < num_dims_; ++j) {
residual_(cell, node, i) +=
stress_(cell, pt, i, j) * w_grad_bf_(cell, node, pt, j);
}
}
}
}
}
// optional body force
if (have_body_force_) {
for (std::size_t cell = 0; cell < workset.numCells; ++cell) {
for (std::size_t node = 0; node < num_nodes_; ++node) {
for (std::size_t pt = 0; pt < num_pts_; ++pt) {
for (std::size_t dim = 0; dim < num_dims_; ++dim) {
residual_(cell, node, dim) +=
w_bf_(cell, node, pt) * body_force_(cell, pt, dim);
}
}
}
}
}
// dynamic term
if (workset.transientTerms && enable_dynamics_) {
for (std::size_t cell=0; cell < workset.numCells; ++cell) {
for (std::size_t node=0; node < num_nodes_; ++node) {
for (std::size_t pt=0; pt < num_pts_; ++pt) {
for (std::size_t dim=0; dim < num_dims_; ++dim) {
residual_(cell,node,dim) += density_ *
acceleration_(cell,pt,dim) * w_bf_(cell,node,pt);
}
}
}
}
}
}
//------------------------------------------------------------------------------
}
|
3d6c4a6bbb345f68f25c17eafa6695cb317a4dec | 5448b70fca0952bca46443aba0ccf2a9cddbc373 | /datastructure/mo's-algo.cpp | 933b258b017f571c5d57fc96775d61b381e06ea4 | [] | no_license | Tahanima/algorithms-datastructures-codebook | a4060eb3e63ff080b78428cca978e9ac7a5d51fb | 21e8d2e4d01d282a3793001de64829b555fab537 | refs/heads/master | 2021-01-23T10:45:00.306288 | 2017-07-14T13:21:29 | 2017-07-14T13:21:29 | 93,091,411 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,798 | cpp | mo's-algo.cpp | #include <bits/stdc++.h>
using namespace std;
/**********************************************************************************************
Given an array of N integers and Q queries. For each query of type l r, the number of distinct
numbers from indices l to r should be outputted.
Input:
8 5 -----------------------> N Q
1 2 3 3 1 2 4 2 -----------> N numbers
1 4 |
3 8 |
2 4 |---------------------> Q queries
7 8 |
3 6 |
Output:
3
4
2
2
3
**********************************************************************************************/
#define f first
#define s second
const int MX = 1e6 + 10;
typedef pair<int,int> pii;
typedef pair<pii,int> piii;
int N, Q, current_answer, BLOCK_SZ;
int cnt[MX], ans[MX], arr[MX];
piii queries[MX];
bool comp(piii x, piii y){
int block_x = x.f.f/BLOCK_SZ;
int block_y = y.f.f/BLOCK_SZ;
return (block_x != block_y) ? block_x < block_y : x.f.s < y.f.s;
}
void add(int x){
cnt[x]++;
if(cnt[x] == 1) current_answer++;
}
void remove(int x){
cnt[x]--;
if(cnt[x] == 0) current_answer--;
}
int main(){
int a, b;
cin >> N >> Q;
BLOCK_SZ = sqrt(N);
for(int i = 0; i < N; i++){
cin >> arr[i];
}
for(int i = 0; i < Q; i++){
cin >> a >> b;
queries[i].f.f = --a;
queries[i].f.s = --b;
queries[i].s = i;
}
sort(queries, queries + Q, comp);
int mo_left = 0, mo_right = -1;
for(int i = 0; i < Q; i++){
int left = queries[i].f.f;
int right = queries[i].f.s;
for(; mo_right < right ; mo_right++, add(arr[mo_right]));
for(; mo_right > right ; remove(arr[mo_right]), mo_right--);
for(; mo_left < left ; remove(arr[mo_left]), mo_left++);
for(; mo_left > left ; mo_left--, add(arr[mo_left]));
ans[queries[i].s] = current_answer;
}
for(int i = 0; i < Q; i++) cout << ans[i] << endl;
return 0;
} |
3e0ef52688a213e0c899b1d3d55e7939a6c4f839 | 7a6e612c7182d72a3fc1721a173ad9a592eb6b29 | /Utils/CalibratorTool/Synchronization.h | 3553aa3580763008bfdd1f5e8413273eb63d5db7 | [] | no_license | pablocano/mundosvirtuales-BanknoteClassifier | 034766be40be9cdc4237e1d98fcf2b1d12a6c91f | f2718acda441baf3d68fd769552a7462a879c474 | refs/heads/master | 2021-03-16T06:06:36.117636 | 2019-04-10T16:00:08 | 2019-04-10T16:00:08 | 103,450,373 | 0 | 0 | null | 2019-04-10T16:00:09 | 2017-09-13T21:04:39 | C++ | UTF-8 | C++ | false | false | 1,534 | h | Synchronization.h | //
// Synchronization.h
// GroundTruth
//
// Created by Pablo Cano Montecinos on 06-09-16.
//
//
#pragma once
#include <QMutex>
class SyncObject
{
public:
QMutex mutex;
void enter() {mutex.lock();}
void leave() {mutex.unlock();}
};
class Sync
{
private:
SyncObject& syncObject;
public:
/**
* Constructor.
* @param s A reference to a sync object representing a critical
* section. The section is entered.
*/
Sync(SyncObject& s) : syncObject(s) {syncObject.enter();}
/**
* Destructor.
* The critical section is left.
*/
~Sync() {syncObject.leave();}
};
/**
* The macro places a SyncObject as member variable into a class.
* This is the precondition for using the macro SYNC.
*/
#define DECLARE_SYNC mutable SyncObject _syncObject
/**
* The macro SYNC ensures that the access to member variables is synchronized.
* So only one thread can enter a SYNC block for this object at the same time.
* The SYNC is automatically released at the end of the current code block.
* Never nest SYNC blocks, because this will result in a deadlock!
*/
#define SYNC Sync _sync(_syncObject)
/**
* The macro SYNC_WITH ensures that the access to the member variables of an
* object is synchronized. So only one thread can enter a SYNC block for the
* object at the same time. The SYNC is automatically released at the end of
* the current code block. Never nest SYNC blocks, because this will result
* in a deadlock!
*/
#define SYNC_WITH(obj) Sync _sync((obj)._syncObject)
|
b4acc50e3479d7cb3e0658d94fcbfd3fd360706a | 1acacc4a1428e6b63c3ab7c846a0b67fe4d92cd6 | /HouseCamera/Camera.h | 8fa2db668bfbab2c56a9fe9d18a9089c1b43dde5 | [] | no_license | louis1204/HouseCamera | 46a38bfbdd61dbe658a01aa885f556cf655d7bdc | a17f891471aea91d15021587e0b81fe32c80e427 | refs/heads/master | 2020-06-08T20:14:43.938628 | 2014-03-14T04:01:18 | 2014-03-14T04:01:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 386 | h | Camera.h | #pragma once
#include "Vector3.h"
#include "Matrix4.h"
#include <GL/glut.h>
class Camera
{
protected:
Vector3 e; //center of projection
Vector3 d; //object looking at
Vector3 up; //(unit?) vector looking up
public:
Matrix4 c; //internal camera matrix
Camera();
Camera(Vector3 e, Vector3 d, Vector3 up);
~Camera(void);
Matrix4& getGLMatrix();
void spin(double);
};
|
f3423839466ae97169a4abf92fd6689cd79dd318 | 1bef2b315dc18cf10caf1fc9d1f03f055a8abf28 | /구현/SW_1949.cpp | f1272554e74eef734df6744c2064535d6eacc34d | [] | no_license | woongseob12/Algorithm | ffd7fabcc1774135a119153798d3d1e93ddd781a | 87d0bf3796780ffdec1e1a3a90a4c895ad5bad3d | refs/heads/master | 2023-06-28T10:28:06.006783 | 2021-07-30T13:51:23 | 2021-07-30T13:51:23 | 209,935,509 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,564 | cpp | SW_1949.cpp | #include <iostream>
#include <algorithm>
#include <cstring>
#define MAX 8
using namespace std;
int N, K, ans;
bool cut;
int arr[MAX][MAX];
bool visit[MAX][MAX];
int dy[] = { 1, -1, 0, 0 };
int dx[] = { 0, 0, 1, -1 };
void dfs(int y, int x, int cnt);
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int TC;
cin >> TC;
for (int t = 1; t <= TC; t++) {
cin >> N >> K;
int maxH = 0;
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
cin >> arr[i][j];
maxH = max(maxH, arr[i][j]);
}
}
memset(visit, false, sizeof(visit));
ans = 0;
cut = true;
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (arr[i][j] == maxH && !visit[i][j]) {
visit[i][j] = true;
dfs(i, j, 1);
visit[i][j] = false;
}
}
}
cout << "#" << t << " " << ans << "\n";
}
}
void dfs(int y, int x, int cnt) {
for (int i = 0; i < 4; i++) {
int ny = y + dy[i];
int nx = x + dx[i];
if (ny < 0 || nx < 0 || ny >= N || nx >= N) { continue; }
if (visit[ny][nx]) { continue; }
if (arr[y][x] > arr[ny][nx]) {
visit[ny][nx] = true;
dfs(ny, nx, cnt + 1);
visit[ny][nx] = false;
}
if (cut && arr[y][x] <= arr[ny][nx]) {
cut = false;
visit[ny][nx] = true;
for (int d = 1; d <= K; d++) {
if (arr[ny][nx] - d < arr[y][x]) {
arr[ny][nx] -= d;
dfs(ny, nx, cnt + 1);
arr[ny][nx] += d;
}
}
visit[ny][nx] = false;
cut = true;
}
}
ans = max(ans, cnt);
}
|
6597901092882908e3992dc63bbf33011def9636 | 7a28a00bd395977d2004361b480c5c9c226b06b0 | /nebulosity4/manual_color_camera.cpp | 74f73843379b035d6571894d9b2d6ad9e515a926 | [
"BSD-3-Clause"
] | permissive | supritsingh/OpenNebulosity | 99d3b037ec33a66bf079643d536790d85daa64b8 | fa5cc91aec0cbb9e8cac7fdc434d617b02ee8175 | refs/heads/main | 2023-08-27T19:47:35.879790 | 2021-11-07T21:55:11 | 2021-11-07T21:55:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,899 | cpp | manual_color_camera.cpp | /*
BSD 3-Clause License
Copyright (c) 2021, Craig Stark
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER 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.
*/
#include "precomp.h"
#include "Nebulosity.h"
#include "camera.h"
class ManualColorDialog: public wxDialog {
public:
wxRadioBox *ArrayBox;
wxTextCtrl *XPixelSizeCtrl;
wxTextCtrl *YPixelSizeCtrl;
wxSpinCtrl *XOffsetCtrl;
wxSpinCtrl *YOffsetCtrl;
wxTextCtrl *RR;
wxTextCtrl *RG;
wxTextCtrl *RB;
wxTextCtrl *GR;
wxTextCtrl *GG;
wxTextCtrl *GB;
wxTextCtrl *BR;
wxTextCtrl *BG;
wxTextCtrl *BB;
ManualColorDialog();
~ManualColorDialog(void) {};
};
ManualColorDialog::ManualColorDialog():
wxDialog(frame, wxID_ANY, _T("Manual Demosaic Setup"), wxPoint(-1,-1), wxSize(-1,-1), wxCAPTION | wxCLOSE_BOX) {
//int box_xsize = 160;
wxSize FieldSize = wxSize(GetFont().GetPixelSize().y * 3, -1);
wxBoxSizer *TopSizer = new wxBoxSizer(wxHORIZONTAL);
wxBoxSizer *LeftSizer = new wxBoxSizer(wxVERTICAL);
wxBoxSizer *RightSizer = new wxBoxSizer(wxVERTICAL);
// Left side
wxString array_choices[] = { _T("RGB"), _T("CMYG") };
ArrayBox = new wxRadioBox(this,wxID_ANY,_T("Array Type"),wxDefaultPosition,wxDefaultSize,WXSIZEOF(array_choices), array_choices);
LeftSizer->Add(ArrayBox,wxSizerFlags(0).Expand().Border(wxALL,5));
wxStaticBoxSizer *PixelSizeSizer = new wxStaticBoxSizer(wxHORIZONTAL, this, _("Pixel size"));
PixelSizeSizer->Add( new wxStaticText(this,wxID_ANY,_T("X"),wxDefaultPosition,wxDefaultSize),wxSizerFlags(1).Expand().Right().Border(wxTOP,2));
XPixelSizeCtrl = new wxTextCtrl(this,wxID_ANY,_T("1.0"),wxDefaultPosition,FieldSize);
PixelSizeSizer->Add(XPixelSizeCtrl,wxSizerFlags(0).Expand().Left());
PixelSizeSizer->AddStretchSpacer(1);
PixelSizeSizer->Add(new wxStaticText(this,wxID_ANY,_T("Y"),wxDefaultPosition,wxDefaultSize),wxSizerFlags(1).Expand().Right().Border(wxTOP,2));
YPixelSizeCtrl = new wxTextCtrl(this,wxID_ANY,_T("1.0"),wxDefaultPosition,FieldSize);
PixelSizeSizer->Add(YPixelSizeCtrl,wxSizerFlags(0).Expand().Left());
LeftSizer->Add(PixelSizeSizer,wxSizerFlags(0).Expand().Border(wxALL,5));
wxStaticBoxSizer *OffsetSizer = new wxStaticBoxSizer(wxHORIZONTAL, this, _("Matrix offset"));
OffsetSizer->Add(new wxStaticText(this,wxID_ANY,_T("X"),wxDefaultPosition,wxDefaultSize));
XOffsetCtrl = new wxSpinCtrl(this,wxID_ANY,_T("0"),wxDefaultPosition,FieldSize,
wxSP_ARROW_KEYS,0,1,0);
OffsetSizer->Add(XOffsetCtrl);
OffsetSizer->AddStretchSpacer(1);
OffsetSizer->Add(new wxStaticText(this,wxID_ANY,_T("Y"),wxDefaultPosition,wxDefaultSize),wxSizerFlags(1).Expand().Right());
YOffsetCtrl = new wxSpinCtrl(this,wxID_ANY,_T("0"),wxDefaultPosition,FieldSize,
wxSP_ARROW_KEYS,0,3,0);
OffsetSizer->Add(YOffsetCtrl,wxSizerFlags(0).Expand());
LeftSizer->Add(OffsetSizer,wxSizerFlags(0).Expand().Border(wxALL,5));
// Right side
// Weighting grid
wxFlexGridSizer *MatrixSizer = new wxFlexGridSizer(4);
MatrixSizer->AddStretchSpacer(1);
MatrixSizer->Add(new wxStaticText(this,wxID_ANY,_T("R"),wxDefaultPosition,wxDefaultSize), wxSizerFlags().Center());
MatrixSizer->Add(new wxStaticText(this,wxID_ANY,_T("G"),wxDefaultPosition,wxDefaultSize), wxSizerFlags().Center());
MatrixSizer->Add(new wxStaticText(this,wxID_ANY,_T("B"),wxDefaultPosition,wxDefaultSize), wxSizerFlags().Center());
MatrixSizer->Add(new wxStaticText(this,wxID_ANY,_T("R"),wxDefaultPosition,wxDefaultSize), wxSizerFlags().Right());
RR = new wxTextCtrl(this,wxID_ANY,_T("1.0"),wxDefaultPosition,FieldSize);
RG = new wxTextCtrl(this,wxID_ANY,_T("0.0"),wxDefaultPosition,FieldSize);
RB = new wxTextCtrl(this,wxID_ANY,_T("0.0"),wxDefaultPosition,FieldSize);
MatrixSizer->Add(RR);
MatrixSizer->Add(RG);
MatrixSizer->Add(RB);
MatrixSizer->Add(new wxStaticText(this,wxID_ANY,_T("G"),wxDefaultPosition,wxDefaultSize), wxSizerFlags().Right());
GR = new wxTextCtrl(this,wxID_ANY,_T("0.0"),wxDefaultPosition,FieldSize);
GG = new wxTextCtrl(this,wxID_ANY,_T("1.0"),wxDefaultPosition,FieldSize);
GB = new wxTextCtrl(this,wxID_ANY,_T("0.0"),wxDefaultPosition,FieldSize);
MatrixSizer->Add(GR);
MatrixSizer->Add(GG);
MatrixSizer->Add(GB);
MatrixSizer->Add(new wxStaticText(this,wxID_ANY,_T("B"),wxDefaultPosition,wxDefaultSize), wxSizerFlags().Right());
BR = new wxTextCtrl(this,wxID_ANY,_T("0.0"),wxDefaultPosition,FieldSize);
BG = new wxTextCtrl(this,wxID_ANY,_T("0.0"),wxDefaultPosition,FieldSize);
BB = new wxTextCtrl(this,wxID_ANY,_T("1.0"),wxDefaultPosition,FieldSize);
MatrixSizer->Add(BR);
MatrixSizer->Add(BG);
MatrixSizer->Add(BB);
wxSizer *ButtonSizer = CreateButtonSizer(wxOK | wxCANCEL);
// RightSizer->AddStretchSpacer(1);
RightSizer->Add(new wxStaticText(this,wxID_ANY,_("Color control")),wxSizerFlags().Center());
RightSizer->Add(MatrixSizer,wxSizerFlags(0).Border(wxALL,5).Center());
RightSizer->AddStretchSpacer(1);
RightSizer->Add(ButtonSizer,wxSizerFlags(1).Expand().Border(wxALL,5));
TopSizer->Add(LeftSizer);
TopSizer->Add(RightSizer);
SetSizerAndFit(TopSizer);
}
bool SetupManualDemosaic(bool do_debayer) {
ManualColorDialog* dlog = new ManualColorDialog;
// Populate with current values
dlog->RR->SetValue(wxString::Format("%.2f",NoneCamera.RR));
dlog->RG->SetValue(wxString::Format("%.2f",NoneCamera.RG));
dlog->RB->SetValue(wxString::Format("%.2f",NoneCamera.RB));
dlog->GR->SetValue(wxString::Format("%.2f",NoneCamera.GR));
dlog->GG->SetValue(wxString::Format("%.2f",NoneCamera.GG));
dlog->GB->SetValue(wxString::Format("%.2f",NoneCamera.GB));
dlog->BR->SetValue(wxString::Format("%.2f",NoneCamera.BR));
dlog->BG->SetValue(wxString::Format("%.2f",NoneCamera.BG));
dlog->BB->SetValue(wxString::Format("%.2f",NoneCamera.BB));
dlog->XOffsetCtrl->SetValue(NoneCamera.DebayerXOffset);
dlog->YOffsetCtrl->SetValue(NoneCamera.DebayerYOffset);
dlog->XPixelSizeCtrl->SetValue(wxString::Format("%.2f",NoneCamera.PixelSize[0]));
dlog->YPixelSizeCtrl->SetValue(wxString::Format("%.2f",NoneCamera.PixelSize[1]));
dlog->ArrayBox->SetSelection(NoneCamera.ArrayType - COLOR_RGB);
if (!do_debayer) {
dlog->RR->Enable(false);
dlog->RG->Enable(false);
dlog->RB->Enable(false);
dlog->GR->Enable(false);
dlog->GG->Enable(false);
dlog->GB->Enable(false);
dlog->BR->Enable(false);
dlog->BG->Enable(false);
dlog->BB->Enable(false);
dlog->XOffsetCtrl->Enable(false);
dlog->YOffsetCtrl->Enable(false);
dlog->ArrayBox->Enable(false);
}
// Put up dialog
if (dlog->ShowModal() != wxID_OK) // Decided to cancel
return true;
// Update values
double val; wxString str;
str = dlog->RR->GetValue(); str.ToDouble(&val); NoneCamera.RR = (float) val;
str = dlog->RG->GetValue(); str.ToDouble(&val); NoneCamera.RG = (float) val;
str = dlog->RB->GetValue(); str.ToDouble(&val); NoneCamera.RB = (float) val;
str = dlog->GR->GetValue(); str.ToDouble(&val); NoneCamera.GR = (float) val;
str = dlog->GG->GetValue(); str.ToDouble(&val); NoneCamera.GG = (float) val;
str = dlog->GB->GetValue(); str.ToDouble(&val); NoneCamera.GB = (float) val;
str = dlog->BR->GetValue(); str.ToDouble(&val); NoneCamera.BR = (float) val;
str = dlog->BG->GetValue(); str.ToDouble(&val); NoneCamera.BG = (float) val;
str = dlog->BB->GetValue(); str.ToDouble(&val); NoneCamera.BB = (float) val;
NoneCamera.DebayerXOffset = dlog->XOffsetCtrl->GetValue();
NoneCamera.DebayerYOffset = dlog->YOffsetCtrl->GetValue();
str = dlog->XPixelSizeCtrl->GetValue(); str.ToDouble(&val); NoneCamera.PixelSize[0] = (float) val;
str = dlog->YPixelSizeCtrl->GetValue(); str.ToDouble(&val); NoneCamera.PixelSize[1] = (float) val;
NoneCamera.ArrayType = dlog->ArrayBox->GetSelection() + COLOR_RGB;
return false;
}
/*
void MyFrame::OnAdvanced(wxCommandEvent& WXUNUSED(event)) {
if (CaptureActive) return; // Looping an exposure already
AdvancedDialog* dlog = new AdvancedDialog();
dlog->RA_Aggr_Ctrl->SetValue((int) (RA_aggr * 100.0));
// dlog->Dec_Aggr_Ctrl->SetValue((int) (Dec_aggr * 100.0));
dlog->RA_Hyst_Ctrl->SetValue((int) (RA_hysteresis * 100.0));
dlog->UseDec_Box->SetValue(Dec_guide);
dlog->Cal_Dur_Ctrl->SetValue(Cal_duration);
dlog->Time_Lapse_Ctrl->SetValue(Time_lapse);
dlog->Gain_Ctrl->SetValue(GuideCameraGain);
if (Calibrated) dlog->Cal_Box->SetValue(false);
else dlog->Cal_Box->SetValue(true);
// dlog->Dec_Backlash_Ctrl->SetValue((int) Dec_backlash);
// dlog->UseDec_Box->Enable(false);
// dlog->Dec_Aggr_Ctrl->Enable(false);
// dlog->Dec_Backlash_Ctrl->Enable(false);
if (dlog->ShowModal() != wxID_OK) // Decided to cancel
return;
if (dlog->Cal_Box->GetValue()) Calibrated=false; // clear calibration
if (!Dec_guide && dlog->UseDec_Box->GetValue()) Calibrated = false; // added dec guiding -- recal
if (!Calibrated) SetStatusText(_T("No cal"),5);
RA_aggr = (double) dlog->RA_Aggr_Ctrl->GetValue() / 100.0;
// Dec_aggr = (double) dlog->Dec_Aggr_Ctrl->GetValue() / 100.0;
RA_hysteresis = (double) dlog->RA_Hyst_Ctrl->GetValue() / 100.0;
Cal_duration = dlog->Cal_Dur_Ctrl->GetValue();
Dec_guide = dlog->UseDec_Box->GetValue();
Time_lapse = dlog->Time_Lapse_Ctrl->GetValue();
GuideCameraGain = dlog->Gain_Ctrl->GetValue();
//Dec_backlash = (double) dlog->Dec_Backlash_Ctrl->GetValue();
}
*/
|
c8cc808d48187f230a62865e1cafd90baf17fab6 | 179c68f0e2a2cbddb795ea9a83441294ae0768e1 | /MyBotLogic/Utils/PathHelper.h | 41afa266128539e0e83f1b36484da07a31f2a47d | [] | no_license | patator62180/IA_project | b3be0a7cfa8b1ae8459d207e9e2fb2a50c8c7883 | 1b1fe58c70e649ff7b819f91803175513b82de0a | refs/heads/master | 2020-03-31T19:03:04.837610 | 2018-10-25T00:18:45 | 2018-10-25T00:18:45 | 152,482,814 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 896 | h | PathHelper.h | #ifndef PATH_HELPER_H
#define PATH_HELPER_H
#include "..\MapStructure\CoordAxial.h"
#include "Globals.h"
#include <vector>
class PathHelper {
static const std::vector<CoordAxial> baseMovement;
public:
static const size_t getDirectionCount() noexcept;
static const HexDirection getReverseDirection(const HexDirection) noexcept;
static const CoordAxial CalculateDirectionPos(const HexDirection) noexcept;
static const CoordAxial CalculatePos(const CoordAxial&, const HexDirection) noexcept;
static const CoordAxial CalculatePosOffset(const CoordAxial&, const HexDirection) noexcept;
static const CoordAxial PathHelper::AxialToOffset(const CoordAxial&) noexcept;
static float DistanceBetween(const CoordAxial&, const CoordAxial&) noexcept;
static unsigned int HexCountBetween(const CoordAxial& cl, const CoordAxial& cr) noexcept;
};
#endif // PATH_HELPER_H |
242af7b43abff9f00a9741cfc33c654b43a3e7b7 | 8b77be32c4422fbc778bf20d6370f5e8514fef96 | /Solution2/ConsoleApplication3/TarCleaner.h | 65fd94234af8540af39863383abafa7ee7dd7595 | [] | no_license | venerjoel99/TarProject | e1c76297f363850f9e99ca11080c3b007bd4218a | df01620a7064fa6970d34ca9db47db1df224f99a | refs/heads/master | 2021-10-09T14:26:08.705217 | 2018-12-29T19:04:07 | 2018-12-29T19:04:07 | 100,327,040 | 12 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 907 | h | TarCleaner.h | #pragma once
#ifndef TARCLEANER_H_INCLUDED
#define TARCLEANER_H_INCLUDED
#include <stdio.h>
class TarCleaner
{
public:
typedef __int64 Integer;
typedef struct _header {
char fileName[100];
int fileSize;
int bufferSize;
Integer headerIndex;
}Header;
private:
FILE *in_file;
FILE *out_file;
Integer tarSize = 0;
int writeNull(int);
int copy(Integer, Integer);
int checkLeak(Integer);
int leaking(Integer);
Header parseHeader(Integer);
Integer findSize(void);
int findStr(const char*, Integer);
int cleanAndCopy();
int checkUstar(Integer);
TarCleaner(const char*, const char*);
TarCleaner();
~TarCleaner();
public:
static int TarCleaner::cleanCopy(const char* input, const char* output) {
TarCleaner *cleaner = new TarCleaner(input, output);
int return_val = cleaner->cleanAndCopy();
delete cleaner;
return return_val;
}
};
#endif
|
2410695f054e2a627d7f601a53c14fdb4818da39 | e042fcaa4f81a33cda9a16ae63b177b7a7d05024 | /CPP/replace charactor.cpp | 8e705dbf2747e158910cb0cc9c402be2f24839f2 | [] | no_license | amanashu201/Aman2002 | 9c4f68a3181bc841b09bb6e18f575b1fc8d79bba | a14d9ebf8e32d62438c953fa1c0d183a3756b07f | refs/heads/master | 2023-04-12T13:32:51.655489 | 2021-05-11T10:30:35 | 2021-05-11T10:30:35 | 306,860,992 | 0 | 0 | null | 2020-10-29T11:57:43 | 2020-10-24T10:40:09 | HTML | UTF-8 | C++ | false | false | 985 | cpp | replace charactor.cpp | #include <iostream>
using namespace std;
void replaceDemo(string s1, string s2, string s3, string s4)
{
s1.replace(0, 7, s2); //Replaces 7 characters from 0th index by s2
cout << s1 << endl;
s4.replace(0, 3, "Hello "); //// Repalces 3 characters from 0th index with "Hello"
cout << s4 << endl;
s4.replace(6, 5, s3, 0, 5); //// Replaces 5 characters from 6th index of s4 with ,,5 characters from 0th of s3
cout << s4 << endl;
// Replaces 5 charcaters from 6th index of s4 with
// 6 characters from string "to all"
s4.replace(6, 5, "to all", 6);
cout << s4 << endl;
// Replaces 1 character from 12th index of s4 with
// 3 copies of '!'
s4.replace(12, 1, 3, '!');
cout << s4 << endl;
}
int main()
{
string s1 = "Example of replace";
string s2 = "Demonstration";
string s3 = "how are you";
string s4 = "HeyWorld !";
replaceDemo(s1, s2, s3, s4);
return 0;
}
|
a0afa1dac3c88ca515724bef4b07b30532f80fac | af272cd800f183d308cdbdf4d0e92690544acfad | /BasicTimers/BasicTimers.ino | bab10716e7def43bb956cec97f2d0d9dafb4dae0 | [] | no_license | kurt/FreeRTOS-Arduino | fbd6e289af22319f7cb058c145a1766c34882cd7 | ed73f907de4605d81ee073588c8eea6780127507 | refs/heads/master | 2022-04-23T22:20:19.502662 | 2020-04-17T19:06:23 | 2020-04-17T19:06:23 | 255,745,127 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,070 | ino | BasicTimers.ino | #include <Arduino_FreeRTOS.h>
#include <timers.h>
#define ONESECONDDELAY 1000/portTICK_PERIOD_MS
#define TWOSECONDDELAY 2000/portTICK_PERIOD_MS
void timer1_callback( TimerHandle_t xTimer ){
Serial.println("Timer Done");
}
void timer2_callback( TimerHandle_t xTimer ){
Serial.println("Timer 2 Done");
}
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
//xTimerCreate(pcTimerName,xTimerPeriod, uxAutoReload,pvTimerID, pxCallbackFunction );
TimerHandle_t timer1=xTimerCreate("1 second timer", ONESECONDDELAY, pdTRUE, 0, timer1_callback);
TimerHandle_t timer2=xTimerCreate("2 second timer", TWOSECONDDELAY, pdTRUE, 0, timer2_callback);
if (timer1 == NULL || timer2 == NULL) {
Serial.println("A timer can not be created");
} else {
// Start timer
if ((xTimerStart(timer1, 0) == pdPASS) && (xTimerStart(timer2, 0) == pdPASS )) { // Start the scheduler
vTaskStartScheduler(); //start scheduler should start the timers
}
}
}
void loop() {
// put your main code here, to run repeatedly:
}
|
d071799c4153b532c9261b8f4a01a54c11b458fc | c8b39acfd4a857dc15ed3375e0d93e75fa3f1f64 | /Engine/Source/Runtime/AIModule/Private/EnvironmentQuery/Generators/EnvQueryGenerator_Composite.cpp | 000675df42ce10ff7960299a1fc6f5c9712a771c | [
"MIT",
"LicenseRef-scancode-proprietary-license"
] | permissive | windystrife/UnrealEngine_NVIDIAGameWorks | c3c7863083653caf1bc67d3ef104fb4b9f302e2a | b50e6338a7c5b26374d66306ebc7807541ff815e | refs/heads/4.18-GameWorks | 2023-03-11T02:50:08.471040 | 2022-01-13T20:50:29 | 2022-01-13T20:50:29 | 124,100,479 | 262 | 179 | MIT | 2022-12-16T05:36:38 | 2018-03-06T15:44:09 | C++ | UTF-8 | C++ | false | false | 2,164 | cpp | EnvQueryGenerator_Composite.cpp | // Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
#include "EnvironmentQuery/Generators/EnvQueryGenerator_Composite.h"
#include "EnvironmentQuery/Items/EnvQueryItemType_Point.h"
#define LOCTEXT_NAMESPACE "EnvQueryGenerator"
UEnvQueryGenerator_Composite::UEnvQueryGenerator_Composite(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer)
{
ItemType = UEnvQueryItemType_Point::StaticClass();
bHasMatchingItemType = true;
}
void UEnvQueryGenerator_Composite::GenerateItems(FEnvQueryInstance& QueryInstance) const
{
if (bHasMatchingItemType)
{
for (int32 Idx = 0; Idx < Generators.Num(); Idx++)
{
if (Generators[Idx])
{
FScopeCycleCounterUObject GeneratorScope(Generators[Idx]);
Generators[Idx]->GenerateItems(QueryInstance);
}
}
}
}
FText UEnvQueryGenerator_Composite::GetDescriptionTitle() const
{
FText Desc = Super::GetDescriptionTitle();
for (int32 Idx = 0; Idx < Generators.Num(); Idx++)
{
if (Generators[Idx])
{
Desc = FText::Format(LOCTEXT("DescTitleExtention", "{0}\n {1}"), Desc, Generators[Idx]->GetDescriptionTitle());
}
}
return Desc;
};
void UEnvQueryGenerator_Composite::VerifyItemTypes()
{
TSubclassOf<UEnvQueryItemType> CommonItemType = nullptr;
bHasMatchingItemType = true;
if (bAllowDifferentItemTypes)
{
// ignore safety and force user specified item type
// REQUIRES proper memory layout between forced type and ALL item types used by child generators
// this is advanced option and will NOT be validated!
CommonItemType = ForcedItemType;
bHasMatchingItemType = (ForcedItemType != nullptr);
}
else
{
for (int32 Idx = 0; Idx < Generators.Num(); Idx++)
{
if (Generators[Idx])
{
if (CommonItemType)
{
if (CommonItemType != Generators[Idx]->ItemType)
{
bHasMatchingItemType = false;
break;
}
}
else
{
CommonItemType = Generators[Idx]->ItemType;
}
}
}
}
if (bHasMatchingItemType)
{
ItemType = CommonItemType;
}
else
{
// any type will do, generator is not allowed to create items anyway
ItemType = UEnvQueryItemType_Point::StaticClass();
}
}
#undef LOCTEXT_NAMESPACE
|
68b14c7400174ca116f13dcda8c271c31e8b54e2 | 96976a2c205d679261aa6ff6cd0db286c43ee350 | /src/revlanguage/functions/DistributionFunctionPdf.h | dcc28979f3c322d6f46ad13b1f492d3c84a8f697 | [] | no_license | sundsx/RevBayes | f99305df6b72bd70039b046d5131c76557e53366 | 13e59c59512377783673d3b98c196e8eda6fedee | refs/heads/master | 2020-04-06T06:29:46.557485 | 2014-07-26T14:26:57 | 2014-07-26T14:26:57 | 36,248,250 | 0 | 1 | null | 2015-05-25T18:44:13 | 2015-05-25T18:44:13 | null | UTF-8 | C++ | false | false | 7,046 | h | DistributionFunctionPdf.h | /**
* @file
* This file contains the declaration of ConstructorFunction, which is used
* for functions that construct objects using the RevLanguage.
*
* @brief Declaration of ConstructorFunction
*
* (c) Copyright 2009- under GPL version 3
* @date Last modified: $Date: 2012-06-01 14:40:37 +0200 (Fri, 01 Jun 2012) $
* @author The RevBayes Development Core Team
* @license GPL version 3
* @version 1.0
*
* $Id: ConstructorFunction.h 1602 2012-06-01 12:40:37Z hoehna $
*/
#ifndef DistributionFunctionPdf_H
#define DistributionFunctionPdf_H
#include "RlTypedDistribution.h"
#include "RlFunction.h"
#include <string>
#include <vector>
namespace RevLanguage {
template <class valueType>
class DistributionFunctionPdf : public Function {
public:
DistributionFunctionPdf(TypedDistribution<valueType> *d); //!< Object constructor
DistributionFunctionPdf(const DistributionFunctionPdf& obj); //!< Copy constructor
// overloaded operators
DistributionFunctionPdf& operator=(const DistributionFunctionPdf& c);
// Basic utility functions
DistributionFunctionPdf* clone(void) const; //!< Clone the object
static const std::string& getClassType(void); //!< Get Rev type
static const TypeSpec& getClassTypeSpec(void); //!< Get class type spec
const TypeSpec& getTypeSpec(void) const; //!< Get language type of the object
// Regular functions
RevPtr<Variable> execute(void); //!< Execute the function. This is the function one has to overwrite for single return values.
const ArgumentRules& getArgumentRules(void) const; //!< Get argument rules
const TypeSpec& getReturnType(void) const; //!< Get type of return value
protected:
ArgumentRules argRules; //!< Member rules converted to reference rules
TypedDistribution<valueType>* templateObject; //!< The template object
};
}
#include "ArgumentRule.h"
#include "DeterministicNode.h"
#include "DistributionFunctionPdf.h"
#include "Probability.h"
#include "ProbabilityDensityFunction.h"
#include "RevObject.h"
#include "RlBoolean.h"
#include "Real.h"
#include "TypeSpec.h"
#include <sstream>
/** Constructor */
template <class valueType>
RevLanguage::DistributionFunctionPdf<valueType>::DistributionFunctionPdf( TypedDistribution<valueType> *d ) : Function(), templateObject( d ) {
argRules.push_back( new ArgumentRule("x", true, valueType::getClassTypeSpec()));
const ArgumentRules &memberRules = templateObject->getMemberRules();
for (std::vector<ArgumentRule*>::const_iterator it = memberRules.begin(); it != memberRules.end(); ++it) {
argRules.push_back( (*it)->clone() );
}
argRules.push_back( new ArgumentRule("log", true, RlBoolean::getClassTypeSpec(), new RlBoolean(true)) );
}
/** Constructor */
template <class valueType>
RevLanguage::DistributionFunctionPdf<valueType>::DistributionFunctionPdf(const DistributionFunctionPdf& obj) : Function(obj), argRules( obj.argRules ) {
templateObject = obj.templateObject->clone();
}
template <class valueType>
RevLanguage::DistributionFunctionPdf<valueType>& RevLanguage::DistributionFunctionPdf<valueType>::operator=(const DistributionFunctionPdf &c) {
if (this != &c) {
Function::operator=(c);
templateObject = c.templateObject->clone();
argRules = c.argRules;
}
return *this;
}
/** Clone the object */
template <class valueType>
RevLanguage::DistributionFunctionPdf<valueType>* RevLanguage::DistributionFunctionPdf<valueType>::clone(void) const {
return new DistributionFunctionPdf<valueType>(*this);
}
/** Execute function: we reset our template object here and give out a copy */
template <class valueType>
RevLanguage::RevPtr<RevLanguage::Variable> RevLanguage::DistributionFunctionPdf<valueType>::execute( void ) {
TypedDistribution<valueType>* copyObject = templateObject->clone();
for ( size_t i = 1; i < (args.size()-1); i++ ) {
if ( args[i].isConstant() ) {
copyObject->setConstMember( args[i].getLabel(), RevPtr<const Variable>( (Variable*) args[i].getVariable() ) );
} else {
copyObject->setMember( args[i].getLabel(), args[i].getReferenceVariable() );
}
}
RevBayesCore::TypedDagNode<typename valueType::valueType>* arg = static_cast<const valueType &>( this->args[0].getVariable()->getRevObject() ).getDagNode();
RevBayesCore::ProbabilityDensityFunction<typename valueType::valueType>* f = new RevBayesCore::ProbabilityDensityFunction<typename valueType::valueType>( arg, copyObject->createDistribution() );
RevBayesCore::DeterministicNode<double> *detNode = new RevBayesCore::DeterministicNode<double>("", f);
Real* value = new Real( detNode );
return new Variable( value );
}
/** Get argument rules */
template <class valueType>
const RevLanguage::ArgumentRules& RevLanguage::DistributionFunctionPdf<valueType>::getArgumentRules(void) const {
return argRules;
}
/** Get Rev type of object */
template <class valueType>
const std::string& RevLanguage::DistributionFunctionPdf<valueType>::getClassType(void) {
static std::string revType = "DistributionFunctionPdf";
return revType;
}
/** Get class type spec describing type of object */
template <class valueType>
const RevLanguage::TypeSpec& RevLanguage::DistributionFunctionPdf<valueType>::getClassTypeSpec(void) {
static TypeSpec revTypeSpec = TypeSpec( getClassType(), new TypeSpec( Function::getClassTypeSpec() ) );
return revTypeSpec;
}
/** Get type spec */
template <class valueType>
const RevLanguage::TypeSpec& RevLanguage::DistributionFunctionPdf<valueType>::getTypeSpec( void ) const {
static TypeSpec typeSpec = getClassTypeSpec();
return typeSpec;
}
/** Get return type */
template <class valueType>
const RevLanguage::TypeSpec& RevLanguage::DistributionFunctionPdf<valueType>::getReturnType(void) const {
return Probability::getClassTypeSpec();
}
#endif
|
1e04cdd2cd0005bbc05395cbe03fee3df546f76c | c63698c70fb0d13821dc480505c0a5a7eda39c8f | /2017/24/main.cpp | c1206002cc225db76102255c97040e6b40168609 | [] | no_license | nagygeri97/AdventOfCode | 7430201bbe46d09ef793634cf72fb5b0b3b73655 | d8b8770982f85b6820c8c0f5edd3a6ae48246579 | refs/heads/master | 2023-01-13T15:44:41.921023 | 2023-01-13T08:35:51 | 2023-01-13T08:35:51 | 115,148,247 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,134 | cpp | main.cpp | #include <iostream>
#include <vector>
#include <utility>
using namespace std;
struct Piece{
int a,b;
bool used;
Piece(int a, int b):used(false),a(a),b(b){}
};
vector<Piece> pieces;
vector<vector<int>> as;
vector<vector<int>> bs;
pair<int,int> pathFind(int currPiece, bool useA, int weight, int depth){
pieces[currPiece].used = true;
int next = useA?pieces[currPiece].b:pieces[currPiece].a;
pair<int,int> max = pair<int,int>(depth,weight);
for(int i = 0; i<as[next].size(); ++i){
if(!pieces[as[next][i]].used){
pair<int,int> tmp = pathFind(as[next][i],true,weight + pieces[as[next][i]].a + pieces[as[next][i]].b, depth + 1);
if(tmp.first > max.first || (tmp.first == max.first && tmp.second > max.second)) max = tmp;
}
}
for(int i = 0; i<bs[next].size(); ++i){
if(!pieces[bs[next][i]].used){
pair<int,int> tmp = pathFind(bs[next][i],false,weight + pieces[bs[next][i]].a + pieces[bs[next][i]].b, depth + 1);
if(tmp.first > max.first || (tmp.first == max.first && tmp.second > max.second)) max = tmp;
}
}
pieces[currPiece].used = false;
return max;
}
void first(){
int a,b;
int i = 0;
as.resize(51);
bs.resize(51);
while(cin >> a >> b){
pieces.push_back(Piece(a,b));
as[a].push_back(i);
bs[b].push_back(i);
++i;
}
pair<int,int> max = pair<int,int>(0,0);
for(int i = 0; i<as[0].size(); ++i){
if(!pieces[as[0][i]].used){
pair<int,int> tmp = pathFind(as[0][i],true,pieces[as[0][i]].a + pieces[as[0][i]].b,0);
if(tmp.first > max.first || (tmp.first == max.first && tmp.second > max.second)) max = tmp;
}
}
for(int i = 0; i<bs[0].size(); ++i){
if(!pieces[bs[0][i]].used){
pair<int,int> tmp = pathFind(bs[0][i],false,pieces[bs[0][i]].a + pieces[bs[0][i]].b,0);
if(tmp.first > max.first || (tmp.first == max.first && tmp.second > max.second)) max = tmp;
}
}
cout << max.first << " " << max.second << endl;
}
int main(){
first();
return 0;
} |
a883ed712d8180db19b7ab5ffbd7645b4a003d7c | ff0b6f4c1026ffe934fa29e98ce5db20d7584b13 | /src/SkewDetector.h | 5e1d727b2a877d9b05b709fa0d4af1b7e71c6b54 | [] | no_license | yuansanwan/skewDetection | b47c300bc0335d91e067abf96855222b247dfc0a | 66c4df96678dfd921ddc42a56b6ed7a8122527a6 | refs/heads/master | 2021-01-22T03:22:08.588414 | 2016-03-03T09:34:33 | 2016-03-03T09:34:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,168 | h | SkewDetector.h | /*
* SkewDetector.h
*
* Created on: Jul 9, 2013
* Author: Michal Busta
*/
#ifndef SKEWDETECTOR_H_
#define SKEWDETECTOR_H_
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#define _USE_MATH_DEFINES
#include <math.h>
namespace cmp
{
//the horizont threshold
#define IGNORE_ANGLE 30
#define ANGLE_TOLERANCE M_PI/60.0
//common functions
void draw_polar_histogram(cv::Mat& img, double* histogram, int bins, cv::Scalar color);
void draw_polar_histogram_color(cv::Mat& img, std::vector<double>& angles, std::vector<double>& probabilities, std::vector<cv::Scalar>& colors);
/**
* @class cmp::SkewDetector
*
* @brief The skew detector interface
*
* TODO type description
*/
class SkewDetector
{
public:
SkewDetector();
virtual ~SkewDetector();
/**
*
* @param mask the character mask - ink is white
* @param lineK
* @param debugImage the debug image will be created in same size as mask image
* @return the skew angle in radians
*/
virtual double detectSkew( cv::Mat& mask, double lineK, cv::Mat* debugImage = NULL ) = 0;
/** the measure of "how sure" the detector is about the result */
double lastDetectionProbability;
/** probality measure 1 */
int probMeasure1;
/** probality measure 2 */
double probMeasure2;
};
/**
* @class cmp::ContourSkewDetector
*
* @brief The skew detector interface for detectors working on contour
*
* Class interface carry out: contour detection and returning just biggest contour
*/
class ContourSkewDetector : public SkewDetector
{
public:
ContourSkewDetector( int approximatioMethod, double epsilon );
virtual ~ContourSkewDetector(){ }
virtual double detectSkew( cv::Mat& mask, double lineK, cv::Mat* debugImage = NULL );
virtual void getSkewAngles( std::vector<cv::Point>& outerContour, double lineK, std::vector<double>& angles, std::vector<double>& probabilities, std::vector<int>& detecotrsId, cv::Mat* debugImage){
}
virtual void voteInHistogram( std::vector<cv::Point>& outerContour, double lineK, double *histogram, double weight, bool approximate = false, cv::Mat* debugImage = NULL) = 0;
/**
* Descendants have to implement this method
*
* @param mask
* @param contours
* @param debugImage
* @return
*/
virtual double detectSkew( std::vector<cv::Point>& contour, double lineK, bool approximate = false, cv::Mat* debugImage = NULL ) = 0;
static void getBigestContour( std::vector<std::vector<cv::Point> >& contours, std::vector<cv::Vec4i>& hierarchy );
// function to filter things that are closer than ANGLE_TOLERANCE to other thing (e.g. thin profiles)
static void filterValuesBySimiliarAngle
(const std::vector<double>& values, const std::vector<double>& angles, std::vector<double>& valuesOut, std::vector<double>& anglesOut, double angleRange = ANGLE_TOLERANCE * 2);
protected:
void approximateContour(std::vector<cv::Point>& contour, std::vector<cv::Point>& contourOut);
//@see cv::findContorurs
int approximatioMethod;
/** the constant in approximation method @see cv::approxPolyDP */
double epsilon;
const double scalefactor;
};
/**
* @class cmp::MockSkewDetector
*
* @brief The test detector, detected skew is allways 0
*/
class MockSkewDetector : public SkewDetector
{
inline virtual double detectSkew( cv::Mat& mask, double lineK, cv::Mat* debugImage = NULL )
{
if(debugImage != NULL)
{
cv::Mat& drawing = *debugImage;
drawing = cv::Mat::zeros( mask.size(), CV_8UC3 );
std::vector<std::vector<cv::Point> > contours;
std::vector<cv::Vec4i> hierarchy;
cv::findContours( mask, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE, cv::Point(0, 0) );
cv::Scalar color = cv::Scalar( 255, 255, 255 );
drawContours( drawing, contours, 0, color, 2, 8, hierarchy, 0, cv::Point() );
}
return 0.0;
}
};
/**
* Create image which is horizontal alignment of imagesToMerge
*
* @param imagesToMerge
* @param spacing space between images
* @param verticalDisplacement
*
* @return the merged image
*/
inline cv::Mat mergeHorizontal(std::vector<cv::Mat>& imagesToMerge, int spacing, int verticalDisplacement, std::vector<cv::Point>* imagesCenters, cv::Scalar color = cv::Scalar(0, 0, 0) )
{
int sw = 0;
int sh = 0;
for( std::vector<cv::Mat>::iterator it = imagesToMerge.begin(); it < imagesToMerge.end(); it++ )
{
sw += it->cols + spacing;
sh = MAX(it->rows + verticalDisplacement, sh);
}
cv::Mat mergedImage = cv::Mat::zeros(sh, sw, imagesToMerge[0].type()) + color;
int wOffset = 0;
int i = 0;
for( std::vector<cv::Mat>::iterator it = imagesToMerge.begin(); it < imagesToMerge.end(); it++ )
{
int hoffset = (i % 2 ) * verticalDisplacement;
if( it->rows < mergedImage.rows)
{
hoffset += (mergedImage.rows - it->rows) / 2;
}
if(it->cols == 0)
continue;
cv::Rect roi = cv::Rect(wOffset, hoffset, it->cols, it->rows);
mergedImage(roi) = cv::Scalar(0, 0, 0);
mergedImage(roi) += *it;
wOffset += it->cols + spacing;
if(imagesCenters != NULL)
imagesCenters->push_back( cv::Point(roi.x + roi.width / 2, roi.y + roi.height / 2) );
i++;
}
return mergedImage;
}
} /* namespace cmp */
#endif /* SKEWDETECTOR_H_ */
|
ec1fa80a538d99a327cb959a619ae08baae427f2 | 1ceb557d0e054738a69a2346ffb08aafbb041602 | /listas.cpp | 29fbae6b65a0e8a47517fed6c38d8aa0eafd4bb4 | [] | no_license | DaviSeb/Tesina-RTS | 3f74473fc2138430018a55b500a00fe1006320f7 | ececbe5b26c3f2281fac0da62a3dddc37fe5d53c | refs/heads/master | 2022-12-02T06:46:53.174818 | 2020-08-21T20:41:01 | 2020-08-21T20:41:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,026 | cpp | listas.cpp | /*
* listas.cpp
*
*/
#include "listas.h"
// Prototipos de Funciones
// Funciones de Listas
node_t *newNode(tcb_t *tcb, int prioridad);
node_t *addNodeList(node_t *list, tcb_t *tcb, uint64_t prioridad);
node_t *topNodeList(node_t *list);
// Crear nuevo nodo
node_t *newNode(tcb_t *tcb, int prioridad){
node_t *newNode;
newNode= (node_t *) malloc(sizeof (node_t));
if(newNode == NULL){
printf("(*) newNode: error malloc.\n\r");
exit(1);
}
newNode->tcb= tcb;
newNode->prioridad= prioridad;
newNode->next= NULL;
return newNode;
}
// Agregar un nodo a la lista en orden
node_t *addNodeList(node_t *list, tcb_t *tcb, uint64_t prioridad){
// Crea nuevo nodo para la lista con su prioridad
node_t *nNode= newNode(tcb, prioridad);
// punteros necesarios para agregar nodo entre nodos
node_t *before;
node_t *cursor;
// Si la lista esta vacia
if(list == NULL){
list= nNode;
}
else{
before= NULL;
cursor= list;
// Recorrer la lista buscando por prioridad
while(cursor != NULL && (nNode->prioridad >= cursor->prioridad)){
before= cursor;
cursor= cursor->next;
}
// Si el nuevo nodo es de menor prioridad que el primero
if (before == NULL){
list= nNode;
nNode->next= cursor;
}
else{
before->next= nNode;
nNode->next= cursor;
}
}
return list;
}
// Sacar cabeza de la lista
node_t* topNodeList(node_t *list){
node_t* node;
// Si la lista tiene un elemento
if(list->next == NULL){
free(list);
list= NULL;
}
else{ // Si tiene mas de 1 elemento
node= list;
list= list->next;
free(node);
}
return list;
}
// Agregar una Tarea a una Lista
node_t *agregarTareaALista(node_t *list, tcb_t *tcb, uint64_t prioridad){
node_t *lista= addNodeList(list, tcb, prioridad);
return lista;
}
// Sacar una Tarea de una Lista
node_t* sacarTareaDeLista(node_t *list){
node_t* node= topNodeList(list);
return node;
}
|
441a71a6f6181f7700929e6e31f2c574acac24a8 | 2920db67e3abc01c3d5fe8b39d7b1af5726af2f1 | /SndManager.h | 9f3740a36dee8f628122c22da39985eff47f575e | [] | no_license | emfprhs119/OpenMugen | ef0ee7dd19dc813bdf3fa21d2d175962df15fb7b | 460dd6a8e37f5b5dfdc7e20774e147ecfc441693 | refs/heads/master | 2021-01-21T10:38:05.667704 | 2017-05-25T11:21:37 | 2017-05-25T11:21:37 | 87,546,464 | 1 | 0 | null | 2017-04-07T13:06:08 | 2017-04-07T13:06:07 | null | UTF-8 | C++ | false | false | 598 | h | SndManager.h | #include "global.h"
class CSndManager
{
private:
SND* lpSpriteList;
CAllocater *m_pAlloc;
bool bPlay;
Uint32 wav_length; // length of our sample
Uint8 *wav_buffer; // buffer containing our audio file
SDL_AudioSpec wav_spec; // the specs of our piece of music
Mix_Chunk *mix,*mix1;
int ff=0;
SND IpSndListFight;
SND IpSndListCommon;
SND IpSndListPlayer;
SND curIpSndList;
public:
bool LoadSndFile(const char *strSndFile, CAllocater* a, SNDFLAG flag);
void PlayAudio(SNDFLAG flag, s32 nGroupNumber, s32 SampleNumber);
bool CurPlay(){ return bPlay; };
bool PlayMutex();
}; |
8ddc2cde199cc6e064e065eb275538f080d93861 | 9192182cfcfcf4ce9f9bbb4003106e29b37b5bd1 | /mame-0.141/src/mame/includes/esd16.h | 9330d7a3041dc1bb1e7261639ebe5f7e169ed47a | [] | no_license | johkelly/MAME_hi | a2b9ea9d4f089f75e57de5963af187718733fccd | ccbec44e4c82e5ca83ba80de19bfb9c100dbd349 | refs/heads/master | 2020-05-17T13:29:54.978078 | 2012-07-13T19:03:50 | 2012-07-13T19:03:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,239 | h | esd16.h | /***************************************************************************
ESD 16 Bit Games
***************************************************************************/
class esd16_state : public driver_device
{
public:
esd16_state(running_machine &machine, const driver_device_config_base &config)
: driver_device(machine, config) { }
/* memory pointers */
UINT16 * vram_0;
UINT16 * vram_1;
UINT16 * scroll_0;
UINT16 * scroll_1;
UINT16 * spriteram;
UINT16 * head_layersize;
UINT16 * headpanic_platform_x;
UINT16 * headpanic_platform_y;
// UINT16 * paletteram; // currently this uses generic palette handling
size_t spriteram_size;
/* video-related */
tilemap_t *tilemap_0_16x16, *tilemap_1_16x16;
tilemap_t *tilemap_0, *tilemap_1;
int tilemap0_color;
/* devices */
device_t *audio_cpu;
device_t *eeprom;
};
/*----------- defined in video/esd16.c -----------*/
WRITE16_HANDLER( esd16_vram_0_w );
WRITE16_HANDLER( esd16_vram_1_w );
WRITE16_HANDLER( esd16_tilemap0_color_w );
VIDEO_START( esd16 );
VIDEO_UPDATE( esd16 );
VIDEO_UPDATE( hedpanic );
VIDEO_UPDATE( hedpanio );
|
9fe07d0d734fdfff2267f13dc842654eea1bcd2b | 20d52640ca3b625535b766ee093a98d64a67fdc3 | /slave/server/client_class_manager.h | 0af8e2678aee593abe19d83e5f85b61bee037616 | [] | no_license | zdnscloud/zdhcp | ebe4013ca65d2c01b305a04d15a5b66564891cb4 | b2308b9c62ea755bc5c410d16b559748f38f966d | refs/heads/master | 2020-08-07T19:41:44.601357 | 2019-10-08T06:58:29 | 2019-10-08T06:58:29 | 213,567,680 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 718 | h | client_class_manager.h | #pragma once
#include <kea/server/client_class_matcher.h>
#include <map>
using namespace kea::dhcp;
namespace kea {
namespace server {
class DuplicateClientClassName : public Exception {
public:
DuplicateClientClassName(const char* file, size_t line, const char* what) :
kea::Exception(file, line, what) { };
};
class ClientClassManager {
public:
static ClientClassManager& instance();
ClientClassManager() {}
void addClientClass(const std::string& name, const std::string& exp);
std::vector<std::string> getMatchedClass(const Pkt& pkt);
void removeAll();
private:
std::map<std::string, PktOptionMatcher> client_classes_;
};
};
};
|
e5cc41f370eebd13a7c42c281e263f4ab461f122 | b9cae22574611541bb06e87e03ab73fc6148f2c2 | /NormalMappingReflection/NAH_lib/TransformObject.h | 82af87b572dae82808fcce4e84a59df5911b9517 | [] | no_license | NikolaiAlexanderHimlan/GameGraphicsII_TeamProject | 7b7ec59098e1e8f1832f4c06624a7f087cc14078 | 52df77115a7cdba7560d0f05c6dbfad8128caec3 | refs/heads/master | 2016-08-04T20:49:00.699394 | 2015-04-25T04:42:58 | 2015-04-25T04:42:58 | 30,326,911 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,760 | h | TransformObject.h | /*
Author: Nikolai Alexander-Himlan
Class: EPG-425 <Section 51>
Assignment: pa 2
Certification of Authenticity:
I certify that this assignment is entirely my own work.
*/
#ifndef _TRANSFORM_OBJECT_H
#define _TRANSFORM_OBJECT_H
#include "Transform.h"
//Object containing a transform and handling complex transformations
class TransformObject
{
//TODO: make class pure virtual
//TODO: pull transform (position) change check down from PhysicsObject
private:
const TransformObject* mpTargetTransform = nullptr;//look at
const TransformObject* mpParentTransform = nullptr;//move with
Transform mLocalTransform;//The local transform
//TODO: need to setup calling this function in setters (and refs)
//TODO: add check for any calculations (ex: in setters) to see if the calculation should be overridden by an existing locks.
bool HandleLocks(void)//handles any existing locks (Target, etc..), returns if anything was modified.
{
//TODO: if target and parent are the same, lookAt can be simplified
if (hasTarget())
lookAt(mpTargetTransform->getWorldTransform().position);
if (hasParent())
{
}//parent is only relevant to world transform
}
public:
//Getters
inline const Transform& getLocalTransform() const { return mLocalTransform; };
virtual inline Transform& refLocalTransform() { return mLocalTransform; };//returns a modifiable reference, done as a function so modifications can be tracked
//Setters
inline void setLocalTransform(const Transform& newTransform) { refLocalTransform() = newTransform; };//done using getLocalTransformRef for convenience to subclasses
//Properties
inline bool hasLock() const
{
return false//will not affect result
|| hasTarget()
|| hasParent()
;
}
inline bool hasTarget() const { return mpTargetTransform != nullptr; };
inline bool hasParent() const { return mpParentTransform != nullptr; };
const Transform getWorldTransform() const//calculates the world transform based on the local transform and parent world transform
{
if (!hasParent())
return getLocalTransform();
//HACK: Currently only calculates the (incorrect) world position and scale. correct world position will require scale calculation
//TODO: store current world, and previous local and world transforms. Don't recalculate WorldTransform unless LocalTransform has changed.
//initialize with world transform values
Transform parentWorldTransform = mpParentTransform->getWorldTransform();
Vector3f worldPosition = getLocalTransform().position;
Vector3f worldRotation = getLocalTransform().rotation;
Vector3f worldScale = getLocalTransform().scale;
//TODO: parent rotation needs to affect position
worldPosition = parentWorldTransform.position + Vect3_Multiply(getLocalTransform().position, parentWorldTransform.scale);//scale affects the position//HACK: should be influenced by rotation
worldRotation = parentWorldTransform.rotation + Vect3_Multiply(getLocalTransform().rotation, parentWorldTransform.scale);//scale affects rotation
worldScale = Vect3_Multiply(worldScale, parentWorldTransform.scale);//combine the scales
return Transform(worldPosition, worldRotation, worldScale);
};
//Modifiers
void setWorldTransform(const Transform& newWorldTransform)
{
setWorldPosition(newWorldTransform.position);
setWorldRotation(newWorldTransform.rotation);
setWorldScale(newWorldTransform.scale);
}
void setWorldPosition(const Vector3f& newWorldPosition)
{
if (mpParentTransform == nullptr)
{
refLocalTransform().position = newWorldPosition;
return;
}
//Calculate new local position value
//TODO: parent rotation needs to affect position
refLocalTransform().position =
Vect3_Divide(getLocalTransform().position,
mpParentTransform->getWorldTransform().scale)
- mpParentTransform->getWorldTransform().position;//HACK: simplified
}
void setWorldRotation(const Rotation3D& newWorldRotation)
{
if (mpParentTransform == nullptr)
{
refLocalTransform().rotation = newWorldRotation;
return;
}
//Calculate new local rotation value
refLocalTransform().rotation =
Vect3_Divide(getLocalTransform().rotation,
mpParentTransform->getWorldTransform().scale)
- mpParentTransform->getWorldTransform().rotation;
}
void setWorldScale(const Vector3f& newWorldScale)
{
if (mpParentTransform == nullptr)
{
refLocalTransform().scale = newWorldScale;
return;
}
//Calculate new local scale value
refLocalTransform().scale = Vect3_Divide(getLocalTransform().scale, mpParentTransform->getWorldTransform().scale);
}
//Actions
//Lock to Transform, it should be noted that calling these should not actually affect the WorldPosition, though any subsequent movement by the parent should affect the world position
#include "RotationMath.h"//TODO: move to source file
inline void lookAt(const Vector3f& lookHere)
{
setWorldRotation(getWorldTransform().calcLookAtRotation(lookHere));
};
inline void setTarget(const TransformObject* targetThis)//look at this transform and keep looking at it until the lock is released
{
mpTargetTransform = targetThis;
//TODO: if target is the same as parent, lookAt can be simplified
if (hasParent())
lookAt(targetThis->getWorldTransform().position);
};
inline void clearTarget(void) { setTarget(nullptr); };
inline void setParent(const TransformObject* attachTo)//attach to this transform, local transform is now relative to this
{
//world values should be the same before and after the parent has been set
Transform oldWorld = getWorldTransform();//save the current world transform
mpParentTransform = attachTo;
setWorldTransform(oldWorld);//local now stores the value relative to the parent
};
inline void clearParent(void) { setParent(nullptr); };
};
#endif
|
3e714b8d0283946ec8d962188ca1817fb7e33d73 | f4973d588609131fbb2fdc676b93b8f77ed66824 | /C++ in web/cpp/curd.cpp | bf550bf0329905df8651cef92f797761cfaa5baa | [] | no_license | IamRitikS/experimentation | 97adc49816bd0a79035a27ebdc534857078abc50 | 8eaf808d840ebecce5a2c3f8cdccadb4e7f5d1df | refs/heads/master | 2023-04-22T02:18:08.877159 | 2021-05-18T03:51:47 | 2021-05-18T03:51:47 | 242,979,970 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,072 | cpp | curd.cpp | #include <iostream>
#include <stdlib.h>
#include <vector>
#include "mysql_connection.h"
#include <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>
#include <cppconn/prepared_statement.h>
#include <bits/stdc++.h>
#define A 54059 /* a prime */
#define B 76963 /* another prime */
#define C 86969 /* yet another prime */
#define FIRSTH 37 /* also prime */
using namespace std;
std::vector<string> fetchArray(string);
unsigned hash_str(const char* s)
{
unsigned h = FIRSTH;
while (*s)
{
h = (h * A) ^ (s[0] * B);
s++;
}
return h; // or return h % C;
}
class Database
{
private :
string user = "admin";
string password = "passwd=passwd";
string database = "admon_rough";
public:
sql::Connection* connectDB(void)
{
sql::Connection *con = NULL;
try
{
sql::Driver *driver;
sql::Statement *stmt;
sql::ResultSet *res;
driver = get_driver_instance();
con = driver->connect("tcp://127.0.0.1:3306", user, password);
con->setSchema(database);
}
catch (sql::SQLException &e)
{
}
return con;
}
};
std::vector<string> fetchArray(string getString)
{
vector <string> keypairs;
stringstream temp1(getString);
string intermediate;
while(getline(temp1, intermediate, '&'))
{
stringstream temp2(intermediate);
string seperator;
while(getline(temp2, seperator, '='))
{
keypairs.push_back(seperator);
}
}
return keypairs;
}
int findIndex(std::vector<string> v, string keyword)
{
for (int i = 0; i < v.size(); i++)
{
if(v[i] == keyword)
{
return i;
}
}
return -1;
}
bool replace(std::string& str, const std::string& from, const std::string& to)
{
size_t start_pos = str.find(from);
if(start_pos == std::string::npos)
return false;
str.replace(start_pos, from.length(), to);
return true;
}
int main()
{
try
{
vector <string> getString = fetchArray((string)getenv("QUERY_STRING"));
if(getString.empty())
{
cout << "Location: http://localhost/login.cgi\n\n";
return 0;
}
int index = findIndex(getString, "action");
if(getString[index+1] == "login")
{
int len;
char* lenstr = getenv("CONTENT_LENGTH");
string temp = "";
if(lenstr != NULL && (len = atoi(lenstr)) != 0)
{
char *post_data = new char[len];
fgets(post_data, len + 1, stdin);
for (int i = 0; i < len; i++)
{
temp = temp + post_data[i];
}
std::vector<string> postString = fetchArray(temp);
string email = postString[1];
string password = postString[3];
const char * c = password.c_str();
password = to_string(hash_str(c));
replace(email, "@", "%40");
Database db;
sql::Connection *con = db.connectDB();
sql::PreparedStatement *pstmt;
sql::ResultSet *res;
pstmt = con->prepareStatement("SELECT * FROM user WHERE email = ? LIMIT 1");
pstmt->setString(1, email);
res = pstmt->executeQuery();
if(!res->next())
{
cout << "Location: http://localhost/login.cgi?message=No user with that email address\n\n";
return 0;
}
if(res->getString("password") == password)
{
cout << "Content-Type: text/html\n";
cout << "Set-Cookie:user=" << email << ";\n";
cout << "Location: http://localhost/home.cgi?user=" << res->getString("name") << "\n\n";
}
else
{
cout << "Location: http://localhost/login.cgi?message=You entered wrong password\n\n" << endl;
}
delete res;
delete pstmt;
delete con;
return 0;
}
}
else if(getString[index+1] == "registration")
{
int len;
char* lenstr = getenv("CONTENT_LENGTH");
string temp = "";
if(lenstr != NULL && (len = atoi(lenstr)) != 0)
{
char *post_data = new char[len];
fgets(post_data, len + 1, stdin);
for (int i = 0; i < len; i++)
{
temp = temp + post_data[i];
}
std::vector<string> postString = fetchArray(temp);
string name = (string)postString[1] + " " + postString[3];
string email = (string)postString[5];
string password = (string)postString[7];
const char * c = password.c_str();
password = to_string(hash_str(c));
Database db;
sql::Connection *con = db.connectDB();
sql::PreparedStatement *pstmt;
sql::ResultSet *res;
pstmt = con->prepareStatement("SELECT * FROM user WHERE email = ? LIMIT 1");
pstmt->setString(1, email);
res = pstmt->executeQuery();
if(res->next())
{
cout << "Location: http://localhost/signup.cgi?message=There is already an user with that email\n\n";
return 0;
}
pstmt = con->prepareStatement("INSERT INTO `user` (`email`, `name`, `password`) VALUES (?,?,?)");
pstmt->setString(1, email);
pstmt->setString(2, name);
pstmt->setString(3, password);
pstmt->execute();
delete pstmt;
delete con;
cout << "Content-Type: text/html\n";
cout << "Set-Cookie:user=" << email << ";\n";
cout << "Location: http://localhost/home.cgi?user=" << name << "\n\n";
}
}
else if(getString[index+1] == "cookie-resolve")
{
std::vector<string> v = fetchArray(getenv("HTTP_COOKIE"));
int index2 = findIndex(getString, "user");
string email = getString[index2+1];
Database db;
sql::Connection *con = db.connectDB();
sql::PreparedStatement *pstmt;
sql::ResultSet *res;
pstmt = con->prepareStatement("SELECT * FROM user WHERE email = ? LIMIT 1");
pstmt->setString(1, email);
res = pstmt->executeQuery();
if(!res->next())
{
cout << "Content-Type: text/html\n";
cout << "Set-Cookie:user=" << email << ";expires=Thu, 01 Jan 1970 00:00:00 GMT\n";
cout << "Location: http://localhost/login.cgi\n\n";
return 0;
}
else
{
cout << "Location: http://localhost/home.cgi?user=" << res->getString("name") << "\n\n";
}
delete res;
delete pstmt;
delete con;
return 0;
}
else
{
cout << "Location: http://localhost/login.cgi\n\n";
}
return 0;
}
catch(...)
{
cout << "Location: http://localhost/login.cgi\n\n";
return 0;
}
}
|
8d57ef42e8828a530264d8d662042a5c056cdc75 | 9a23bf97410afe9d824ca3e28ed0b57bdf0a69cc | /Holiday/src/StepMotor.h | 5d3b22597544cff5653357def3e53054c9a7ddb0 | [] | no_license | Squirrel-Power/Holiday-Hacks | 12d78a1368f9e482b610dafbac4cc4f08e9323b9 | b5ea82db2afc5dd31046311f8f08a434ec72eb63 | refs/heads/master | 2021-01-19T08:53:33.553810 | 2015-08-26T01:12:06 | 2015-08-26T01:12:06 | 37,781,592 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 425 | h | StepMotor.h | /*
* StepMotor.h
*
* Created on: Jun 14, 2015
* Author: Cyber
*/
#ifndef STEPMOTOR_H_
#define STEPMOTOR_H_
//#include "SoftwareServo.h"
#include <stdlib.h>
class StepMotor {
public:
StepMotor();
virtual ~StepMotor();
void MyRndMove();
int MaxDist;
int MinDist;
int CurrentPosition;
private:
int GetMax();
int GetMin();
void Move(int distance);
//SoftwareServo myServo;
};
#endif /* STEPMOTOR_H_ */
|
8c2c4aa6148e32949680fb0dd7359472ee00b134 | 77964a8a4e92e3af22f092ea2f674cc1873bf890 | /sort.h | 2a641475973d44063ca54187c5bcba56c49722d2 | [] | no_license | Takovsky/sort | cdc704ebeaca292090e625da65c0bbe4586e1447 | d667d5ec6b310d53ef831d45732e46cf41da61cf | refs/heads/master | 2020-03-15T22:52:33.984540 | 2018-05-06T22:49:42 | 2018-05-06T22:49:42 | 132,382,046 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,636 | h | sort.h | #ifndef SORT_H
#define SORT_H
#include "SortHelper.h"
#include <cmath>
template <typename T>
void mergesort(T *arr, int left, int right)
{
if(left < right)
{
int mid = (left + right) / 2;
mergesort(arr, left, mid);
mergesort(arr, mid + 1, right);
merge(arr, left, mid, right);
}
}
template <typename T>
void quicksort(T *arr, int left, int right)
{
if(left < right)
{
int partitionPoint = partition(arr, left, right);
quicksort(arr, left, partitionPoint);
quicksort(arr, partitionPoint + 1, right);
}
}
template <typename T>
void introsort(T *arr, int left, int right)
{
int depthLimit = 2 * log(right - left);
introsortUtil(arr, left, right, depthLimit);
}
template <typename T>
void revert(T *arr, int left, int right)
{
for(int i = left, j = right; i < j; i++, j--)
swap(arr[i], arr[j]);
}
template <typename T>
bool isSortedDownUp(T *arr, int left, int right)
{
for(int i = left + 1; i <= right; i++)
if(arr[i] < arr[i - 1])
return false;
return true;
}
template <typename T>
bool isSortedUpDown(T *arr, int left, int right)
{
for(int i = left + 1; i <= right; i++)
if(arr[i] > arr[i - 1])
return false;
return true;
}
#endif // SORT_H
// https://www.geeksforgeeks.org/merge-sort/
// https://www.geeksforgeeks.org/know-your-sorting-algorithm-set-2-introsort-cs-sorting-weapon/
// http://www.algorytm.org/algorytmy-sortowania/sortowanie-szybkie-quicksort/quick-1-c.html
// https://www.geeksforgeeks.org/know-your-sorting-algorithm-set-2-introsort-cs-sorting-weapon/
|
c198a5b96709a5427ad089ad855ab7ff82519c26 | 487f8831b17f773b526d12f97d499d568e39cc35 | /longest-substring-with-at-least-k-repeating-characters/sliding-window-solution.cpp | c1d96d272640d2c331a3cf9ccaa442c915a65c9e | [] | no_license | gengyouchen/leetcode | 83879ca8163ab9527765dacb5165e622d0bf3f60 | e4fdcbe858e0996f1f80034f640dbe2c0f536592 | refs/heads/master | 2021-06-28T16:13:31.670311 | 2020-09-08T14:36:32 | 2020-09-08T14:36:32 | 142,698,749 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,386 | cpp | sliding-window-solution.cpp | class Counter {
private:
const int threshold;
int char2count[26] = {};
int nDistinct = 0, nDistinctOverThreshold = 0;
public:
Counter(int threshold) : threshold(max(threshold, 1)) {}
void add(char c) {
const int after = ++char2count[c - 'a'];
if (after == 1)
++nDistinct;
if (after == threshold)
++nDistinctOverThreshold;
};
void remove(char c) {
const int after = --char2count[c - 'a'];
if (after == 0)
--nDistinct;
if (after == threshold - 1)
--nDistinctOverThreshold;
}
int countDistinct() const { return nDistinct; }
int countDistinctOverThreshold() const { return nDistinctOverThreshold; }
};
class Solution {
private:
/* See LeetCode 340 - Longest Substring with At Most K Distinct Characters */
static int lengthOfLongestSubstringKDistinct(const string& s, int k, int threshold) {
const int n = s.size();
Counter window(threshold);
int ans = 0, L = 0;
for (int R = 0; R < n; ++R) {
window.add(s[R]);
while (window.countDistinct() > k)
window.remove(s[L++]);
if (window.countDistinct() == window.countDistinctOverThreshold())
ans = max(ans, R - L + 1);
}
return ans;
}
public:
/* time: O(n * |charset|), space: O(|charset|) */
static int longestSubstring(const string& s, int k) {
int ans = 0;
for (int i = 1; i <= 26; ++i)
ans = max(ans, lengthOfLongestSubstringKDistinct(s, i, k));
return ans;
}
};
|
fbc5146e93f397d11972c1fcd663e66dd815ef82 | b0745d4dbaf2fb74d808a318e5fefdbc82c6ef00 | /espressifplugin.cpp | 8c4a6dc45fa69c4daca48bbbfd10740d4e240e6c | [
"MIT"
] | permissive | ThomArmax/QtCreatorEspressifPlugin | 73d5d14f8c7fc757cc18f45e4a36f493218c7e83 | 1ef87de9ff59180d68d733cc7af4f7caedac2e22 | refs/heads/master | 2020-03-06T22:09:09.132751 | 2018-03-28T14:09:18 | 2018-03-28T14:09:18 | 127,096,252 | 3 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 3,338 | cpp | espressifplugin.cpp | /****************************************************************************
**
** Copyright (c) 2018 Thomas COIN
** Contact: Thomas Coin<esvcorp@gmail.com>
**
** Permission is hereby granted, free of charge, to any person obtaining a copy
** of this software and associated documentation files (the "Software"), to deal
** in the Software without restriction, including without limitation the rights
** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
** copies of the Software, and to permit persons to whom the Software is
** furnished to do so, subject to the following conditions:
**
** The above copyright notice and this permission notice shall be included in all
** copies or substantial portions of the Software.
**
** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
** SOFTWARE.
**
****************************************************************************/
#include "espressifplugin.h"
#include "espressifconstants.h"
#include "espressifsettingspage.h"
#include "espressiftoolchain.h"
#include <coreplugin/icore.h>
#include <coreplugin/icontext.h>
#include <coreplugin/actionmanager/actionmanager.h>
#include <coreplugin/actionmanager/command.h>
#include <coreplugin/actionmanager/actioncontainer.h>
#include <coreplugin/coreconstants.h>
#include <QAction>
#include <QMessageBox>
#include <QMainWindow>
#include <QMenu>
namespace Espressif {
namespace Internal {
class EspressifPluginPrivate
{
public:
EspressifSettingsPage settingsPage;
EspressifToolChainFactory toolchainFactory;
};
static EspressifPluginPrivate *dd = nullptr;
EspressifPlugin::EspressifPlugin()
{
// Create your members
}
EspressifPlugin::~EspressifPlugin()
{
// Unregister objects from the plugin manager's object pool
// Delete members
}
bool EspressifPlugin::initialize(const QStringList &arguments, QString *errorString)
{
// Register objects in the plugin manager's object pool
// Load settings
// Add actions to menus
// Connect to other plugins' signals
// In the initialize function, a plugin can be sure that the plugins it
// depends on have initialized their members.
Q_UNUSED(arguments)
Q_UNUSED(errorString)
dd = new EspressifPluginPrivate;
// Handles Espressif toolchain
//addAutoReleasedObject(new EspressifSettingsPage);
return true;
}
void EspressifPlugin::extensionsInitialized()
{
// Retrieve objects from the plugin manager's object pool
// In the extensionsInitialized function, a plugin can be sure that all
// plugins that depend on it are completely initialized.
}
ExtensionSystem::IPlugin::ShutdownFlag EspressifPlugin::aboutToShutdown()
{
// Save settings
// Disconnect from signals that are not needed during shutdown
// Hide UI (if you add UI that is not in the main window directly)
return SynchronousShutdown;
}
} // namespace Internal
} // namespace EspressifToolchain
|
e988ddcfac938ac1136bd83a9acda05c48352505 | d453876b9c787523acd7a94f2ae56d79cd5806b6 | /books.h | c7bb94aa012a1e228f181924c70852e5ecf0a1f4 | [] | no_license | awais987123/Libarary-Management-System-with-complete-GUI | d1a9a15d295d77f601790f47023c047df91ad06a | a41750b175a163d0f00aaaada8fbdbc62331d032 | refs/heads/main | 2023-07-12T02:06:13.087941 | 2021-08-14T09:02:17 | 2021-08-14T09:02:17 | 395,948,064 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,895 | h | books.h | #pragma once
#ifndef BOOKS_H
#define BOOKS_H
#include<string>
#include<sstream>
#include<iomanip>
using namespace std;
class books // declaration of class
{
private://members variables
string title,
author,
publisher,
status;
int production_year,
copies,
item_id;
public://member functions
books();//default constructor
books(string t, string a, string p, int prd, int c, string s, int i);//parameterized constructor
books(string t, string a);//overloaded parameterized constructor for two parameters
books& setbook(string t, string a, string p, int prd, int c, string s, int id);//setter for all variables
string tostring() const;//return a string having all the values of member variables
string sptostring()const;//return a string having all the values of member variables seperated by ','
friend bool operator ==(const books& left, const books& right);//operator overload for comparison
bool copiesdecrement();//to decrease one from no of copies
string getbooktitle() const;//getter for title
string getbookauthor() const;//getter for author
string getbookstatus() const;//getter for status
string getbookpublisher() const;//getter for publisher
int getbookprodyear() const;//getter for production year
int getbookcopies() const;//getter for copies
int getbookitemid() const;//getter for item id
string isValidAuthor(string);//validation check for author
string isValidPublisher(string);//validation check for publisher
int isValidProductionYear(int);//validation check for production year
int isValidCopies(int);//validation check for copies
void incresebookcopies(int itemid);//increase the number of copies when an book is returned
void decreaseoneinitemid();//decrese in item id by one when an book is deleted
friend bool operator<(books& left, books& right);//operater overload for '<'
};
#endif // !BOOKS_H
|
e6e130c2aaaac2bd94969c778cd74170ded8c547 | 660bb7a494ba2d6d91b99ff7e319ba0961d690e4 | /Sprint4/destinationcity.h | 261687c751215ddeba1ef8f0d5bc489da9e612bc | [] | no_license | pattisonb/DataStructures | 5ce07ce59411e1f4cdb50f57d34b972d90936000 | 28589097ee833902b92869b7d3028fa9191f2c06 | refs/heads/master | 2020-12-29T23:47:44.040659 | 2019-11-08T22:31:08 | 2019-11-08T22:31:08 | 238,782,581 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 656 | h | destinationcity.h | #ifndef DESTINATIONCITY_H
#define DESTINATIONCITY_H
#include "dsstring.h"
class destinationCity
{
private:
DSString name;
DSString airline;
double cost;
double time;
public:
bool isVisited = false;
int timesVisited = 0;
destinationCity();
destinationCity(const destinationCity&);
destinationCity(DSString, DSString, double, double);
DSString getName();
DSString getAirline();
double getCost();
double getTime();
void setName(DSString);
void setPrice(double);
void setTime(double);
void setAirline(DSString);
bool operator != (const destinationCity&);
};
#endif // DESTINATIONCITY_H
|
da8c9b2cc899daf17b3884fc52e25075d45b224a | 4de392fee2aa29308cfdac7a45fa83b7a597a5a2 | /Project2/src/scenegraph/primitives/Flag.cpp | 213851ebe4705522ace1e32dfa19afd2c29bbea3 | [] | no_license | danfergo/FEUP-LAIG1415-T1G11 | 99a3d99dd2ee71065e263456fd565024e1b34bd2 | cab2d5d1886f71804b3a4b0732f8459ca308087e | refs/heads/master | 2021-01-20T11:57:14.657502 | 2015-01-05T17:42:26 | 2015-01-05T17:42:26 | 24,367,772 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 297 | cpp | Flag.cpp | #include "Flag.h"
#include <iostream>
FlagShader * Flag::shader = NULL;
Flag::Flag(std::string tex): Plane(100,1,1)
{
texture = new CGFtexture(tex);
}
void Flag::draw(Texture * texture){
FlagShader::activeTexture = this->texture;
shader->bind();
Plane::draw(texture);
shader->unbind();
} |
11657d2b142d7df0517aaecc8e58966c2823f245 | 853345c3ee9adeba2157b1805d77dd92049c7d3a | /STL/STL_1week _class_review/STL_1week _class_review/main.cpp | 2dae3468181e843d26921e6a7daca6965f5f8143 | [] | no_license | SuperHong94/2020_1_ | 9aea61ae1d3c97201fa0800ecae0acd1179bf93e | 7799b5a3979b63818ba8acc3f23247796189f9c9 | refs/heads/master | 2021-03-17T20:01:14.226581 | 2020-08-20T08:35:36 | 2020-08-20T08:35:36 | 247,012,963 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 1,772 | cpp | main.cpp | #include <iostream>
//자원을 할당하는 클래스
//문제 1 , 2
class Model
{
public:
static int cnt;
Model();
Model(size_t);
Model(const Model&);
Model(Model&&);
Model& operator=(const Model&);
Model& operator=(Model&&);
~Model();
private:
int id;
char* data;
size_t size; //unsinged int
};
Model::Model() :data(nullptr),size{ 0 }
{
id = cnt++;
std::cout << "생성! " << id<< '\n';
}
Model::Model(size_t n) :size{ n }
{
id = cnt++;
data = new char[n];
std::cout << "data 할당 생성! " << id << '\n';
}
Model::Model(const Model& other):size(other.size)
{
id = cnt++;
data = new char[size];
memcpy(data, other.data, size);
std::cout << "복사 생성 " << id << " " << &other << '\n';
}
Model& Model::operator=(const Model& x)
{
size = x.size;
data = new char[size];
memcpy(data, x.data, size);
std::cout << "복사 할당 " << id << " " << '\n';
return *this;
}
Model& Model::operator=( Model&& x)
{
size = x.size;
data = x.data;
x.data = nullptr;
x.size = 0;
std::cout << "이동할당 할당 " << id << " "<< '\n';
return *this;
}
Model::Model(Model&& other):data{nullptr},size(other.size)
{
id = cnt++;
data = other.data;
other.data = nullptr;
other.size = 0;
std::cout << "이동 생성자 " << id << '\n';
}
Model::~Model()
{
std::cout << "\n소멸" << " " << id << '\n';
if (data != NULL) {
std::cout << "data 삭제" << '\n';
delete[] data;
}
else
std::cout << "data는 없음" << '\n';
}
int Model::cnt = 0;
int main()
{
// Model a;
// Model b;
//Model c;
////c = b;
////std::move(b);
//문제 3~5
/*Model a;
Model b{ 1000 };
Model c = b;
a = c;*/
//문제6
//Model a[10];
//문제7~8
//Model a[10];
Model a{ 1000 };
Model b = std::move(a);
Model c;
c = std::move(a);
} |
bb98d50ccde7856941d5b76df0ee193fd5d6c725 | c8480b0a5f445ddd3aedf6e871810ebf8eda4262 | /source/physics.cpp | 68d0311f1e6966882fc1dd8bf43f8f90a04c3cd8 | [] | no_license | Gaspard--/The-great-SHEEP | 2df41aed8e5bb61a4e5ebbbd8ef155abbeb12b17 | 982c765eecbc9e768daa7a2c4b4bec0acd952d2b | refs/heads/master | 2020-04-11T03:01:01.338183 | 2017-03-18T10:27:19 | 2017-03-18T10:27:19 | 60,603,500 | 4 | 2 | null | 2016-06-26T10:58:33 | 2016-06-07T10:10:52 | C++ | UTF-8 | C++ | false | false | 1,200 | cpp | physics.cpp | #include "physics.hpp"
#include "fixture.hpp"
// |Vt + P| == r
// V\2t\2 + P\2 + V.Pt - r = 0
// Equation de degré 2:
//
double physics::collisionTest(Fixture &fixture, double max)
{
if (fixture.position.scalar(fixture.speed) > 0.0)
return (max);
double a(fixture.speed.scalar(fixture.speed));
double b(fixture.speed.scalar(fixture.position));
double c(fixture.position.scalar(fixture.position) - fixture.size / 2);
double delta(b * b - 4 * a * c);
if (delta < 0)
return (max);
if (delta == 0)
return (-b * 0.5 / a);
delta = sqrt(delta);
return (std::min((-b + delta) * 0.5 / a, (-b - delta) * 0.5 / a));
}
double physics::collisionTest(Fixture &fixture, Vect<2u, double>& point, double max)
{
Vect<2u, double> position(fixture.position - point);
Fixture tmp(position, fixture.speed, fixture.size);
return (collisionTest(tmp, max));
}
double physics::collisionTest(Fixture &fixture, Fixture &other, double max)
{
Vect<2u, double> position(fixture.position - other.position);
Vect<2u, double> speed(fixture.speed - other.speed);
double size(fixture.size + other.size);
Fixture tmp(position, speed, size);
return (collisionTest(tmp, max));
}
|
da99ef4ea112943ff0781e11450f585d5e5e3489 | c7f6aabcf4ed5b626ce3313d5f768448f74be499 | /289.game-of-life.cpp | 9045c69f81d6ece6b13914c9ff094706aa7a72b2 | [] | no_license | liuchy0427/Leetcode-Solution | f1e9bcf1384c3dd80da4e3402a46d93c9c5ee369 | dcc21f22070eb9d28f692bf98c041c70100d6d77 | refs/heads/main | 2023-03-29T12:16:35.651228 | 2021-03-29T01:50:19 | 2021-03-29T01:50:19 | 331,563,788 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,375 | cpp | 289.game-of-life.cpp | /*
* @lc app=leetcode id=289 lang=cpp
*
* [289] Game of Life
*/
// @lc code=start
class Solution {
public:
void gameOfLife(vector<vector<int>>& board) {
vector<vector<int>> tmp = board;
for(int i=0;i<tmp.size();i++){
for(int j=0;j<tmp[0].size();j++){
if(tmp[i][j] == 1)
board[i][j] = live(i, j, tmp);
else
board[i][j] = die(i, j, tmp);
}
}
}
int live(int index1, int index2, vector<vector<int>>& board){
int count = 0;
int m = board.size();
int n = board[0].size();
for(int i = max(0, index1-1);i<min(m,index1+2);i++){
for(int j=max(0, index2-1);j<min(n,index2+2);j++)
count += board[i][j];
}
if(count < 3)
return 0;
else if(count <= 4)
return 1;
else
return 0;
}
int die(int index1, int index2, vector<vector<int>>& board){
int count = 0;
int m = board.size();
int n = board[0].size();
for(int i = max(0, index1-1);i<min(m,index1+2);i++){
for(int j=max(0, index2-1);j<min(n,index2+2);j++)
count += board[i][j];
}
if(count == 3)
return 1;
return 0;
}
};
// @lc code=end
|
8f3b3db1decdaddd86b88bfa8dbdab919693bceb | 413ada855bc6b477dd6a66c3908e30927add8406 | /framework/channel/channel-common.h | 874952d342dd71a4be00bda43e960fc8fa086353 | [] | no_license | BRAHMS-SystemML/brahms | e6ba164a27cd428e5068571cbcb03caaac5517eb | 32ca5f7bb17b7ccd4dd41b0394f14f85ff99bcc7 | refs/heads/master | 2020-04-10T06:49:44.519094 | 2019-04-30T09:19:42 | 2019-04-30T09:19:42 | 21,689,838 | 0 | 2 | null | 2019-04-30T09:19:44 | 2014-07-10T10:06:52 | C++ | UTF-8 | C++ | false | false | 1,937 | h | channel-common.h | #ifndef _BRAHMS_CHANNEL_COMMON_H_
#define _BRAHMS_CHANNEL_COMMON_H_
#ifndef BRAHMS_BUILDING_ENGINE
#define BRAHMS_BUILDING_ENGINE
#endif
#include "brahms-client.h" // Ensure types are set up (INT32 etc)
#include "base/ipm.h" // ChannelPoolData
#include <string>
using std::string;
namespace brahms
{
namespace channel
{
enum Protocol
{
PROTOCOL_NULL = 0,
// note that the protocols are listed in preference order - earlier
// ones will be selected, if available, during reading of the Execution
// File
//
// note, also, that they are |'d during the parsing process, so they
// must be bit-exclusive (1, 2, 4, etc.)
PROTOCOL_MPI = 1,
PROTOCOL_SOCKETS = 2
};
// INITIALISATION DATA
// comms init data
struct CommsInitData
{
INT32 voiceIndex;
INT32 voiceCount;
};
// channel init data
struct ChannelInitData
{
// contact data
UINT32 remoteVoiceIndex;
string remoteAddress;
};
// AUDIT DATA
// channel simplex data
struct ChannelSimplexData
{
ChannelSimplexData();
UINT64 uncompressed;
UINT64 compressed;
UINT32 queue;
};
// channel audit data
struct ChannelAuditData
{
// send and recv
ChannelSimplexData send;
ChannelSimplexData recv;
// pool
brahms::base::ChannelPoolData pool;
};
// use default timeout rather than anything specific
const UINT32 COMMS_TIMEOUT_DEFAULT = 0x80000001;
// push data handler function prototype
typedef Symbol (*PushDataHandler)(void* arg, BYTE* stream, UINT32 count);
}
}
#endif // _BRAHMS_CHANNEL_COMMON_H_
|
4739f730d63e4bc845c839f280726becb83141f7 | b2d26f0c20253a65794e1dfc75a8273cf73db641 | /table/delete.cpp | f7e342baaa59a7ecc2c61ccf38e190dca3804bc0 | [] | no_license | hhsyy/door | 3fee5d3cdb453d06e768224513f61b79bfb42add | 76e025f0b216888c3ebc5ca861998bd4b1c52210 | refs/heads/master | 2021-08-28T06:52:01.250339 | 2017-12-11T13:29:32 | 2017-12-11T13:29:32 | 113,862,606 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 187 | cpp | delete.cpp | #include "delete.h"
#include "ui_delete.h"
delete::delete(QWidget *parent) :
QDialog(parent),
ui(new Ui::delete)
{
ui->setupUi(this);
}
delete::~delete()
{
delete ui;
}
|
3727a1fc0fc5d00efb376facdc6d9faa4afd8fe8 | 22d298e4a29a24aa93d83ef428e058ee59e397d7 | /client/game_objects/units/unit.h | f0eaebbdc625c4ade569637c886ca55471c989dc | [] | no_license | BlancoSebastianEzequiel/Z-Steel-Soldiers | c732462d3f9205f024ba9f1ccf2b044e55de3f46 | 9dd1caf9bc5af800bc0426ad7d613ad9941de534 | refs/heads/master | 2020-06-11T14:01:03.294744 | 2019-07-24T01:14:05 | 2019-07-24T01:14:05 | 193,990,060 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,127 | h | unit.h | #ifndef UNIT_H
#define UNIT_H
#include "../gameObject.h"
#include "../../frames/frame.h"
#include "vector"
#include "SDL/SDL.h"
#include "SDL/SDL_image.h"
#include "../../actions/unitAction.h"
#include "../ammos/ammo.h"
class UnitAction;
class Ammo;
class Unit: public GameObject {
protected:
std::vector<Frame> x_frames;
std::vector<Frame> y_frames;
std::vector<Frame> xy_frames;
std::vector<Frame>::iterator current_xframe;
std::vector<Frame>::iterator current_yframe;
std::vector<Frame>::iterator current_xyframe;
std::vector<Frame> x_shoot_frames;
std::vector<Frame> y_shoot_frames;
std::vector<Frame> xy_shoot_frames;
unsigned int frame_index;
UnitAction* current_action;
bool dead;
unsigned int owner_id;
//Desplaza la unidad hacia la izquierda o hacia la derecha, tantos
//pixeles como x especifique. Si x>0 se desplazara hacia la derecha
// y si x<0 se desplazara a la izquierda.
virtual void move_x(unsigned int dest_x, double speed);
//Desplaza la unidad hacia arriba o abajo , tantos
//pixeles como y especifique. Si y>0 se desplazara hacia arriba
// y si y<0 se desplazara abajo.
virtual void move_y(unsigned int dest_y, double speed);
//Desplaza la unidad en diagonal , tantos
//pixeles como x e y especifiquen.
virtual void move_xy(unsigned int dest_x,
unsigned int dest_y,
double speed);
//Dispara a una posicion hacia la izquierda o derecha de la actual
//dependiendo de si target_x>0 o target_x<0
virtual void shoot_x(GameObject* target) = 0;
//Dispara a una posicion hacia arriba o abajo de la actual
//dependiendo de si target_y>0 o target_y<0
virtual void shoot_y(GameObject* target) = 0;
//Realiza un disparo en diagonal hacia el punto de coordenadas
//pasadas por parametro
virtual void shoot_xy(GameObject* target) = 0;
public:
Unit(unsigned int id,
unsigned int owner_id,
unsigned int init_pos_x,
unsigned int init_pos_y);
~Unit();
//Retorna el id de la unidad.
unsigned int get_id();
//Le asigna al robot la siguiente accion que debe ejecutar, puede
//ser disparar, desplazarse hasta un punto en especifico, entre otras.
// Cualquier accion nueva interrumpe a la actual en caso de que no se
//haya completado
void new_command(UnitAction* action);
//Mueve la unidad al punto del mapa cuyas coordenadas coinciden con las
//pasadas por parametro
void move(unsigned int dest_x, unsigned int dest_y, double speed);
//Dispara a la posicion cuyas coordenadas son las pasadas por parametro
virtual void shoot(GameObject* target);
//Selecciona arbitrariamente el fotograma a mostrar cuanndo la unidad
//se detenga
void stand_still();
//Devuelve un proyectil del tipo que dispare la unidad
virtual Ammo* get_bullet(unsigned int bullet_id,
Unit* shooter, GameObject* target) = 0;
//Dibuja en la escena a la unidad
void draw(SDL_Surface* surface, Camera& camera);
//Metodos exclusivos para sincronizar con el modelo, permiten forzar la
//posicion de la unidad
void set_x(unsigned int dest_x);
void set_y(unsigned int dest_y);
//El atributo dead pasa a ser verdadero
void die();
//Devuelve true si la unidad esta muerta, y false en caso contrario
bool is_dead();
//Devuelve el id del jugador que tiene el control sobre la unidad
unsigned int get_owner_id();
virtual bool isUnit()const;
//--------------------------------------------------------------------------
virtual bool isBuilding()const;
//--------------------------------------------------------------------------
virtual bool isTerrainObject()const;
};
#endif // UNIT_H
|
a12bc49c628ed5506ec3e0aa37f74a56b2943116 | efb69f2b3960a6060361c662cdd0e715a4c5ad6f | /LAB4/Reader.h | bb9d0f597a2009a34e50026303c53ad33e562d4a | [] | no_license | andrejxz/LAB4 | c5e13d77a8a03c153f1791c4e874a7f8f7c73760 | e7b450610c6b7656d1019e83eb76be5baa8a1016 | refs/heads/master | 2021-01-13T07:17:31.632467 | 2016-12-07T07:03:47 | 2016-12-07T07:03:47 | 71,649,947 | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 744 | h | Reader.h | #pragma once
#include "stdafx.h"
#include "TableRow.h"
#include <string>
#include "Serializer.h"
// описывает читателя
class Reader : public TableRow
{
CString _fio;
CString _address;
CString _phone;
public:
CString GetFio() { return _fio; }
CString GetAddress() { return _address; }
CString GetPhone() { return _phone; }
void SetFio(CString fio) { _fio = fio; }
void SetAddress(CString address) { _address = address; }
void SetPhone(CString phone) { _phone = phone; }
virtual CString ToString()
{
CString ID;
ID.Format(_T("%u"), this->GetId());
return ID + L". " + GetFio();
}
};
template<>
void Serialize<Reader>(std::ostream &os, Reader& value);
template<>
Reader Deserialize<Reader>(std::istream &is); |
1487caab0a0a3222c9b7891724556a8ea34a13e5 | 32815cd1de61cfa78fd025486ba74249c08b009a | /college_life/timus/1581.cpp | 2bcfc5e181a78d51c9602c968320c035a38706f3 | [] | no_license | krshubham/compete | c09d4662eaee9f24df72059d67058e7564a4bc10 | d16b0f820fa50f8a7f686a7f93cab7f9914a3f9d | refs/heads/master | 2020-12-25T09:09:10.484045 | 2020-10-31T07:46:39 | 2020-10-31T07:46:39 | 60,250,510 | 2 | 1 | null | 2020-10-31T07:46:40 | 2016-06-02T09:25:15 | C++ | UTF-8 | C++ | false | false | 476 | cpp | 1581.cpp | #include <iostream>
#include <vector>
using namespace std;
typedef vector<int> Integers;
int main() {
int n;
cin >> n;
Integers numbers(n);
for (int i = 0; i < n; ++i) {
cin >> numbers[i];
}
int count = 0;
int num = -1;
for (int i = 0; i < n; ++i) {
if (numbers[i] == num) {
++count;
} else {
if (count) {
cout << count << " " << num << " ";
}
count = 1;
num = numbers[i];
}
}
if (count) {
cout << count << " " << num;
}
return 0;
} |
225ea47eb63061785610188d4445686a05b0894e | 06bed8ad5fd60e5bba6297e9870a264bfa91a71d | /operations/carloadeditframe.h | 1a21f4c60300f37bbaf994d963399d1a7ee04f2a | [] | no_license | allenck/DecoderPro_app | 43aeb9561fe3fe9753684f7d6d76146097d78e88 | 226c7f245aeb6951528d970f773776d50ae2c1dc | refs/heads/master | 2023-05-12T07:36:18.153909 | 2023-05-10T21:17:40 | 2023-05-10T21:17:40 | 61,044,197 | 4 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 2,173 | h | carloadeditframe.h | #ifndef CARLOADEDITFRAME_H
#define CARLOADEDITFRAME_H
#include "operationsframe.h"
#include "appslib_global.h"
#include "jcombobox.h"
class PropertyChangeEvent;
class JTextField;
class QLabel;
namespace Operations
{
class CarLoads;
class APPSLIBSHARED_EXPORT CarLoadEditFrame : public OperationsFrame
{
Q_OBJECT
public:
CarLoadEditFrame(QWidget* parent = 0);
/*public*/ static /*final*/ QString NONE;// = "";
/*public*/ void initComponents(QString type, QString select);
/*public*/ void toggleShowQuanity();
/*public*/ void dispose();
/*public*/ QString getClassName();
public slots:
/*public*/ void propertyChange(PropertyChangeEvent* e);
/*public*/ void buttonActionPerformed(QWidget* ae);
private:
CarLoads* carLoads;//= CarLoads.instance();
// labels
QLabel* textSep;//= new JLabel();
QLabel* quanity;//= new JLabel("0");
// major buttons
JButton* addButton;//= new JButton(Bundle.getMessage("Add"));
JButton* deleteButton;//= new JButton(Bundle.getMessage("Delete"));
JButton* replaceButton;//= new JButton(Bundle.getMessage("Replace"));
JButton* saveButton;//= new JButton(Bundle.getMessage("Save"));
// combo boxes
JComboBox* loadComboBox;
JComboBox* priorityComboBox;
JComboBox* loadTypeComboBox;//= carLoads.getLoadTypesComboBox();
// text boxes
JTextField* addTextBox;//= new JTextField(10);
JTextField* pickupCommentTextField;//= new JTextField(35);
JTextField* dropCommentTextField;//= new JTextField(35);
QString _type;
bool menuActive;// = false;
Logger* log;
bool showQuanity;// = false;
/*private*/ void loadComboboxes();
/*private*/ void updateLoadType();
/*private*/ void updatePriority();
/*private*/ void updateCarQuanity();
/*private*/ void updateCarCommentFields();
/*private*/ void replaceAllLoads(QString oldLoad, QString newLoad) ;
/*private*/ void deleteLoadFromCombobox(QString type, QString name);
/*private*/ void replaceLoad(QString type, QString oldLoad, QString newLoad);
/*private*/ void addLoadToCombobox(QString type, QString name);
protected slots:
/*protected*/ void comboBoxActionPerformed(QWidget* ae);
};
}
#endif // CARLOADEDITFRAME_H
|
1c0f840df905004b76b12310c048a24e6868c994 | ebab7a4b4fd80065d1dbdb7cf6c70405c0b98943 | /hcml-test.cpp | b2185c59802d923cbe95dd5a501a17ea109538c8 | [
"MIT"
] | permissive | littlepush/hcml | 5c111b2a5102611f4400ea30d7dca11dcfe1cab4 | c44ac6be9bfb452435061aa5d911bffe5b74e51e | refs/heads/master | 2021-03-23T14:26:38.650070 | 2020-03-19T10:25:38 | 2020-03-19T10:25:38 | 247,462,426 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 426 | cpp | hcml-test.cpp | #include "hcml.h"
int main( int arg, char * argv [] ) {
hcml_t _h = hcml_create();
hcml_set_print_method(_h, "resp.write");
// Parse the input file
int _r = hcml_parse(_h, argv[1]);
if ( _r == HCML_ERR_OK ) {
printf("%s\n", hcml_get_output(_h) );
} else {
printf("%.*s\n", hcml_get_output_size(_h), hcml_get_errstr(_h) );
}
hcml_destroy(_h);
return 0;
} |
f06ab55d22f46f0824f4ff2970e6b72637c5ecfd | 9b6c46aa2b28a5a172e244232f9df309f6c5404c | /pstree/pstree/process.h | b5ccee7aafca170486e2c26a32789acacae5a018 | [
"MIT"
] | permissive | Jostyck9/Process-Tree | 3296c1d0c7ea6d776b26900e07f5527acdb80d3d | 590129c935c04d315f48f28314f9e7a17becd3c4 | refs/heads/main | 2023-04-30T07:38:41.582792 | 2021-05-17T08:50:00 | 2021-05-17T08:50:00 | 366,967,150 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 237 | h | process.h | #pragma once
#include <windows.h>
#include <list>
#include <memory>
typedef struct sProcess Process;
typedef struct sProcess {
WCHAR name[MAX_PATH];
DWORD id;
DWORD parentId;
std::list<std::shared_ptr<Process>> children;
} Process; |
382a349bf11eb6e4f3142b9a3346cd885b3b9d12 | 03b5b626962b6c62fc3215154b44bbc663a44cf6 | /src/instruction/PUSHFD.cpp | 361ce26f74ccc85017a1e3e198946976acc4864a | [] | no_license | haochenprophet/iwant | 8b1f9df8ee428148549253ce1c5d821ece0a4b4c | 1c9bd95280216ee8cd7892a10a7355f03d77d340 | refs/heads/master | 2023-06-09T11:10:27.232304 | 2023-05-31T02:41:18 | 2023-05-31T02:41:18 | 67,756,957 | 17 | 5 | null | 2018-08-11T16:37:37 | 2016-09-09T02:08:46 | C++ | UTF-8 | C++ | false | false | 183 | cpp | PUSHFD.cpp | #include "PUSHFD.h"
int CPUSHFD::my_init(void *p)
{
this->name = "CPUSHFD";
this->alias = "PUSHFD";
return 0;
}
CPUSHFD::CPUSHFD()
{
this->my_init();
}
CPUSHFD::~CPUSHFD()
{
}
|
977df48775ad01a9bebed6cc4d23318417f35119 | 1cecbd8d44397ea8db757b963cd74ef5d0ebd9a4 | /RayTracing_Cuda/rtcuda.h | 4ba97732f9734fd89edf2862d28f8848e58b89c6 | [] | no_license | weslse/RayTracing_Cuda | 0afdeb26edc4199c892da520b5cd61c49be67cef | d240f339a64feffd0fed083d2e80471a3e3386b3 | refs/heads/main | 2023-02-14T02:17:43.212275 | 2021-01-06T09:20:31 | 2021-01-06T09:20:31 | 326,907,016 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 300 | h | rtcuda.h | #pragma once
// Common Headers
#include "ray.h"
#include "vec3.h"
// Constants
__constant__ float infinity = std::numeric_limits<float>::infinity();
__constant__ float pi = 3.141592f;
// Utility Functions
__device__ inline float degrees_to_radians(float degrees) {
return degrees * pi / 180.f;
}
|
5eece54368c7b2d3e1352420409ab98c2440c471 | f55405e83541ba9f95dce39ef9a0be5420861ed2 | /Code/main.cpp | 4be5c05c7df667bf934786ad7c438eada593615c | [] | no_license | jamieson1995/AStar-Pathfinding | ef2a613b4d417ac3de4dd04eade8787765a3ea0a | ae5bea1de301aeb8f0ca43fce9de1a4a95c928d9 | refs/heads/master | 2021-01-11T04:10:19.414177 | 2016-10-18T11:34:41 | 2016-10-18T11:34:41 | 71,238,552 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,710 | cpp | main.cpp | #include <SDL.h>
#include <iostream>
#include <math.h>
#include "Images.h"
#include "ScreenManager.h"
bool init(const int SCREEN_HEIGHT, const int SCREEN_WIDTH);
void close();
ScreenManager Screen;
int main(int argc, char** argv){
bool quit = false;
SDL_Event event;
int Active_Tile = 0;
const int SCREEN_HEIGHT = 900;
const int SCREEN_WIDTH = 768;
if( !init(SCREEN_HEIGHT, SCREEN_WIDTH) ){
std::cout << "Failed to initialise" << std::endl;
}
else
{
if ( !Screen.loadMedia() )
{
std::cout << "Failed to load media" << std::endl;
}
else
{
Screen.Update(NULL, NULL);
}
}
int mouse_x, mouse_y;
while (!quit){
while(SDL_PollEvent(&event))
{
if ( ( SDL_GetMouseState(&mouse_x, &mouse_y) ) && ( event.type == SDL_MOUSEBUTTONDOWN ) ){
Screen.Mouse_Controller(mouse_x, mouse_y);
}
Screen.Update(mouse_x, mouse_y);
if (event.type == SDL_QUIT)
quit = true;
}
}
close();
return 0;
}
bool init(const int SCREEN_HEIGHT, const int SCREEN_WIDTH){
bool success = true;
if (SDL_Init( SDL_INIT_VIDEO ) < 0){
std::cout << "SDL not initialized! SDL_Error: " << SDL_GetError() << std::endl;
success = false;
}
else
{
Screen.setWindow( SDL_CreateWindow( "AI Pathfinding Assignment", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN ) );
if( Screen.getWindow() == NULL )
{
std::cout << "Window could not be created! SDL_Error: " << SDL_GetError() << std::endl;
success = false;
}
else
{
Screen.setScreen(SDL_GetWindowSurface( Screen.getWindow() ) );
}
}
return success;
}
void close(){
Screen.Close();
SDL_Quit();
} |
65d961cadc9691e8f7bf888b6dd9dfc1f8f4cf97 | d1427c0b9c5cb618b4dd77703139e4de3a0b6a61 | /main.cpp | d6dc63ccb313ef283a4d0a2f386e4111329b27e4 | [] | no_license | 80deardorff/String-Pyramid-Builder | c8bc3693080f0cb169b78d0d6af5eedee9421131 | 2803f0f21371da65339169d3d988b7aee73f1878 | refs/heads/master | 2020-03-28T22:01:53.045705 | 2018-09-17T23:22:00 | 2018-09-17T23:22:00 | 149,200,229 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 965 | cpp | main.cpp | #include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
string message {};
cout << "Enter a sentence and press Enter: ";
getline(cin, message);
cout << endl << endl;
size_t spaces {message.length() - 1};
size_t index {message.length()};
string reversed_message {message};
reverse(reversed_message.begin(), reversed_message.end());
size_t counter {1};
if (message.length() != 0) {
for (size_t i{0}; i < message.length(); ++i) {
for (size_t j {spaces}; j >= 1; --j) {
cout << " ";
}
for (size_t j {0}; j < counter; ++j) {
cout << message.at(j);
}
for (size_t j {1}; j < counter; ++j, ++index) {
cout << reversed_message.at(index);
}
for (size_t j {spaces}; j >= 1; --j) {
cout << " ";
}
index = message.length() - counter;
++counter;
--spaces;
cout << endl;
}
} else {
cout << "\nNo message was submitted....Goodbye." << endl;
}
cout << endl;
return 0;
} |
c2cae7978ddf18c7d489b8fbc37b38f38cb006e1 | 221e3e713891c951e674605eddd656f3a4ce34df | /core/OUE/Error.cpp | b5f35e3ed9913b3865bb248efec32f6446b5a99d | [
"MIT"
] | permissive | zacx-z/oneu-engine | da083f817e625c9e84691df38349eab41d356b76 | d47a5522c55089a1e6d7109cebf1c9dbb6860b7d | refs/heads/master | 2021-05-28T12:39:03.782147 | 2011-10-18T12:33:45 | 2011-10-18T12:33:45 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 4,897 | cpp | Error.cpp | /*
This source file is part of OneU Engine.
Copyright (c) 2011 Ladace
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "OneUPreDef.h"
#include "Error.h"
#include <cstdlib>
#include <errno.h>
#include "String.h"
#include "Logger.h"
#include "Impl/Win32.h"
#ifdef __GNUC__
typedef int errno_t;
#endif
#pragma warning( disable : 4311 )
namespace OneU
{
#ifdef ONEU_USE_ASSERT
void DumpString( pcwstr str )
{
OutputDebugString( str );
}
#endif
}
#pragma warning( default : 4311 )
namespace OneU
{
extern "C" ONEU_API pcwstr GetErrnoString( errno_t Errno )
{
switch( Errno )
{
case EPERM:
return L"Operation not permitted";
case ENOENT:
return L"No such file or directory";
case ESRCH:
return L"No such process";
case EINTR:
return L"Interrupted system call";
case EIO:
return L"I/O error";
case ENXIO:
return L"No such device or address";
case E2BIG:
return L"Arg list too long";
case ENOEXEC:
return L"Exec format error";
case EBADF:
return L"Bad file number";
case ECHILD:
return L"No child processes";
case EAGAIN:
return L"Try again";
case ENOMEM:
return L"Out of memory";
case EACCES:
return L"Permission denied";
case EFAULT:
return L"Bad address";
case EBUSY:
return L"Device or resource busy";
case EEXIST:
return L"File exists";
case EXDEV:
return L"Cross-device link";
case ENODEV:
return L"No such device";
case ENOTDIR:
return L"Not a directory";
case EISDIR:
return L"Is a directory";
case EINVAL:
return L"Invalid argument";
case ENFILE:
return L"File table overflow";
case EMFILE:
return L"Too many open files";
case ENOTTY:
return L"Not a typewriter";
case EFBIG:
return L"File too large";
case ENOSPC:
return L"No space left on device";
case ESPIPE:
return L"Illegal seek";
case EROFS:
return L"Read-only file system";
case EMLINK:
return L"Too many links";
case EPIPE:
return L"Broken pipe";
case EDOM:
return L"Math argument out of domain of func";
case ERANGE:
return L"Math result not representable";
case EDEADLK:
return L"Resource deadlock would occur";
case ENAMETOOLONG:
return L"File name too long";
case ENOLCK:
return L"No record locks available";
case ENOSYS:
return L"Function not implemented";
case ENOTEMPTY:
return L"Directory not empty";
case EILSEQ:
return L"Illegal byte sequence";
#ifdef _MSC_VER_
case STRUNCATE:
return L"A string copy or concatenation resulted in a truncated string";
#endif
default:
return L"An unknown error occurs";
}//switch
}//GetErrorString
static TerminateHandler s_eh = NULL;
static bool isTerminating = false;
void _TerminateApp(const char * FileName, const int Line, const char* Function, pcwstr str ){
if(isTerminating){
MessageBoxW(g_hWnd, L"二次异常抛出!!", L"错误", MB_OK | MB_ICONERROR);
}
isTerminating = true;
GetLogger().stream(ILogger::ML_CRITICAL) << FileName << L':' << Line << L"\nFunction:" << Function << L"\n发生异常,程序终止执行。\n异常信息:" << str;
::MessageBoxW(g_hWnd, str, L"错误", MB_OK | MB_ICONERROR);
//调用ExitHandler
if(s_eh != NULL)s_eh();
//Logger和Allocator应该在Game析构函数(在s_eh中)销毁 为了顾及不安全情况 在这里再调用销毁函数一次
Logger_destroy();
exit(-1);
}
TerminateHandler SetTerminateHandler(TerminateHandler eh)
{
TerminateHandler ret = s_eh;
s_eh = eh;
return ret;
}
ONEU_API void Prompt( pcwstr message )
{
::MessageBoxW(g_hWnd, message, L"Message", MB_OK);
}
ONEU_API void ErrorBox(pcwstr message, pcwstr captain){
::MessageBoxW(g_hWnd, message, captain, MB_OK | MB_ICONERROR);
}
}
|
736c4064b65b3544699f3b56086638d5502a195e | 5c3c559b9accafebcbd143f543ecf20dd4410269 | /Catastrophe/Game/velocity direction.hpp | 21f837350b645fbbe629b1fc1f0af1b1e613c941 | [] | no_license | indianakernick/Catastrophe | cd2688af966755d934c20aafdb73562674071939 | 8b50525c43c4f6d6b034e98c1882ded492745458 | refs/heads/master | 2022-05-24T13:45:30.678733 | 2018-10-06T09:32:44 | 2018-10-06T09:32:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 594 | hpp | velocity direction.hpp | //
// velocity direction.hpp
// Catastrophe
//
// Created by Indi Kernick on 21/10/17.
// Copyright © 2017 Indi Kernick. All rights reserved.
//
#ifndef velocity_direction_hpp
#define velocity_direction_hpp
#include <glm/vec2.hpp>
class VelDir1 {
public:
VelDir1() = default;
explicit VelDir1(float);
float getDir(float);
float getDir() const;
private:
float lastDir = 1.0f;
};
class VelDir2 {
public:
VelDir2() = default;
explicit VelDir2(const glm::vec2);
glm::vec2 getDir(glm::vec2);
glm::vec2 getDir() const;
private:
VelDir1 x;
VelDir1 y;
};
#endif
|
04c7b631951964b497adbca048f84942d45caff8 | 90ff6d52061bc23deecbbaf60fe4b9b54aca4b7b | /solidarity/event.h | 2c52f8b34eaad9bcc26a3ce1da55012983e1e460 | [
"Apache-2.0"
] | permissive | lysevi/solidarity | 6e3ee5fd26a0f26f7d89ed8a96f4334ccacbb8dd | c4febebce2247b5ab628bea226aa5e7e4805a1e5 | refs/heads/master | 2021-06-29T01:18:07.694329 | 2020-10-01T10:41:24 | 2020-10-01T10:41:24 | 171,683,290 | 1 | 0 | Apache-2.0 | 2019-08-19T07:07:19 | 2019-02-20T13:59:59 | C++ | UTF-8 | C++ | false | false | 1,161 | h | event.h | #pragma once
#include <solidarity/error_codes.h>
#include <solidarity/exports.h>
#include <solidarity/node_kind.h>
#include <solidarity/raft.h>
#include <optional>
namespace solidarity {
enum class command_status : uint8_t {
WAS_APPLIED,
APPLY_ERROR,
CAN_BE_APPLY,
CAN_NOT_BE_APPLY,
IN_LEADER_JOURNAL,
ERASED_FROM_JOURNAL,
LAST
};
EXPORT std::string to_string(const command_status s);
struct command_status_event_t {
command_status status;
uint32_t crc;
};
struct network_state_event_t {
ERROR_CODE ecode = ERROR_CODE::OK;
};
struct raft_state_event_t {
NODE_KIND old_state;
NODE_KIND new_state;
};
// TODO move to dedicated header.
struct cluster_state_event_t {
std::string leader;
std::unordered_map<std::string, log_state_t> state;
};
struct client_event_t {
enum class event_kind { UNDEFINED, RAFT, NETWORK, COMMAND_STATUS, LAST };
event_kind kind = event_kind::UNDEFINED;
std::optional<raft_state_event_t> raft_ev;
std::optional<network_state_event_t> net_ev;
std::optional<command_status_event_t> cmd_ev;
};
[[nodiscard]] EXPORT std::string to_string(const client_event_t &cev);
} // namespace solidarity |
e6b204b2eeb6f4f3fba073a9cc8b1030f48cc791 | be460e66f05c0259cf45e6c0cdb653fc2913972d | /acm/Online-Judge/hdu/code/hdu5006.cpp | b49dc5163c616b7ba663da13352a0c77578ede2d | [] | no_license | Salvare219/CodeLibrary | 3247aee350402dac3d94e059a8dc97d5d5436524 | 8961a6d1718c58d12c21a857b23e825c16bdab14 | refs/heads/master | 2021-06-16T18:38:21.693960 | 2017-05-09T12:47:36 | 2017-05-09T12:47:36 | 81,569,241 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,666 | cpp | hdu5006.cpp | #include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<vector>
#include<queue>
using namespace std;
vector<int>g[10050];
vector<int>w[10050];
int com[10050];
int lab[10050];
bool v[10050];
int find(int s)
{
return com[s]==s?s:com[s]=find(com[s]);
}
double a[1050][1050];
double x[1050];
int sgn(double x)
{
return fabs(x)<1e-8?0:(x>0.0?1:-1);
}
int Gauss(int equ,int var)
{
int i,j,k,max_r,col=0;
for(i=0;i<=var;i++)
x[i]=0.0;
for(k=0;k<equ && col<var;k++,col++)
{
max_r=k;
for(i=k+1;i<equ;i++)
if(fabs(a[i][col])>fabs(a[max_r][col])) max_r=i;
if(max_r!=k) for(j=k;j<var+1;j++) swap(a[k][j],a[max_r][j]);
if(sgn(a[k][col])==0)
{
k--;
continue;
}
for(i=k+1;i<equ;i++)
if(sgn(a[i][col])!=0)
{
double tt=a[i][col]/a[k][col];
for(j=col;j<var+1;j++)
a[i][j]-=a[k][j]*tt;
}
}
for(i=k;i<equ;i++)
if(sgn(a[i][col])!=0)return -1;
if(k<var)
{
return var-k;
}
else
{
for(i=var-1;i>-1;i--)
{
double temp=a[i][var];
for(j=i+1;j<var;j++)
if(a[i][j]!=0)temp-=a[i][j]*x[j];
x[i]=temp/a[i][i];
}
return 0;
}
}
int main()
{
int tt;scanf("%d",&tt);
while(tt--)
{
int n,m,s,t;
scanf("%d%d%d%d",&n,&m,&s,&t);
for(int i=1;i<=n;i++)
{
g[i].clear();w[i].clear();
com[i]=i;lab[i]=-1;v[i]=0;
}
for(int i=0;i<m;i++)
{
int x,y,z;
scanf("%d%d%d",&x,&y,&z);
if(z)g[x].push_back(y);
else w[x].push_back(y);
com[find(x)]=find(y);
}
if(find(s)!=find(t))puts("inf");
else
{
for(int i=1;i<=n;i++)
if(find(i)==find(s))v[i]=1;
for(int i=1;i<=n;i++)com[i]=i;
for(int i=1;i<=n;i++)
if(v[i])
for(int j=0;j<w[i].size();j++)
com[find(i)]=find(w[i][j]);
if(find(s)==find(t))puts("0.000000");
else
{
int cnt=0,sx,sy;
for(int i=1;i<=n;i++)
if(v[i])
if(lab[find(i)]==-1)
lab[find(i)]=cnt++;
for(int i=1;i<=n;i++)
if(lab[find(i)]!=-1)
for(int j=0;j<g[i].size();j++)
{
sx=lab[find(i)];
sy=lab[find(g[i][j])];
a[sx][sy]++;
a[sx][sx]--;
a[sy][sx]++;
a[sy][sy]--;
}
sx=lab[find(s)];sy=lab[find(t)];
a[sx][cnt]=-1.0;
a[sy][cnt]=1.0;
for(int i=0;i<cnt;i++)
a[cnt-1][i]=0;
a[cnt-1][sx]=1.0;
a[cnt-1][cnt]=1.0;
Gauss(cnt,cnt);
printf("%.6f\n",1.0-x[sy]);
for(int i=0;i<=cnt;i++)
for(int j=0;j<=cnt;j++)
a[i][j]=0;
}
}
}
return 0;
}
|
79a8315ed58c63a7e2da39a2a0bd0cbae9feaed3 | fa28b1ad5b7510b3b4228573c304bc4e39aba2e6 | /src/pwgen.h | c85c71c279b7d0f8bf477e5888764e37cdebfbbc | [
"CC-BY-4.0"
] | permissive | enivium/password_generator | e942b2fb8ba0d2b398dcb66a9354ef2f06fba73e | 8aefaf32c9d95111617872533a607d3bfee61a0e | refs/heads/master | 2020-04-28T08:27:48.031170 | 2019-04-22T03:04:23 | 2019-04-22T03:04:23 | 175,127,574 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 299 | h | pwgen.h | // pwgen.h
// Functions and variables for the password generator program
#pragma once
#include <vector>
// The number of characters to pull from /dev/urandom on each read
const int rand_vec_length = 20;
// Fill the vector with psuedo-random bytes
int fill_rand_vec(std::vector<char> &rand_vec);
|
886061d8f3d34f32e0399a4708cc237b331f0cb6 | 1f774438979d1c2ad5d56b963a99c8b4e8d70406 | /Examples+Challenges+Functions/Netwon Backward Interpolation.cpp | fca27cd701d26374b3fd422abbf9ce784e10f010 | [] | no_license | SparkyTS/CPP | f62a247778cbd66bd1ff7040ae334324ea82a5d0 | a2c0c91472993151c04212028ed6178b5ee2397e | refs/heads/master | 2020-05-01T10:35:00.484244 | 2019-03-24T14:22:39 | 2019-03-24T14:22:39 | 177,423,462 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,712 | cpp | Netwon Backward Interpolation.cpp | #include<stdio.h>
float x[20]/*={1891,1901,1911,1921,1931}*/;
float y[20]/*={46,66,81,93,101}*/;
float temp[20];
static int length;
show_steps()
{
int i;
static int count=length;
for(i=0;i<count;i++) printf(" %0.2f ",y[i]); printf("\n"); count--;
}
get_tabular()
{ int i,j,k;
show_steps();
for(j=length;j>1;j--)
{
for(i=length-1;i>=0;i--)
if((i+1)>=j)
temp[i]=y[i];
else
temp[i]=y[i+1]-y[i];
for(k=0;k<length;k++)
y[k]=temp[k];
show_steps();
}
}
int fact(int n)
{
int i,f=1;
for (i=2;i<=n;i++) f *= i;
return f;
}
show_tabular()
{
int i,j;
printf("\n\nTabular Values Are : \n\n");
for(i=0,j=length-1;i<length/2;i++,j--) y[i]=y[j]+y[i]-(y[j]=y[i]);
for(i=0;i<length;i++)
printf(" %0.2f ",y[i]);
}
main()
{
float h,p,f,sum,a;int i;
printf("What is the length of table : "); scanf("%d",&length);
printf("\nEnter the values of x : "); for(i=0;i<length;i++) scanf("%f",&x[i]);
printf("\nEnter the values of y(x) : "); for(i=0;i<length;i++) scanf("%f",&y[i]);
printf("\nEnter the value of Xn to find : "); scanf("%f",&f);
get_tabular(); show_tabular();
sum=y[0]; h=x[1]-x[0]; p=(f-x[length-1])/h;
for(i=1,a=p;i<length;i++)
{
sum+=(a*y[i])/fact(i);
a=a*(p+i);
}
printf("\n\n y(%0.f) = %0.2f\n",f,sum);
printf("\n\n--------------------------------------------------------------------- - ______________________________________ |\n|\n|\n|\n|\n|\n|\n|\n|\n|\n|\n|\n|\n|\n|\n|\n|\n|\n|\n|\n|\n ");
}
|
a2a7fab32793e4ae65ac9de72ce5937a3bc28fad | b2928ec6d1d7e6399db4b7803260d002e809ac92 | /ISHavok/Havok.h | eb7c681204d3200bcbaa6daaccb61a8ba288775e | [] | no_license | gui-works/IronSightEngine | 7884fb8f9bae1f60e02136a904b158f97d3d6322 | ec7ab97565ec3d45995b976ea76d5bc57bd1b675 | refs/heads/master | 2020-07-18T03:55:07.872387 | 2018-03-30T14:33:19 | 2018-03-30T14:33:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 22,767 | h | Havok.h | #ifndef __HAVOK_H
#define __HAVOK_H
#include "ISHavok.h"
#include "..\\global\\HKResult.h"
#include <map>
/*#include <Common/Base/hkBase.h>
#include <Common/Base/Memory/Allocator/Malloc/hkMallocAllocator.h>
#include <Common/Base/Memory/System/Util/hkMemoryInitUtil.h>
#include <Physics/Collide/Shape/Convex/Box/hkpBoxShape.h>
#include <Physics/Dynamics/RegularEntity/hkpRigidBody.h>
#include <Physics/Dynamics/RegularEntity/hkpRigidBodyCinfo.h>
#include <Physics/Utilities/Dynamics/Inertia/hkpInertiaTensorComputer.h>*/
#pragma comment (lib, "hkInternal.lib")
#pragma comment (lib, "hkGeometryUtilities.lib")
#pragma comment (lib, "hkVisualize.lib")
#pragma comment (lib, "hkSerialize.lib")
#pragma comment (lib, "hkCompat.lib")
#pragma comment (lib, "hkSceneData.lib")
#pragma comment (lib, "hkBase.lib")
#pragma comment (lib, "hkcdCollide.lib")
#pragma comment (lib, "hkcdInternal.lib")
#pragma comment (lib, "hkpUtilities.lib")
#pragma comment (lib, "hkpDynamics.lib")
#pragma comment (lib, "hkpCollide.lib")
#pragma comment (lib, "hkpConstraintSolver.lib")
#pragma comment (lib, "hkpInternal.lib")
#pragma comment (lib, "hkpVehicle.lib")
#pragma comment (lib, "hkaInternal.lib")
#pragma comment (lib, "hkaAnimation.lib")
#pragma comment (lib, "hkaRagdoll.lib")
/*#pragma comment (lib, "hkgBridge.lib")
#pragma comment (lib, "hkgOgls.lib")
#pragma comment (lib, "hkgOglES.lib")
#pragma comment (lib, "hkgOglES2.lib")
#pragma comment (lib, "hkgDx11.lib")
#pragma comment (lib, "hkgDx9s.lib")
#pragma comment (lib, "hkgSoundCommon.lib")
#pragma comment (lib, "hkgSoundXAudio2.lib")
#pragma comment (lib, "hkgCommon.lib")*/
/*// Register Havok classes.
#include <Common/Base/KeyCode.cxx>
#define HK_CLASSES_FILE <Common/Serialize/Classlist/hkKeyCodeClasses.h>
//#include <Common/Serialize/Util/hkBuiltinTypeRegistry.cxx>
// Select product features
//#include <Common/Base/keycode.cxx>
#include <Common/Base/Config/hkProductFeatures.cxx>
// No backward compatibility needed
#define HK_SERIALIZE_MIN_COMPATIBLE_VERSION Current*/
#include <Common/Base/hkBase.h>
#include <Common/Base/Memory/System/Util/hkMemoryInitUtil.h>
#include <Common/Base/Memory/Allocator/Malloc/hkMallocAllocator.h>
#include <Common/Base/Memory/Allocator/LargeBlock/hkLargeBlockAllocator.h>
#include <Common/Base/Memory/System/FreeList/hkFreeListMemorySystem.h>
#include <Common/Base/Fwd/hkcstdio.h>
#include <Common/Base/Ext/hkBaseExt.h>
#include <Physics/Dynamics/Phantom/hkpSimpleShapePhantom.h>
#include <Physics/Utilities/CharacterControl/CharacterProxy/hkpCharacterProxy.h>
#include <Physics/Utilities/CharacterControl/StateMachine/hkpDefaultCharacterStates.h>
#include <Physics/Utilities/CharacterControl/CharacterRigidBody/hkpCharacterRigidBody.h>
#include <Physics/Utilities/Actions/MouseSpring/hkpMouseSpringAction.h>
#include <Physics/Utilities/Weapons/hkpBallGun.h>
#include <Physics/Vehicle/hkpVehicleInstance.h>
#include <Physics/Collide/Filter/Group/hkpGroupFilter.h>
#include <Physics/Dynamics/Constraint/Util/hkpConstraintStabilizationUtil.h>
// Physics
#include <Physics/Dynamics/World/hkpWorld.h>
#include <Physics/Collide/Dispatch/hkpAgentRegisterUtil.h>
#include <Physics/Dynamics/Entity/hkpRigidBody.h>
#include <Physics/Collide/Shape/HeightField/Plane/hkpPlaneShape.h>
#include <Physics/Utilities/Dynamics/Inertia/hkpInertiaTensorComputer.h>
#include <Physics/Internal/Collide/BvCompressedMesh/hkpBvCompressedMeshShape.h>
#include <Physics/Internal/Collide/BvCompressedMesh/hkpBvCompressedMeshShapeCinfo.h>
#include <Common/Base/Types/Geometry/hkGeometry.h>
// Animation
#include <Animation/Ragdoll/Instance/hkaRagdollInstance.h>
#include <Animation/Ragdoll/Controller/RigidBody/hkaRagdollRigidBodyController.h>
#include <Animation/Animation/Rig/hkaPose.h>
#include <Animation/Animation/Playback/hkaAnimatedSkeleton.h>
#include <Animation/Animation/Animation/Interleaved/hkaInterleavedUncompressedAnimation.h>
#include <Animation/Animation/Playback/Control/Default/hkaDefaultAnimationControl.h>
#include <Animation/Animation/Rig/hkaBoneAttachment.h>
#include <Animation/Animation/Ik/FootPlacement/hkaFootPlacementIkSolver.h>
// Visualization
#include <Common/Visualize/hkVisualDebugger.h>
#include <Physics/Utilities/VisualDebugger/hkpPhysicsContext.h>
// Serialization
#include <Common/Serialize/Util/hkSerializeUtil.h>
#define HAVOK_RELEASE(obj) {if(obj) {(obj)->removeReference(); (obj) = HK_NULL;}}
struct StringComparator
{
bool operator()(const String& str1, const String& str2) const {return std::strcmp(str1, str2) < 0;}
};
class Entity
{
public:
virtual void PreUpdate() {}
virtual void Update() {};
virtual void Release() = 0;
};
class Havok;
class RagdollEntity;
class hkpStaticCompoundShape;
//-----------------------------------------------------------------------------
// Name: Weapon
// Desc: Uses Havok utility functions to act as a projectile gun
//-----------------------------------------------------------------------------
class Weapon : public IWeapon
{
private:
Havok* parent;
hkpBallGun* ballgun;
Vector3* vpos;
Quaternion* qrot;
public:
Weapon(Havok* parent) : parent(parent), ballgun(NULL) {}
Result Init();
void Fire(Vector3* vpos, Quaternion* qrot);
void Update();
void Release();
};
//-----------------------------------------------------------------------------
// Name: Vehicle
// Desc: A vehicle with Havok car pyhsics
//-----------------------------------------------------------------------------
class Vehicle : public IVehicle
{
private:
Havok* parent;
hkpVehicleInstance* vehicle;
Vector3* vpos;
Quaternion* qrot;
public:
Vehicle(Havok* parent);
Result Init(const VehicleDesc* vehicledesc, Vector3* vpos, Quaternion* qrot);
void PreUpdate();
void Update();
void Release();
};
//-----------------------------------------------------------------------------
// Name: Pose
// Desc: A collection of bone transformations represented in model and local spaces, based on the hierarchy of a given skeleton
//-----------------------------------------------------------------------------
class Pose : public IPose
{
private:
Vector3** pivots;
hkArray<hkQsTransform> localtransforms;
public:
hkaPose* pose; //EDIT: Make private
int GetNumBones() {return pose->getSkeleton()->m_bones.getSize();}
const hkQsTransform& getBoneLocalSpace(int boneidx) {return pose->getBoneLocalSpace(boneidx);}
const hkQsTransform& getBoneModelSpace(int boneidx) {return pose->getBoneModelSpace(boneidx);}
void setBoneLocalSpace(int boneidx, const hkQsTransform& transform) {pose->setBoneLocalSpace(boneidx, transform);}
void setBoneModelSpace(int boneidx, const hkQsTransform& transform, bool propagate) {pose->setBoneModelSpace(boneidx, transform, (hkaPose::PropagateOrNot)propagate);}
void GetRotation(Quaternion* qrot, int boneidx);
void SetRotation(const Quaternion* qrot, int boneidx);
void GetPosition(Vector3* vpos, int boneidx);
void SetPosition(const Vector3* vpos, int boneidx);
Pose(const hkaSkeleton* skeleton, const hkArrayBase<hkpConstraintInstance*>& constraints);
};
//-----------------------------------------------------------------------------
// Name: Animation
// Desc: A collection of poses with time reference and annotations
//-----------------------------------------------------------------------------
class Animation : public IAnimation
{
private:
RagdollEntity* parent;
hkaInterleavedUncompressedAnimation* ani; //EDIT: Make private
hkaAnimationBinding* anibinding;
hkaDefaultAnimationControl* anictrl;
bool enabled;
public:
Animation(RagdollEntity* parent, int numtracks, float duration);
bool GetEnabled() {return enabled;}
bool SetEnabled(bool val);
float GetTime() {return anictrl->getLocalTime();}
float SetTime(float val) {anictrl->setLocalTime(val); return val;}
UINT GetLoops() {return anictrl->getOverflowCount();}
UINT SetLoops(UINT val) {anictrl->setOverflowCount(val); return val;}
float GetDuration() {return ani->m_duration;}
float SetDuration(float val) {return ani->m_duration = val;}
float GetWeight() {return anictrl->getMasterWeight();}
float SetWeight(float val) {val = hkMath::clamp(val, 0.0f, 1.0f); anictrl->setMasterWeight(val); return val;}
void AddFrame(IPose* frame);
Result Serialize(const FilePath& filename);
std::shared_ptr<void> GetPyPtr();
};
//-----------------------------------------------------------------------------
// Name: PlayerEntity
// Desc: An object in collision detection context with player characteristics
//-----------------------------------------------------------------------------
class MyCharacterListener;
class PlayerEntity : public IPlayerEntity
{
private:
Havok* parent;
hkpCharacterContext* m_characterContext;
hkpCharacterProxy* m_characterProxy;
Vector3* vpos;
Quaternion* qrot;
public:
PlayerEntity(Havok* parent) : parent(parent), vpos(NULL), qrot(NULL) {m_characterContext = NULL; m_characterProxy = NULL;}
Result Create(const HvkShapeDesc* shapedesc, Vector3* vpos, Quaternion* qrot);
void Update(float dx, float dy, float rot, bool jump);
void Release();
};
//-----------------------------------------------------------------------------
// Name: PlayerRBEntity
// Desc: PlayerEntity, utilizing a rigid body, instead of a shape phantom
//-----------------------------------------------------------------------------
class MyCharacterListener;
class PlayerRBEntity : public IPlayerEntity
{
private:
Havok* parent;
Vector3* vpos;
Quaternion* qrot;
hkpCharacterRigidBody* characterrigidbody;
hkpCharacterContext* characterctx;
public:
PlayerRBEntity(Havok* parent) : parent(parent), vpos(NULL), qrot(NULL) {}
Result Create(const HvkShapeDesc* shapedesc, Vector3* vpos, Quaternion* qrot);
void Update(float dx, float dy, float rot, bool jump);
void Release();
};
//-----------------------------------------------------------------------------
// Name: RegularEntity
// Desc: An object in collision detection context
//-----------------------------------------------------------------------------
class RegularEntity : public IRegularEntity, public Entity
{
private:
Havok* parent;
Vector3* vpos;
Quaternion* qrot;
public:
hkpRigidBody* rigidbody;
RegularEntity(Havok* parent) : parent(parent), vpos(NULL), qrot(NULL) {}
Result Create(const HvkShapeDesc* shapedesc, IHavok::Layer layer, Vector3* vpos, Quaternion* qrot);
void Update();
void applyForce(const Vector3* force);
void applyAngularImpulse(const Vector3* impulse);
void applyLinearImpulse(const Vector3* impulse);
void applyPointImpulse(const Vector3* impulse, const Vector3* pos);
void setMotionType(MotionType mtype);
void Release();
};
//-----------------------------------------------------------------------------
// Name: LevelEntity
// Desc: A collection of static shapes
//-----------------------------------------------------------------------------
class LevelEntity : public ILevelEntity, public Entity
{
private:
Havok* parent;
hkpStaticCompoundShape* compoundshape;
public:
hkpRigidBody* rigidbody;
LevelEntity(Havok* parent) : parent(parent) {}
Result Create(const HvkStaticCompoundShapeDesc* shapedesc, const Vector3& vpos, const Quaternion& qrot);
void EnableAll();
void DisableAll();
void EnableShape(UINT32 shapekey);
void DisableShape(UINT32 shapekey);
void Release();
};
//-----------------------------------------------------------------------------
// Name: BoxedLevelEntity
// Desc: An entity implementing a custom boxed-level-shape
//-----------------------------------------------------------------------------
class BoxedLevelShape;
class hkpContactMgr;
class BoxedLevelEntity : public IBoxedLevelEntity, public Entity
{
private:
Havok* parent;
BoxedLevelShape* shape;
public:
hkpRigidBody* rigidbody;
static struct CollisionAgentFunctions
{
static hkpCollisionAgent* HK_CALL CreateFunc(const hkpCdBody& collA, const hkpCdBody& collB, const hkpCollisionInput& env, hkpContactMgr* mgr);
static void HK_CALL GetPenetrationsFunc(const hkpCdBody& bodyA, const hkpCdBody& bodyB, const hkpCollisionInput& input, hkpCdBodyPairCollector& collector);
static void HK_CALL GetClosestPointsFunc(const hkpCdBody& bodyA, const hkpCdBody& bodyB, const hkpCollisionInput& input, hkpCdPointCollector& output);
static void HK_CALL LinearCastFunc(const hkpCdBody& bodyA, const hkpCdBody& bodyB, const hkpLinearCastCollisionInput& input, hkpCdPointCollector& castCollector, hkpCdPointCollector* startCollector);
};
BoxedLevelEntity(Havok* parent) : parent(parent) {}
Result Create(const UINT (&chunksize)[3]);
void SetBoxTypes(BoxedLevelBoxType* boxtypes, UINT32 numtypes);
void SetBoxTypesWrapper(std::vector<BoxedLevelBoxType>& list)
{
if(list.size())
SetBoxTypes(&list[0], list.size());
}
Result CreateBoxShapes(HvkShapeDesc** boxshapes, UINT32 numboxshapes);
void CreateBoxShapesWrapper(std::vector<HvkShapeDesc*>& list)
{
if(list.size())
CreateBoxShapes(&list[0], list.size());
}
void AssignChunk(BoxedLevelChunk* chunk);
void UnassignChunk(BoxedLevelChunk* chunk);
BoxedLevelChunk* ChunkFromShapeKey(UINT32 chunkshapekey);
void BoxPosFromShapeKey(UINT32 boxshapekey, UINT32 (*boxpos)[3]);
void Release();
};
//-----------------------------------------------------------------------------
// Name: RagdollEntity
// Desc: An animatable ragdoll object, composed of multiple connected shapes
//-----------------------------------------------------------------------------
class MyCharacterListener2;
class RagdollEntity : public IRagdollEntity, public Entity
{
private:
// Global
// hkQsTransform* transform;
// Character controller
hkpCharacterContext* m_characterContext;
hkpCharacterProxy* m_characterProxy;
MyCharacterListener2* m_listener;
// Animation
hkpPhysicsSystem* ragdoll;
int collisiongroup;
hkaSkeleton* ragdollskeleton;
public:
hkaAnimatedSkeleton* animatedskeleton;
private:
hkaRagdollInstance* ragdollinstance;
hkaRagdollRigidBodyController* controller;
std::list<Animation*> animations;
// Attachments
hkArray<hkRefPtr<hkaBoneAttachment>> attachments;
hkaPose* currentpose;
// Look at IK solver
struct LookAtDesc
{
hkVector4 targetpos;
hkReal gain;
int neckboneidx, headboneidx;
}* lookatdesc;
// Foot IK solver
struct FootIkDesc
{
hkaFootPlacementIkSolver *leftlegsolver, *rightlegsolver;
FootIkDesc() : leftlegsolver(NULL), rightlegsolver(NULL) {}
~FootIkDesc()
{
if(leftlegsolver)
delete leftlegsolver;
if(rightlegsolver)
delete rightlegsolver;
}
}* footikdesc;
struct Part
{
hkpRigidBody* rigidbody;
const Matrix* vtransform;
hkInt16 index;
Part(hkpRigidBody* rigidbody, const Matrix* vtransform, hkInt16 index) : rigidbody(rigidbody), vtransform(vtransform), index(index) {}
};
std::map<String, Part*, StringComparator> parts;
Havok* parent;
Vector3* vpos;
Quaternion* qrot;
hkQsTransform* transform;
public:
RagdollEntity(Havok* parent) : parent(parent), vpos(NULL), qrot(NULL), lookatdesc(NULL), footikdesc(NULL)//, transform(hkQsTransform::IDENTITY)
{
this->transform = new hkQsTransform(hkQsTransform::IDENTITY);
dx = dz = rot = 0.0f;
jump = onladder = false;
}
Result Create(const HvkShapeDesc* shapedesc, Vector3* vpos, Quaternion* qrot);
Result SetRootBone(const HvkShapeDesc* shapedesc, const String& shapekey, const Matrix* worldmatrix);
Result AttachShape(const HvkShapeDesc* shapedesc, const ConstraintDesc* constraintdesc, const String& newshapekey, const String& anchorshapekey, const Matrix* worldmatrix);
void AttachEntity(IRegularEntity* entity, const String& targetshapekey, const float* localtransform);
void DetachEntity(const IRegularEntity* entity);
Result AssembleRagdoll();
Result CreatePose(IPose** pose);
Pose* CreatePoseWrapper()
{
Pose* pose;
CreatePose((LPPOSE*)&pose);
return pose;
}
Result CreateAnimation(float duration, IAnimation** ani);
Animation* CreateAnimationWrapper(float duration)
{
Animation* ani;
CreateAnimation(duration, (LPANIMATION*)&ani);
return ani;
}
float* GetPivot(const String& shapekey);
float* GetPivot(int boneidx);
void LookAt(const float* vtargetpos, float gain);
void EnableFootIk();
void PreUpdate();
void Update();
void Release();
std::shared_ptr<void> GetPyPtr();
};
//-----------------------------------------------------------------------------
// Name: LocalVisualizer
// Desc: Proxy class for forwarding debug draw calls to Direct 3D
//-----------------------------------------------------------------------------
class LocalVisualizer : public hkDebugDisplayHandler
{
private:
LPOUTPUTWINDOW d3dwnd;
LPRENDERSHADER shader;
std::map<hkUlong, LPVOID> objids;
hkResult addGeometry(const hkArrayBase<hkDisplayGeometry*>& geometries, const hkTransform& transform, hkUlong id, int tag, hkUlong shapeIdHint);
//hkResult addGeometry(hkDisplayGeometry* geometry, hkUlong id, int tag, hkUlong shapeIdHint);
hkResult addGeometryInstance(hkUlong origianalGeomId, const hkTransform& transform, hkUlong id, int tag, hkUlong shapeIdHint);
hkResult setGeometryColor(int color, hkUlong id, int tag);
hkResult setGeometryTransparency(float alpha, hkUlong id, int tag);
hkResult updateGeometry(const hkTransform& transform, hkUlong id, int tag);
hkResult updateGeometry( const hkMatrix4& transform, hkUlong id, int tag );
hkResult skinGeometry(hkUlong* ids, int numIds, const hkMatrix4* poseModel, int numPoseModel, const hkMatrix4& worldFromModel, int tag );
hkResult removeGeometry(hkUlong id, int tag, hkUlong shapeIdHint);
hkResult updateCamera(const hkVector4& from, const hkVector4& to, const hkVector4& up, hkReal nearPlane, hkReal farPlane, hkReal fov, const char* name);
hkResult displayPoint(const hkVector4& position, int colour, int id, int tag);
hkResult displayLine(const hkVector4& start, const hkVector4& end, int color, int id, int tag);
hkResult displayTriangle(const hkVector4& a, const hkVector4& b, const hkVector4& c, int colour, int id, int tag);
hkResult displayText(const char* text, int color, int id, int tag);
hkResult display3dText(const char* text, const hkVector4& pos, int color, int id, int tag);
hkResult displayBone(const hkVector4& a, const hkVector4& b, const hkQuaternion& orientation, int color, int tag);
hkResult displayGeometry(const hkArrayBase<hkDisplayGeometry*>& geometries, const hkTransform& transform, int color, int id, int tag);
hkResult displayGeometry(const hkArrayBase<hkDisplayGeometry*>& geometries, int color, int id, int tag);
hkResult sendMemStatsDump(const char* data, int length);
hkResult holdImmediate();
public:
LocalVisualizer(LPOUTPUTWINDOW d3dwnd, LPRENDERSHADER shader) : d3dwnd(d3dwnd), shader(shader) {}
};
//-----------------------------------------------------------------------------
// Name: Havok
// Desc: API to the midi functionality of windows multimedia library. Mainly used to open devices.
//-----------------------------------------------------------------------------
class Havok : public IHavok
{
private:
bool memutilinitialized;
hkArray<hkProcessContext*> contexts;
hkVisualDebugger* visualdebugger;
// hkDebugDisplayHandler* localvisualizer;
std::map<HvkViewer, hkProcess*> viewerprocesses;
hkpMouseSpringAction* mousespring;
hkReal mousepickdist;
void _Update();
float CastRay(hkVector4& src, hkVector4& dest, LPENTITY* hitentity, UINT32 (*shapekeys)[8], Vector3* hitnml);
public:
hkDebugDisplayHandler* localvisualizer;
hkpWorld* world;
hkpGroupFilter* groupfilter;
std::list<Entity*> entities;
std::list<Weapon*> weapons;
std::list<Vehicle*> vehicles;
float t, dt;
Havok();
void Sync(GLOBALVARDEF_LIST);
Result Init(const Vector3& worldsize_min, const Vector3& worldsize_max, VisualizationType vtype, LPOUTPUTWINDOW localvizwnd, LPRENDERSHADER localvizshader);
void InitDone();
Result CreateRegularEntity(const HvkShapeDesc* shapedesc, Layer layer, Vector3* vpos, Quaternion* qrot, IRegularEntity** entity);
RegularEntity* CreateRegularEntityWrapper(const HvkShapeDesc* shapedesc, Layer layer, Vector3* vpos, Quaternion* qrot)
{
Result rlt;
RegularEntity* entity;
IFFAILED(CreateRegularEntity(shapedesc, layer, vpos, qrot, (LPREGULARENTITY*)&entity))
throw rlt.GetLastResult();
return entity;
}
Result CreateLevelEntity(const HvkStaticCompoundShapeDesc* shapedesc, const Vector3& vpos, const Quaternion& qrot, ILevelEntity** entity);
Result CreateBoxedLevelEntity(const UINT (&chunksize)[3], IBoxedLevelEntity** entity);
Result CreateRagdollEntity(const HvkShapeDesc* shapedesc, Vector3* vpos, Quaternion* qrot, IRagdollEntity** entity);
RagdollEntity* CreateRagdollEntityWrapper(const HvkShapeDesc* shapedesc, Vector3* vpos, Quaternion* qrot)
{
Result rlt;
RagdollEntity* entity;
IFFAILED(CreateRagdollEntity(shapedesc, vpos, qrot, (IRagdollEntity**)&entity))
throw rlt.GetLastResult();
return entity;
}
Result CreatePlayerEntity(const HvkShapeDesc* shapedesc, Vector3* vpos, Quaternion* qrot, bool isrigidbody, IPlayerEntity** entity);
Result CreateWeapon(IWeapon** weapon);
Result CreateVehicle(const VehicleDesc* vehicledesc, Vector3* vpos, Quaternion* qrot, IVehicle** vehicle);
Result CreateCollisionMesh(LPOBJECT obj, IRegularEntity** entity);
Result CreateConvexCollisionHull(const HvkGeneralShapeDesc* shapedesc, LPOBJECT obj, IRegularEntity** entity);
RegularEntity* CreateConvexCollisionHullWrapper(const HvkGeneralShapeDesc* shapedesc, LPOBJECT obj)
{
Result rlt;
RegularEntity* entity;
IFFAILED(CreateConvexCollisionHull(shapedesc, obj, (LPREGULARENTITY*)&entity))
throw rlt.GetLastResult();
return entity;
}
Result CreateCollisionCapsule(LPOBJECT obj, float radius, IRegularEntity** entity);
Result CreateCollisionRagdoll(LPOBJECT obj, float radius, IRagdollEntity** entity);
RagdollEntity* CreateCollisionRagdollWrapper(LPOBJECT obj, float radius)
{
Result rlt;
RagdollEntity* entity;
IFFAILED(CreateCollisionRagdoll(obj, radius, (IRagdollEntity**)&entity))
throw rlt.GetLastResult();
return entity;
}
float CastRayTo(const Vector3& src, const Vector3& dest, LPENTITY* hitentity, UINT32 (*shapekeys)[8], Vector3* hitnml);
float CastRayDir(const Vector3& src, const Vector3& dir, LPENTITY* hitentity, UINT32 (*shapekeys)[8], Vector3* hitnml);
void EnableViewer(HvkViewer viewer);
void DisableViewer(HvkViewer viewer);
String GetViewerName(HvkViewer viewer);
void MousePickGrab(float* campos, float* camdir);
void MousePickDrag(float* campos, float* camdir);
void MousePickRelease();
void Update();
static Result CreateShape(const HvkShapeDesc* shapedesc, hkpShape** shape);
static Result CreateConstraint(const ConstraintDesc* constraintdesc, hkpRigidBody* anchorbody, hkpRigidBody* connectedbody, hkpConstraintInstance** constraint);
void Release();
};
void SyncWithPython();
#endif |
359eefeba22a3fc8d558db0faeeff542f2c7c99d | 2e11e3d44990a743d4e07f8e9bc94182e67ed861 | /problems/1091. Shortest Path in Binary Matrix.cc | 995177c76be724009e5ab6ed6c81f8f90aabfca6 | [] | no_license | pokaa3a/leetcoding | 8c7c4f20f4a424adeaf43173f33ef01780016dc5 | 7a995cee0eb621df2df5611d1c0a8c5d1a11dca1 | refs/heads/master | 2022-07-22T12:00:38.938350 | 2022-06-17T04:55:42 | 2022-06-17T04:55:42 | 247,426,082 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,525 | cc | 1091. Shortest Path in Binary Matrix.cc | #include <iostream>
#include <vector>
#include <queue>
#include <set>
using namespace std;
// class Solution {
// public:
// int shortestPathBinaryMatrix(vector<vector<int> >& grid) {
// if (grid[0][0] == 1) return -1;
// int n = grid.size();
// if (n == 1) return 1;
// queue<pair<int, int> > q;
// q.push(make_pair(0, 0));
// grid[0][0] = 1;
// int shortest = 1;
// while (!q.empty()) {
// int q_size = q.size();
// shortest++;
// for (int k = 0; k < q_size; ++k) {
// pair<int, int> cur = q.front();
// q.pop();
// int r = cur.first, c = cur.second;
// for (int i = -1; i <= 1; ++i) {
// for (int j = -1; j <= 1; ++j) {
// if (r + i < 0 || r + i >= n || c + j < 0 || c + j >= n ) continue;
// if (grid[r + i][c + j] == 1) continue;
// if (r + i == n - 1 && c + j == n - 1) return shortest;
// q.push(make_pair(r + i, c + j));
// grid[r + i][c + j] = 1;
// }
// }
// }
// }
// return -1;
// }
// };
class Solution {
public:
int shortestPathBinaryMatrix(vector<vector<int> >& grid) {
int rows = grid.size(), cols = grid[0].size();
queue<pair<int, int> > q;
int ans = 0;
if (grid[0][0] == 0){
q.push(make_pair(0, 0));
grid[0][0] = 1;
}
while (!q.empty()) {
int q_size = q.size();
ans++;
for (int i = 0; i < q_size; ++i) {
pair<int, int> cur = q.front(); q.pop();
int x = cur.first, y = cur.second;
if (x == rows - 1 && y == cols - 1) return ans;
for (int r = -1; r <= 1; ++r) {
for (int c = -1; c <= 1; ++c) {
if (x + r >= 0 && x + r < rows &&
y + c >= 0 && y + c < cols &&
grid[x + r][x + c] == 0) {
q.push(make_pair(x + r, y + c));
grid[cur.first][cur.second] = 1;
}
}
}
}
}
return -1;
}
};
int main() {
int row1[] = {0, 1, 0, 1};
int row2[] = {0, 1, 0, 1};
int row3[] = {0, 0, 0, 1};
int row4[] = {1, 0, 1, 0};
vector<vector<int> > grid;
grid.push_back(vector<int>(row1, row1 + 4));
grid.push_back(vector<int>(row2, row2 + 4));
grid.push_back(vector<int>(row3, row3 + 4));
grid.push_back(vector<int>(row4, row4 + 4));
Solution *sol = new Solution();
cout << sol->shortestPathBinaryMatrix(grid) << endl;
} |
a2e4e8bb9a6093f3e599807af4ba57cad91e555a | 297b4c9ff85b4f3f9713d2dab63fff0dd92a55ce | /Ant.hpp | 1df99192d7c1bd0e34eba8cab5b7da49782e4c58 | [] | no_license | janwawruszczak1998/TSP-Algorithms | cba8e36f13dcfe6e98e78e4dfc79a5d6fc57a6a2 | d6d429a81fdb11e1da306d9e881ef6ed240f5778 | refs/heads/master | 2022-12-20T17:23:45.572628 | 2020-09-29T12:18:52 | 2020-09-29T12:18:52 | 214,018,697 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 293 | hpp | Ant.hpp | //
// Created by Jan on 2020-01-06.
//
#ifndef PEA_ANT_H
#define PEA_ANT_H
#include <vector>
class Ant {
public:
Ant(unsigned, unsigned);
unsigned get_number();
std::vector<bool> &get_tabu();
private:
unsigned number;
std::vector<bool> tabu;
};
#endif //PEA_ANT_H
|
f8669ba6c0203ec9693a635b1ec9268d50a8f69a | d489311b0ef11b6431e0cf2876bee6fb5bc95f40 | /evalcom2/AddInComCore.h | b5281a6f090c188d2e2d2c188c61edd5e9c7bb8e | [] | no_license | SergeyXa/erpmebel.ru.evalcom2.addin | 2349e476086e7e091667cc9f8acf14fe79057a46 | 0bfd821f88f6464d8cc7b7594ff2d466d234c997 | refs/heads/master | 2020-03-30T20:30:54.109005 | 2018-10-04T14:59:29 | 2018-10-04T14:59:29 | 151,591,241 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 454 | h | AddInComCore.h | #pragma once
#include <atlbase.h>
#include "Compiler.h"
#include "Interpreter.h"
class CAddInComCore :
private CCompiler,
private CInterpreter
{
public:
HRESULT Compile(SAFEARRAY** paParams);
HRESULT Load(VARIANT * pvarRetValue, SAFEARRAY** paParams);
HRESULT SetValue(VARIANT * pvarRetValue, SAFEARRAY** paParams);
HRESULT Execute(VARIANT * pvarRetValue, SAFEARRAY** paParams);
HRESULT Version(VARIANT * pvarRetValue, SAFEARRAY** paParams);
}; |
9a39774b74ef4810458d2c863b482a6b6f0b64c2 | c7532c99dfe6fd27c6a12fdc9a98ce1fe67bc93d | /Engine/Source/Editor/Gizmo.h | d848db5004839e8bb0dfb860d59a7495879419b0 | [
"MIT"
] | permissive | lqq1985/OpenGL4.5-GameEngine | a7d3dcf408b06b59f5838290ad3a72ec51bfda1d | 79468b7807677372bbc0450ea49b48ad66bbbd41 | refs/heads/master | 2020-08-17T22:57:34.064047 | 2019-03-05T20:36:50 | 2019-03-05T20:36:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 312 | h | Gizmo.h | #pragma once
#include <include/dll_export.h>
#include <include/glm.h>
#include <Core/GameObject.h>
enum class GIZMO_MODE {
TRANSLATE,
Rotate,
Scale
};
class DLLExport Gizmo : virtual public GameObject
{
public:
Gizmo();
~Gizmo();
void SetScale(glm::vec3 scale);
void SetMode(GIZMO_MODE mode);
}; |
b64b59792dbbc5f5ca9c9b73c4564ff5b428f222 | 73b329e4becd3045989e17fbc0c6aed3d46b5854 | /Fitting/11742_HybridFitting/Meow.cpp | 09d57815cfbc7d9e0a86f4a94a5bad9a3d2d3cbc | [] | no_license | FHead/PhysicsHiggsProperties | 36ee6edd9b4a744c41ae8eda58d3b0979e02868d | 25e2cf36b633403a7661488167279a917b76882c | refs/heads/master | 2023-06-01T12:58:09.411729 | 2020-05-05T20:47:51 | 2020-05-05T20:47:51 | 377,256,404 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,686 | cpp | Meow.cpp | #include <iostream>
using namespace std;
#include "DataHelper.h"
int main()
{
DataHelper DHFile("Normalization.dh");
cout << DHFile["ee"]["T1A"].GetDouble() / DHFile["em"]["T1A"].GetDouble() << endl;
cout << DHFile["ee"]["T1B"].GetDouble() / DHFile["em"]["T1B"].GetDouble() << endl;
cout << DHFile["ee"]["T1C"].GetDouble() / DHFile["em"]["T1C"].GetDouble() << endl;
cout << DHFile["ee"]["T1D"].GetDouble() / DHFile["em"]["T1D"].GetDouble() << endl;
cout << DHFile["ee"]["T1E"].GetDouble() / DHFile["em"]["T1E"].GetDouble() << endl;
cout << DHFile["ee"]["T1F"].GetDouble() / DHFile["em"]["T1F"].GetDouble() << endl;
cout << DHFile["ee"]["T1A"].GetDouble() / DHFile["me"]["T1A"].GetDouble() << endl;
cout << DHFile["ee"]["T1B"].GetDouble() / DHFile["me"]["T1B"].GetDouble() << endl;
cout << DHFile["ee"]["T1C"].GetDouble() / DHFile["me"]["T1C"].GetDouble() << endl;
cout << DHFile["ee"]["T1D"].GetDouble() / DHFile["me"]["T1D"].GetDouble() << endl;
cout << DHFile["ee"]["T1E"].GetDouble() / DHFile["me"]["T1E"].GetDouble() << endl;
cout << DHFile["ee"]["T1F"].GetDouble() / DHFile["me"]["T1F"].GetDouble() << endl;
cout << DHFile["ee"]["T1A"].GetDouble() / DHFile["mm"]["T1A"].GetDouble() << endl;
cout << DHFile["ee"]["T1B"].GetDouble() / DHFile["mm"]["T1B"].GetDouble() << endl;
cout << DHFile["ee"]["T1C"].GetDouble() / DHFile["mm"]["T1C"].GetDouble() << endl;
cout << DHFile["ee"]["T1D"].GetDouble() / DHFile["mm"]["T1D"].GetDouble() << endl;
cout << DHFile["ee"]["T1E"].GetDouble() / DHFile["mm"]["T1E"].GetDouble() << endl;
cout << DHFile["ee"]["T1F"].GetDouble() / DHFile["mm"]["T1F"].GetDouble() << endl;
}
|
378160dc81cbab77f1f05984a7db13b055a85e58 | 801f7ed77fb05b1a19df738ad7903c3e3b302692 | /refactoringOptimisation/differentiatedCAD/occt-min-topo-src/src/TDataXtd/TDataXtd_Axis.cxx | de312c2546d79adb3215a785e5f44be559f914ed | [] | no_license | salvAuri/optimisationRefactoring | 9507bdb837cabe10099d9481bb10a7e65331aa9d | e39e19da548cb5b9c0885753fe2e3a306632d2ba | refs/heads/master | 2021-01-20T03:47:54.825311 | 2017-04-27T11:31:24 | 2017-04-27T11:31:24 | 89,588,404 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,775 | cxx | TDataXtd_Axis.cxx | // Created on: 2009-04-06
// Copyright (c) 2009-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#include <BRep_Tool.hxx>
#include <BRepAdaptor_Curve.hxx>
#include <BRepBuilderAPI_MakeEdge.hxx>
#include <Geom_Curve.hxx>
#include <Geom_Line.hxx>
#include <Geom_TrimmedCurve.hxx>
#include <GeomAbs_CurveType.hxx>
#include <gp_Lin.hxx>
#include <Standard_GUID.hxx>
#include <Standard_Type.hxx>
#include <TDataStd.hxx>
#include <TDataXtd.hxx>
#include <TDataXtd_Axis.hxx>
#include <TDF_Attribute.hxx>
#include <TDF_Label.hxx>
#include <TDF_RelocationTable.hxx>
#include <TNaming_Builder.hxx>
#include <TNaming_NamedShape.hxx>
#include <TNaming_Tool.hxx>
#include <TopAbs.hxx>
#include <TopLoc_Location.hxx>
#include <TopoDS.hxx>
#include <TopoDS_Edge.hxx>
//=======================================================================
//function : GetID
//purpose :
//=======================================================================
const Standard_GUID& TDataXtd_Axis::GetID ()
{
static Standard_GUID TDataXtd_AxisID("2a96b601-ec8b-11d0-bee7-080009dc3333");
return TDataXtd_AxisID;
}
//=======================================================================
//function : Set
//purpose :
//=======================================================================
Handle(TDataXtd_Axis) TDataXtd_Axis::Set (const TDF_Label& L)
{
Handle(TDataXtd_Axis) A;
if (!L.FindAttribute(TDataXtd_Axis::GetID(),A)) {
A = new TDataXtd_Axis ();
L.AddAttribute(A);
}
return A;
}
//=======================================================================
//function : Set
//purpose :
//=======================================================================
Handle(TDataXtd_Axis) TDataXtd_Axis::Set (const TDF_Label& L, const gp_Lin& line)
{
Handle(TDataXtd_Axis) A = Set (L);
Handle(TNaming_NamedShape) aNS;
if(L.FindAttribute(TNaming_NamedShape::GetID(), aNS)) {
if(!aNS->Get().IsNull())
if(aNS->Get().ShapeType() == TopAbs_EDGE) {
TopoDS_Edge anEdge = TopoDS::Edge(aNS->Get());
BRepAdaptor_Curve anAdaptor(anEdge);
if(anAdaptor.GetType() == GeomAbs_Line) {
gp_Lin anOldLine = anAdaptor.Line();
if(anOldLine.Direction().X() == line.Direction().X() &&
anOldLine.Direction().Y() == line.Direction().Y() &&
anOldLine.Direction().Z() == line.Direction().Z() &&
anOldLine.Location().X() == line.Location().X() &&
anOldLine.Location().Y() == line.Location().Y() &&
anOldLine.Location().Z() == line.Location().Z()
)
return A;
}
}
}
TNaming_Builder B (L);
B.Generated (BRepBuilderAPI_MakeEdge(line));
return A;
}
//=======================================================================
//function : TDataXtd_Axis
//purpose :
//=======================================================================
TDataXtd_Axis::TDataXtd_Axis () { }
//=======================================================================
//function : ID
//purpose :
//=======================================================================
const Standard_GUID& TDataXtd_Axis::ID() const { return GetID(); }
//=======================================================================
//function : NewEmpty
//purpose :
//=======================================================================
Handle(TDF_Attribute) TDataXtd_Axis::NewEmpty () const
{
return new TDataXtd_Axis();
}
//=======================================================================
//function : Restore
//purpose :
//=======================================================================
void TDataXtd_Axis::Restore (const Handle(TDF_Attribute)&) { }
//=======================================================================
//function : Paste
//purpose :
//=======================================================================
void TDataXtd_Axis::Paste (const Handle(TDF_Attribute)&, const Handle(TDF_RelocationTable)&) const { }
//=======================================================================
//function : Dump
//purpose :
//=======================================================================
Standard_OStream& TDataXtd_Axis::Dump (Standard_OStream& anOS) const
{
anOS << "Axis";
return anOS;
}
|
2a73584b6d7a65577fef48f201d1240f932f5858 | 01fcee587136d5182b2d4ec8c195be350b547555 | /codeeditor.h | bd43e63313922e87db3e951ba54d9ffff76acb6d | [] | no_license | FUMRobotics/FUMDelta | 49600c416f9cd4ffd8d3a4c9b68f434a6858943c | b41f18ce82592aa637a77afc2a57e9b297c16aad | refs/heads/master | 2021-11-21T03:56:36.844534 | 2021-11-16T18:15:18 | 2021-11-16T18:15:18 | 199,139,925 | 2 | 1 | null | 2021-08-23T11:38:47 | 2019-07-27T08:46:20 | C++ | UTF-8 | C++ | false | false | 4,181 | h | codeeditor.h | #ifndef CODEEDITOR_H
#define CODEEDITOR_H
#include <QMainWindow>
#include <highlighter.h>
#include <QShortcut>
#include "QSettings"
#include <QPlainTextEdit>
#include <QCompleter>
#include <QStringListModel>
#include "files.h"
#include "search.h"
#include "utils/conversion.h"
#include "utils/templates.h"
namespace Ui {
class CodeEditor;
}
class CodeEditor : public QMainWindow
{
Q_OBJECT
public:
explicit CodeEditor(QWidget *parent = 0);
~CodeEditor();
void openWith(QString);
private:
QAbstractItemModel *modelFromFile(const QString& fileName);
private slots:
void save();
void open(QString file);
void newTab();
void selectText(int pos,int len);
void highlightCurrentLine();
void highlightRunningLine(QColor highlight_color);
void updateHighlighterTheme();
void setTabWidth(int width);
void updateLineNums(int newBlockCount);
void scrollOverview(int scrollValue);
void setCodeEditorStyle(QString backgroundColor, QString lineColor);
void setTabWidgetStyle(QString foregroundColor, QString backgroundColor);
void setLineNumStyle(QString lineColor, QString foregroundColor);
void setOverViewStyle(QString lineColor, QString foregroundColor);
QString getFileType(QString file);
void on_actionOpen_triggered();
void on_actionNew_triggered();
void on_actionSave_triggered();
void on_actionUndo_triggered();
void on_actionRedo_triggered();
void on_actionExit_triggered();
void on_actionSave_as_triggered();
void on_actionFind_triggered();
void on_actionHex_triggered();
void on_actionAscii_triggered();
void on_actionStrings_triggered();
void on_findLineEdit_returnPressed();
void on_actionAbout_triggered();
void on_tabWidget_tabCloseRequested(int index);
void on_tabWidget_currentChanged(int index);
void onBlockCountChanged(int newBlockCount);
void onTextChanged();
void on_actionFullScreen_triggered();
void on_actionGoTo_triggered();
void on_actionAsm_triggered();
void on_actionC_triggered();
void on_actionCpluspluss_triggered();
void on_actionHtml_triggered();
void on_actionRl_triggered();
void on_actionJava_triggered();
bool confirmApplyTemplate();
void on_actionCss_triggered();
void on_findButton_clicked();
void on_findPrevButton_clicked();
void on_actionFind_Next_triggered();
void findNext();
void findPrev();
void on_actionFind_Previous_triggered();
void on_actionReplace_triggered();
void on_replaceButton_clicked();
void on_actionDelete_line_triggered();
void on_actionRemove_word_triggered();
void on_replaceAllButton_clicked();
void on_replaceLineEdit_returnPressed();
void on_findLineEdit_textChanged(const QString &arg1);
void on_actionToggle_comment_triggered();
void on_actionOverview_triggered();
void on_actionDark_triggered();
void on_actionSolarized_Dark_triggered();
void on_actionJoin_Lines_triggered();
void on_actionMove_Line_Up_triggered();
void on_actionSwap_line_down_triggered();
void on_actionMenubar_triggered();
void on_actionSolarized_triggered();
void on_action8_triggered();
void on_action4_triggered();
void on_action2_triggered();
void on_actionClose_All_triggered();
void on_actionTommorrow_triggered();
void on_actionTommorrow_Night_triggered();
void on_actionRoboticLanguage_triggered();
void on_actionRun_triggered();
private:
Ui::CodeEditor *ui;
Highlighter *highlighter;
QShortcut *shortcut;
QSettings settings;
Conversion conversion;
Files files;
Search searcher;
Templates templates;
int numBlocks;
int newNumBlocks;
int outputMode;
int foundPosElement;
int searchTermLen;
int *outputModeP;
QString filename;
QString theme;
QString currentDirectory;
QString currentSearchTerm; // Current Value Of Search Term
QStringList foundPositions; // Positions Of Substrings Matching Search Term
QColor lineColor;
QCompleter* completer;
};
#endif // CODEEDITOR_H
|
7b5087793d09f72c9d882eb6166d8103a52c0030 | f0073a9b434a9f9d787546f839d521be9dc621d7 | /Classes/CStoryScene.cpp | 8216990a0e6c7e5455f1511b32265431de8f2a71 | [] | no_license | pluto27351/Fraction | 0ad247c6e3ecd2c54587dca213a4f4aa3fcc0558 | 3a7aa17e77c9f925d1831a10e9ad8949cda4578d | refs/heads/master | 2020-04-07T02:07:12.100309 | 2019-10-08T12:27:19 | 2019-10-08T12:27:19 | 157,964,552 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,461 | cpp | CStoryScene.cpp | #define SCREEN_POS Vec2(1365.5,768)
#include "CStoryScene.h"
#include "CTeachScene.h"
#include "CMenuScene.h"
USING_NS_CC;
using namespace cocostudio::timeline;
Scene* CStoryScene::createScene()
{
auto scene = Scene::create();
auto layer = CStoryScene::create();
scene->addChild(layer);
return scene;
}
bool CStoryScene::init()
{
if (!Layer::init())
{
return false;
}
Size visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
Size size;
SpriteFrameCache::getInstance()->addSpriteFramesWithFile("img/teach_scene.plist");
auto rootNode = CSLoader::createNode("storyscene.csb");
addChild(rootNode);
Point pt;
float scale;
// 設定按鈕
char spriteName[20],normalName[20],enableName[20];
for (int i = 0; i < MAX_UNITS; i++)
{
sprintf(spriteName, "story_%d", i + 1);
sprintf(normalName, "story_%d.png", i + 1);
sprintf(enableName, "story_n%d.png", i + 1);
auto spt = (Sprite*)rootNode->getChildByName(spriteName);
pt = spt->getPosition();
scale = spt->getScale();
_unitBtn[i] = new CButton();
_unitBtn[i]->setButtonInfo(normalName,normalName, enableName, *this, pt, 1);
_unitBtn[i]->setScale(scale);
rootNode->removeChildByName(spriteName);
sprintf(spriteName, "STORY_%d", i + 1);
if(CCUserDefault::sharedUserDefault()->getBoolForKey(spriteName)){
_unitBtn[i]->setEnabled(true);
}else {
_unitBtn[i]->setEnabled(false);
}
}
_unitIdx = 0;
for(int i=0;i<4;i++){
sprintf(spriteName, "char_%d", i + 1);
_char[i] = (Sprite*)rootNode->getChildByName(spriteName);
this->addChild(_char[i], 5-i);
sprintf(spriteName, "char_b%d", i + 1);
sprintf(normalName, "tab_%d.png", i + 1);
auto btn = (Sprite*)rootNode->getChildByName(spriteName);
pt = btn->getPosition();
_charBtn[i] = new CButton();
_charBtn[i]->setButtonInfo(normalName,normalName, *this, pt, 5-i);
rootNode->removeChildByName(spriteName);
}
//menubtn
pt = rootNode->getChildByName("home")->getPosition();
scale = rootNode->getChildByName("home")->getScale();
_menuBtn.setButtonInfo("ch_home.png", "ch_home_h.png", *this, pt, 1);
_menuBtn.setScale(scale);
rootNode->removeChildByName("home");
auto top = (Sprite*)rootNode->getChildByName("char_top");
this->addChild(top, 10);
_topPic = 0;
_listener1 = EventListenerTouchOneByOne::create(); //創建一個一對一的事件聆聽器
_listener1->onTouchBegan = CC_CALLBACK_2(CStoryScene::onTouchBegan, this); //加入觸碰開始事件
_listener1->onTouchMoved = CC_CALLBACK_2(CStoryScene::onTouchMoved, this); //加入觸碰移動事件
_listener1->onTouchEnded = CC_CALLBACK_2(CStoryScene::onTouchEnded, this); //加入觸碰離開事件
this->_eventDispatcher->addEventListenerWithSceneGraphPriority(_listener1, this); //加入剛創建的事件聆聽器
this->schedule(CC_SCHEDULE_SELECTOR(CStoryScene::doStep));
return true;
}
void CStoryScene::doStep(float dt) // OnFrameMove
{
if (goBtnPressed) {
this->unscheduleAllCallbacks();
this->removeAllChildren();
SpriteFrameCache::getInstance()->removeSpriteFramesFromFile("img/teach_scene.plist");
Director::getInstance()->getTextureCache()->removeUnusedTextures();
Director::getInstance()->replaceScene(CTeachScene::createScene(_unitIdx));
}else if(menuPressed){
this->unscheduleAllCallbacks();
this->removeAllChildren();
SpriteFrameCache::getInstance()->removeSpriteFramesFromFile("img/teach_scene.plist");
Director::getInstance()->getTextureCache()->removeUnusedTextures();
Director::getInstance()->replaceScene(CMenuScene::createScene());
}
}
bool CStoryScene::onTouchBegan(cocos2d::Touch *pTouch, cocos2d::Event *pEvent)//觸碰開始事件
{
if(_bstory)return true;
Point touchLoc = pTouch->getLocation();
for (int i = 0; i < MAX_UNITS; i++)
{
_unitBtn[i]->touchesBegin(touchLoc);
}
for(int i=0;i<4;i++){
_charBtn[i]->touchesBegin(touchLoc);
}
_menuBtn.touchesBegin(touchLoc);
return true;
}
void CStoryScene::onTouchMoved(cocos2d::Touch *pTouch, cocos2d::Event *pEvent) //觸碰移動事件
{
if(_bstory)return;
Point touchLoc = pTouch->getLocation();
for (int i = 0; i < MAX_UNITS; i++)
{
_unitBtn[i]->touchesMoved(touchLoc);
}
for(int i=0;i<4;i++){
_charBtn[i]->touchesMoved(touchLoc);
}
_menuBtn.touchesMoved(touchLoc);
}
void CStoryScene::onTouchEnded(cocos2d::Touch *pTouch, cocos2d::Event *pEvent) //觸碰結束事件
{
if(_bstory){
_storyPic[_storyNum]->setVisible(false);
_storyNum+=1;
if(_storyNum == _maxstory) goBtnPressed = true;
else _storyPic[_storyNum]->setVisible(true);
return;
}
Point touchLoc = pTouch->getLocation();
if(_menuBtn.touchesEnded(touchLoc)){
menuPressed = true;
}
for (int i = 0; i < MAX_UNITS; i++)
{
if (_unitBtn[i]->touchesEnded(touchLoc)) {
_unitIdx = i + 1;
ShowUnitStory(_unitIdx);
return;
}
}
for(int i=0;i<4;i++){
if(_charBtn[i]->touchesEnded(touchLoc)){
_char[_topPic]->setZOrder(4);
_charBtn[_topPic]->setZ(4);
_topPic = i;
_char[i]->setZOrder(5);
_charBtn[i]->setZ(5);
}
}
}
void CStoryScene::ShowUnitStory(int i) {
char spriteName[30];
_maxstory = STORYDATA[i-1];
for(int k=1; k<=_maxstory; k++){
sprintf(spriteName, "img/story/story_%d_%d.png", i,k);
auto sPic = (Sprite *)Sprite::create(spriteName);
sPic->setPosition(SCREEN_POS);
sPic->setVisible(false);
this->addChild(sPic, 100);
_storyPic.push_back(sPic);
}
_storyPic[0]->setVisible(true);
_storyNum = 0;
_bstory = true;
}
CStoryScene::~CStoryScene()
{
for (int i = 0; i < MAX_UNITS; i++)delete _unitBtn[i];
for( int i=0 ; i<4 ; i++)delete _charBtn[i];
_storyPic.clear();
}
|
5a5f9c3d02a22ceb4738924e9128479b231a7629 | db465710cb4c1849ba2a961a0b51bb3541aeb5c8 | /test/TestCell.cpp | 86a62e1bbf39a71c8842b26242f5954e67788ccd | [
"MIT"
] | permissive | samsparks/climaze | cff513f09d83bcfbb0aa5b5325e6a28c742febc9 | a49dc0a926f86311212a61e837ebb46e2a387fe2 | refs/heads/master | 2021-01-22T05:33:59.906954 | 2017-03-15T20:33:34 | 2017-03-15T20:33:34 | 81,677,258 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 505 | cpp | TestCell.cpp | #include <boost/test/unit_test.hpp>
#include "Cell.hpp"
BOOST_AUTO_TEST_SUITE(TestCell)
BOOST_AUTO_TEST_CASE( Initialization )
{
Cell c;
BOOST_CHECK_EQUAL( c.Visited(), false );
BOOST_CHECK_EQUAL( c.Opened(), false );
}
BOOST_AUTO_TEST_CASE( Accessors )
{
Cell c;
BOOST_CHECK_EQUAL( c.Visited(), false );
BOOST_CHECK_EQUAL( c.Visit().Visited(), true );
BOOST_CHECK_EQUAL( c.Opened(), false );
BOOST_CHECK_EQUAL( c.Open().Opened(), true );
}
BOOST_AUTO_TEST_SUITE_END()
|
735892718c22f75c134fd35f763f498817804b70 | 5e6defa33a822f1bbc690196b6013f9695ccfacf | /pythoncompiler-read-only/.svn/pristine/73/735892718c22f75c134fd35f763f498817804b70.svn-base | 5dbd6e173537e28e0610c249071ed186f6395190 | [] | no_license | tamzinselvi/cs164-proj1 | 1936c363c87a7d999e44d6f4cc83b110957990ea | fdcc6752f72211cbadb669af511879754c6e5a78 | refs/heads/master | 2022-06-14T17:21:16.819823 | 2013-10-16T14:54:40 | 2013-10-16T14:54:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 17,516 | 735892718c22f75c134fd35f763f498817804b70.svn-base | /* -*- mode: C++; c-file-style: "stroustrup"; indent-tabs-mode: nil; -*- */
/* Definitions used internally by VM-related sources. */
#ifndef _VM_INTERNAL_H_
#define _VM_INTERNAL_H_
#include <stack>
#include <vector>
#include "vm.h"
#include "machine-dep.h"
/** Target for IL dump commands. */
extern std::FILE* ILOut;
/** A simple utility to convert STR containing octal escape sequences
* of the form \ooo into a string with the designated characters
* instead. Returns a string, but will accept either a string or
* const char* as input. */
extern std::string convertOctalEscapes (const std::string& str);
/** [Used by runtime.cc] True iff ADDR is the address of an
* instruction in VM. */
extern bool isInsnAddress (Word addr);
/** [Used by runtime.cc] Call the function at Insn FUNCPC, passing it the
* N parameters at PARAMS, and LINK as the value of the static link. Returns
* the returned value. */
extern Word callFunction (int funcPC, int n, Word* params, Word link);
/** Abstraction of a stack frame for use by the interpreter. */
class StackFrame {
public:
/** A stack frame capable of holding local data up to offset
* LARGESTOFFSET and NUMPARAMS parameters. NREGS is the number
* of nonaddressable virtual registers allocated for the
* frame. NEXT is the address of the caller's frame. ENTRYPC is
* the address of the ENTER instruction for the function using
* this stack frame. */
StackFrame (Insn* entryPoint, int numParams, long largestOffset, int nRegs,
StackFrame* next);
/** Current frame pointer as a Word. */
Word framePointer () {
return (Word)frame;
}
/** The memory addressed by frame pointer + byte displacement. */
Word* frameMemory (long disp) {
return (Word*) (frame + disp);
}
/** The address of parameter #K of this frame */
Word* parameterAddress (int k);
/** Push VAL on the parameter stack. */
void pushPendingParam (Word val);
/** Call external (non-interpreted) function F with N parameters
* taken from the parameter stack, returning the result and
* popping the parameter stack. */
Word callExternal (MachineParams::GeneralFunction f, int n);
/** A new call frame, with me as the caller, with a maximum local
* displacement of MAXOFFSET, and NREGS unaddressable virtual
* registers, giving it NUMPARAMS parameters popped from my
* parameter stack. */
StackFrame* createCalleeFrame (Insn* entryPoint, int numParams,
long maxOffset, int nregs);
StackFrame* getCallersFrame ();
/** Set getCallPC PC, which should be the location of a call. */
void setCallPC (int pc) { callPC = pc; }
/** Value saved by last setPc. */
int getCallPC () { return callPC; }
/** Contents of register #K. */
Word& registerContents (int k) {
return registers.at (k);
}
/** Pop and destroy myself, returning my caller's frame. */
StackFrame* pop ();
/** True if this frame is currently being used as the caller on
* behalf of a runtime routine executing VM::callFunction. */
bool wasCalledFromRuntime () {
return calledFromRuntime;
}
/** Set wasCalledFromRuntime () to VAL. */
void setWasCalledFromRuntime (bool val) {
calledFromRuntime = val;
}
/** Entry point of function whose frame this is. */
Insn* getEntryPoint () {
return entryPoint;
}
~StackFrame ();
private:
/** Size of data in stackData. */
size_t totalFrameSize;
/** Dynamic link, or NULL at bottom of stack. */
StackFrame* callersFrame;
/** Contents of stack frame */
char* stackData;
/** Frame base pointer (in stackData). */
char* frame;
/** Number of parameters passed to me by my caller. */
int numParams;
/** Farthest extent of local data from frame pointer. */
long largestOffset;
/** While a call from this frame is in progress, contains address
* of call instruction. */
int callPC;
/** During execution, entry point of function whose frame this
* is. */
Insn* entryPoint;
/** Parameters pushed by PUSH instructions, last at end. */
std::stack<Word> pendingParameters;
/** Register values. */
std::vector<Word> registers;
/** True iff this is the caller's frame during execution of
* VM::callFunction (so that on return, VM::callFunction should
* exit with the returned value, rather than having using
* completeCall). */
bool calledFromRuntime;
};
class EntryInsn : public Insn {
friend class VM;
public:
/** A function entry labeled LAB with N parameters. NEEDSLINK if
* needs a static link. MACHINE is the VM containing the
* instruction. */
EntryInsn (VM* machine, Label* lab, int n, bool needsLink)
: Insn (machine),
localOffset (0), numRegisters (0),
lab (lab), numParams (n), needsLink (needsLink)
{ }
void execute ();
void assemble ();
void dump ();
void insert ();
void executeEntry (int n, Word link);
protected:
/** Offset of last data allocated in this function's stack frame. */
long localOffset;
/** Maximum virtual registers used in this function. */
int numRegisters;
private:
Label* lab;
int numParams;
bool needsLink;
};
class NopInsn : public Insn {
public:
NopInsn (VM* machine) : Insn (machine) {}
void execute ();
void assemble ();
void dump ();
};
/** A LabelInsn is a special kind of instruction that represents a
* point in the program with a statement label. */
class LabelInsn : public Insn {
public:
LabelInsn (VM* machine, Label* stmtLabel)
: Insn (machine), stmtLabel (stmtLabel) {}
void execute ();
void assemble ();
void dump ();
private:
Label* const stmtLabel;
};
class PushInsn : public Insn {
public:
PushInsn (VM* machine, RegImm* opnd)
: Insn (machine), opnd (opnd) { }
void execute ();
void assemble ();
void dump ();
private:
RegImm* opnd;
};
class MoveInsn : public Insn {
public:
MoveInsn (VM* machine, Register* dest, Operand* src)
: Insn (machine), dest (dest), src (src) { }
MoveInsn (VM* machine, Memory* dest, RegImm* src)
: Insn (machine), dest (dest), src (src) { }
void execute ();
void assemble ();
void dump ();
private:
Operand* dest;
Operand* src;
};
class MoveAddrInsn : public Insn {
public:
MoveAddrInsn (VM* machine, Register* dest, Memory* src)
: Insn (machine), dest (dest), src (src) { }
void execute ();
void assemble ();
void dump ();
private:
Operand* dest;
Operand* src;
};
class NegInsn : public Insn {
public:
NegInsn (VM* machine, Register* dest, RegImm* src)
: Insn (machine), dest (dest), src (src) { }
void execute ();
void assemble ();
void dump ();
private:
Register* dest;
RegImm* src;
};
class AddInsn : public Insn {
public:
AddInsn (VM* machine, Register* dest, RegImm* opnd1, RegImm* opnd2)
: Insn (machine), dest (dest), opnd1 (opnd1), opnd2 (opnd2) { }
void execute ();
void assemble ();
void dump ();
private:
Register* dest;
RegImm* opnd1;
RegImm* opnd2;
};
class SubInsn : public Insn {
public:
SubInsn (VM* machine, Register* dest, RegImm* opnd1, RegImm* opnd2)
: Insn (machine), dest (dest), opnd1 (opnd1), opnd2 (opnd2) { }
void execute ();
void assemble ();
void dump ();
private:
Register* dest;
RegImm* opnd1;
RegImm* opnd2;
};
class MultInsn : public Insn {
public:
MultInsn (VM* machine, Register* dest, RegImm* opnd1, RegImm* opnd2)
: Insn (machine), dest (dest), opnd1 (opnd1), opnd2 (opnd2) { }
void execute ();
void assemble ();
void dump ();
private:
Register* dest;
RegImm* opnd1;
RegImm* opnd2;
};
class DivInsn : public Insn {
public:
DivInsn (VM* machine, Register* dest, RegImm* opnd1, RegImm* opnd2)
: Insn (machine), dest (dest), opnd1 (opnd1), opnd2 (opnd2) { }
void execute ();
void assemble ();
void dump ();
private:
Register* dest;
RegImm* opnd1;
RegImm* opnd2;
};
class ModInsn : public Insn {
public:
ModInsn (VM* machine, Register* dest, RegImm* opnd1, RegImm* opnd2)
: Insn (machine), dest (dest), opnd1 (opnd1), opnd2 (opnd2) { }
void execute ();
void assemble ();
void dump ();
private:
Register* dest;
RegImm* opnd1;
RegImm* opnd2;
};
class CallInsn : public Insn {
public:
CallInsn (VM* machine, Register* dest, Memory* target, int n)
: Insn (machine), dest (dest), n (n), target (target) { }
void execute ();
void assemble ();
void dump ();
protected:
void completeCall ();
private:
Register* dest;
int n;
Memory* target;
};
class CallSLInsn : public Insn {
public:
CallSLInsn (VM* machine, Register* dest, Memory* target, int n,
Register* link)
: Insn (machine), dest (dest), n (n), target (target),
link (link) { }
void execute ();
void assemble ();
void dump ();
protected:
void completeCall ();
private:
Register* dest;
int n;
Memory* target;
Register* link;
};
class RetInsn : public Insn {
public:
RetInsn (VM* machine, RegImm* opnd)
: Insn (machine), opnd (opnd) { }
void execute ();
void assemble ();
void dump ();
private:
RegImm* opnd;
};
class JumpInsn : public Insn {
public:
JumpInsn (VM* machine, Label* target)
: Insn (machine), target (target) { }
void execute ();
void assemble ();
void dump ();
private:
Label* target;
};
class IfEQInsn : public Insn {
public:
IfEQInsn (VM* machine, RegImm* opnd1, RegImm* opnd2, Label* target)
: Insn (machine), opnd1 (opnd1), opnd2 (opnd2),
target (target) { }
void execute ();
void assemble ();
void dump ();
private:
RegImm* opnd1;
RegImm* opnd2;
Label* target;
};
class IfNEInsn : public Insn {
public:
IfNEInsn (VM* machine, RegImm* opnd1, RegImm* opnd2, Label* target)
: Insn (machine), opnd1 (opnd1), opnd2 (opnd2),
target (target) { }
void execute ();
void assemble ();
void dump ();
private:
RegImm* opnd1;
RegImm* opnd2;
Label* target;
};
class IfGTInsn : public Insn {
public:
IfGTInsn (VM* machine, RegImm* opnd1, RegImm* opnd2, Label* target)
: Insn (machine), opnd1 (opnd1), opnd2 (opnd2),
target (target) { }
void execute ();
void assemble ();
void dump ();
private:
RegImm* opnd1;
RegImm* opnd2;
Label* target;
};
class IfLTInsn : public Insn {
public:
IfLTInsn (VM* machine, RegImm* opnd1, RegImm* opnd2, Label* target)
: Insn (machine), opnd1 (opnd1), opnd2 (opnd2),
target (target) { }
void execute ();
void assemble ();
void dump ();
private:
RegImm* opnd1;
RegImm* opnd2;
Label* target;
};
class IfGEInsn : public Insn {
public:
IfGEInsn (VM* machine, RegImm* opnd1, RegImm* opnd2, Label* target)
: Insn (machine), opnd1 (opnd1), opnd2 (opnd2),
target (target) { }
void execute ();
void assemble ();
void dump ();
private:
RegImm* opnd1;
RegImm* opnd2;
Label* target;
};
class IfLEInsn : public Insn {
public:
IfLEInsn (VM* machine, RegImm* opnd1, RegImm* opnd2, Label* target)
: Insn (machine), opnd1 (opnd1), opnd2 (opnd2),
target (target) { }
void execute ();
void assemble ();
void dump ();
private:
RegImm* opnd1;
RegImm* opnd2;
Label* target;
};
class ExitInsn : public Insn {
public:
ExitInsn (VM* machine) : Insn (machine) {}
void execute ();
void assemble ();
void dump ();
void insert ();
};
/** Represents a virtual register that resides in at a well-defined
* place in local memory when its function's stack frame is not the
* top of the stack. */
class AddressableRegister : public Register {
public:
void dump ();
bool isInFrame () const;
int frameOffset () const;
AddressableRegister (VM* machine, int id, int seq, int disp)
: Register (machine, id, seq), disp (disp) { }
protected:
Word fetchValue ();
void setValue (Word val);
int disp;
};
class LocalData : public Memory {
public:
LocalData (VM* machine, long offset)
: Memory (machine), offset (offset) { }
Memory* withOffset (int disp);
void dump ();
protected:
Word fetchAddress ();
private:
long offset;
};
class MemoryDisp : public Memory {
public:
MemoryDisp (VM* machine, long disp, Register* base)
: Memory (machine), disp (disp), base (base) {}
Memory* withOffset (int disp);
void dump ();
protected:
bool isMemory () const {
return true;
}
Word fetchAddress ();
private:
long disp;
Register* base;
};
class ImmediateInt : public Immediate {
public:
ImmediateInt (VM* machine, long val) : Immediate (machine), val (val) {}
void dump () {
fprintf (ILOut, "$%ld", val);
}
protected:
Word fetchValue ();
private:
long val;
};
class ImmediateAddr : public Immediate {
public:
ImmediateAddr (VM* machine, Label* lab, size_t disp = 0)
: Immediate (machine), lab (lab), disp (disp) {}
void dump () {
fprintf (ILOut, "$");
lab->dump ();
if (disp != 0)
fprintf (ILOut, "+%zu", disp);
}
protected:
Word fetchValue ();
private:
Label* lab;
size_t disp;
};
class FrameValue : public Register {
public:
FrameValue (VM* machine) : Register (machine, -1, -1) {}
void dump ();
bool isRegister () const;
protected:
Word fetchValue ();
};
/** Represents L+Disp for some label L and integer Disp. */
class OffsetLabel : public Label {
public:
OffsetLabel (Label* label, long disp) :
Label (label->getMachine ()), label (label), disp (disp) { }
Memory* withOffset (int disp);
void dump ();
protected:
Word fetchAddress ();
private:
Label* const label;
long disp;
};
class StmtLabel : public Label {
public:
StmtLabel (VM* machine) : Label (machine), defined (false), name () {}
StmtLabel (VM* machine, const char* name)
: Label (machine), defined (false), id (machine->newId ()),
name (name) {}
bool isDefined () const;
Memory* withOffset (int disp);
bool isCodeLabel () const;
void dump ();
protected:
void define ();
Word fetchValue ();
Word fetchAddress ();
int fetchPC ();
void resolve ();
private:
bool defined;
int id;
int pc;
std::string name;
};
class ExternalLabel : public Label {
public:
ExternalLabel (VM* machine, const char* name)
: Label (machine), name (name) {}
void dump ();
Memory* withOffset (int disp);
bool isDefined () const;
protected:
Word fetchAddress ();
void resolve ();
private:
std::string name;
void* address;
};
class ZeroStorage : public Label {
public:
ZeroStorage (VM* machine, size_t size);
bool isDefined () const;
Memory* withOffset (int disp);
void dump ();
void dumpDefn ();
~ZeroStorage ();
protected:
void initStatic (char*&, size_t&);
Word fetchAddress ();
private:
int id;
size_t size;
char* address;
};
class DataLabel : public Label {
public:
DataLabel (VM* machine, long disp)
: Label (machine), id (machine->newId ()), disp (disp)
{ }
Memory* withOffset (int disp);
bool isDefined () const;
void dump ();
void dumpDefn ();
protected:
Word fetchAddress ();
private:
int id;
long disp;
};
/** A StringData is a dummy operand (not usable in instructions) that
* denotes initialized static storage containing an ASCII string (as
* opposed to a pointer to same). */
class StringData : public Operand {
public:
StringData (VM* machine, const std::string& literal);
void dumpDefn ();
protected:
void initStatic (char*& nextInitialized, size_t& remainingInitialized);
private:
/** The original string literal. */
const std::string literal;
/** The data represented by the string literal. */
const std::string data;
};
/** An IntData is a dummy operand (not usable in instructions) that
* denotes static storage consisting of a single machine word
* initialized to a given integer. */
class IntData : public Operand {
public:
IntData (VM* machine, long data);
void dumpDefn ();
protected:
void initStatic (char*& nextInitialized, size_t& remainingInitialized);
private:
const long data;
};
/** An AddressData is a dummy operand (not usable in instructions)
* that denotes static storage consisting of a single machine word
* initialized to a given address value. */
class AddressData : public Operand {
public:
AddressData (VM* machine, Label* label, long disp);
void dumpDefn ();
protected:
void initStatic (char*& nextInitialized, size_t& remainingInitialized);
private:
Label* const label;
const long disp;
};
#endif
| |
242f3edc4bfa3cc35fd1a4c5b0379ed7017cd75e | 97386f844ed852f4f9cb6ffb2444333107e9b8a6 | /4_planning/visual_ekf_tester/src/qp_generator.cpp | 3c887807c74e350c28536e99d5159bb9fbef8109 | [
"MIT"
] | permissive | robomasterhkust/ros_environment | 865c43bfb1f7139992dcfbcf8ebb0801f5fb33f7 | bac3343bf92e6fa2bd852baf261e80712564f990 | refs/heads/master | 2018-12-27T05:19:11.121916 | 2018-11-21T09:16:57 | 2018-11-21T09:16:57 | 114,446,270 | 8 | 1 | MIT | 2018-09-21T06:50:53 | 2017-12-16T08:39:11 | C++ | UTF-8 | C++ | false | false | 10,966 | cpp | qp_generator.cpp | #include "qp_generator.h"
#include <stdio.h>
#include <ros/ros.h>
#include <ros/console.h>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
using namespace Eigen;
Vector3d startVel;
Vector3d startAcc;
#define inf 1>>30
int m=3; // number of segments in the trajectory
vector<double> TrajectoryGenerator::getCost() { return qp_cost; }
TrajectoryGenerator::TrajectoryGenerator(){}
TrajectoryGenerator::~TrajectoryGenerator(){}
Eigen::MatrixXd TrajectoryGenerator::PolyQPGeneration(
const Eigen::MatrixXd &Path,
const Eigen::Vector3d &Vel,
const Eigen::Vector3d &Acc,
const Eigen::VectorXd &Time,
const int &type) // 1 for using minumum snap for intial; 2 for using straight line for initial
{
/* Get initial trajectory which is a straight line( 0 zero end velocity and acceleration ) minimum snap trajectory or truly minumum snap trajectory */
startVel = Vel;
startAcc = Acc;
m = Time.size();
MatrixXd PolyCoeff(m, 3 * 6);
VectorXd Px(6 * m), Py(6 * m), Pz(6 * m);
int num_f, num_p; // number of fixed and free variables
int num_d; // number of all segments' derivatives
const static auto Factorial = [](int x){
int fac = 1;
for(int i = x; i > 0; i--)
fac = fac * i;
return fac;
};
/* Produce Mapping Matrix A to the entire trajectory. */
MatrixXd Ab;
MatrixXd A = MatrixXd::Zero(m * 6, m * 6);
for(int k = 0; k < m; k++){
Ab = Eigen::MatrixXd::Zero(6, 6);
for(int i = 0; i < 3; i++){
Ab(2 * i, i) = Factorial(i);
for(int j = i; j < 6; j++)
Ab( 2 * i + 1, j ) = Factorial(j) / Factorial( j - i ) * pow( Time(k), j - i );
}
A.block(k * 6, k * 6, 6, 6) = Ab;
}
_A = A;
/* Produce the dereivatives in X, Y and Z axis directly. */
VectorXd Dx = VectorXd::Zero(m * 6);
VectorXd Dy = VectorXd::Zero(m * 6);
VectorXd Dz = VectorXd::Zero(m * 6);
for(int k = 1; k < (m + 1); k ++ ){
Dx((k-1)*6) = Path(k - 1, 0); Dx((k-1)*6 + 1) = Path(k, 0);
Dy((k-1)*6) = Path(k - 1, 1); Dy((k-1)*6 + 1) = Path(k, 1);
Dz((k-1)*6) = Path(k - 1, 2); Dz((k-1)*6 + 1) = Path(k, 2);
if( k == 1){
Dx((k-1)*6 + 2) = Vel(0);
Dy((k-1)*6 + 2) = Vel(1);
Dz((k-1)*6 + 2) = Vel(2);
Dx((k-1)*6 + 4) = Acc(0);
Dy((k-1)*6 + 4) = Acc(1);
Dz((k-1)*6 + 4) = Acc(2);
}
}
/* Produce the Minimum Snap cost function, the Hessian Matrix */
MatrixXd H = MatrixXd::Zero( m * 6, m * 6 );
for(int k = 0; k < m; k ++){
for(int i = 3; i < 6; i ++){
for(int j = 3; j < 6; j ++){
H( k*6 + i, k*6 + j ) = i * (i - 1) * (i - 2) * j * (j - 1) * (j - 2) / (i + j - 5) * pow( Time(k), (i + j - 5) );
}
}
}
_Q = H; // Only minumum snap term is considered here inf the Hessian matrix
/* Produce Selection Matrix C' */
MatrixXd Ct; // The transpose of selection matrix C
MatrixXd C; // The selection matrix C
if(type == 1){ // generating minumum snap curve
num_f = 2 * m + 4; //3 + 3 + (m - 1) * 2 = 2m + 4
num_p = 2 * m - 2; //(m - 1) * 2 = 2m - 2
num_d = 6 * m;
Ct = MatrixXd::Zero(num_d, num_f + num_p);
Ct( 0, 0 ) = 1; Ct( 2, 1 ) = 1; Ct( 4, 2 ) = 1; // stack the start point
Ct( 1, 3 ) = 1; Ct( 3, 2 * m + 4 ) = 1; Ct( 5, 2 * m + 5 ) = 1;
Ct(6 * (m - 1) + 0, 2 * m + 0) = 1;
Ct(6 * (m - 1) + 1, 2 * m + 1) = 1; // Stack the end point
Ct(6 * (m - 1) + 2, 4 * m + 0) = 1;
Ct(6 * (m - 1) + 3, 2 * m + 2) = 1; // Stack the end point
Ct(6 * (m - 1) + 4, 4 * m + 1) = 1;
Ct(6 * (m - 1) + 5, 2 * m + 3) = 1; // Stack the end point
for(int j = 2; j < m; j ++ ){
Ct( 6 * (j - 1) + 0, 2 + 2 * (j - 1) + 0 ) = 1;
Ct( 6 * (j - 1) + 1, 2 + 2 * (j - 1) + 1 ) = 1;
Ct( 6 * (j - 1) + 2, 2 * m + 4 + 2 * (j - 2) + 0 ) = 1;
Ct( 6 * (j - 1) + 3, 2 * m + 4 + 2 * (j - 1) + 0 ) = 1;
Ct( 6 * (j - 1) + 4, 2 * m + 4 + 2 * (j - 2) + 1 ) = 1;
Ct( 6 * (j - 1) + 5, 2 * m + 4 + 2 * (j - 1) + 1 ) = 1;
}
C = Ct.transpose();
VectorXd Dx1 = C * Dx;
VectorXd Dy1 = C * Dy;
VectorXd Dz1 = C * Dz;
MatrixXd Q; // The Hessian of the total cost function
Q = H; // Now only minumum snap is used in the cost
MatrixXd R = C * A.transpose().inverse() * Q * A.inverse() * Ct;
VectorXd Dxf(2 * m + 4), Dyf(2 * m + 4), Dzf(2 * m + 4);
Dxf = Dx1.segment( 0, 2 * m + 4 );
Dyf = Dy1.segment( 0, 2 * m + 4 );
Dzf = Dz1.segment( 0, 2 * m + 4 );
MatrixXd Rff(2 * m + 4, 2 * m + 4);
MatrixXd Rfp(2 * m + 4, 2 * m - 2);
MatrixXd Rpf(2 * m - 2, 2 * m + 4);
MatrixXd Rpp(2 * m - 2, 2 * m - 2);
Rff = R.block(0, 0, 2 * m + 4, 2 * m + 4);
Rfp = R.block(0, 2 * m + 4, 2 * m + 4, 2 * m - 2);
Rpf = R.block(2 * m + 4, 0, 2 * m - 2, 2 * m + 4);
Rpp = R.block(2 * m + 4, 2 * m + 4, 2 * m - 2, 2 * m - 2);
VectorXd Dxp(2 * m - 2), Dyp(2 * m - 2), Dzp(2 * m - 2);
Dxp = - (Rpp.inverse() * Rfp.transpose()) * Dxf;
Dyp = - (Rpp.inverse() * Rfp.transpose()) * Dyf;
Dzp = - (Rpp.inverse() * Rfp.transpose()) * Dzf;
Dx1.segment(2 * m + 4, 2 * m - 2) = Dxp;
Dy1.segment(2 * m + 4, 2 * m - 2) = Dyp;
Dz1.segment(2 * m + 4, 2 * m - 2) = Dzp;
Px = (A.inverse() * Ct) * Dx1;
Py = (A.inverse() * Ct) * Dy1;
Pz = (A.inverse() * Ct) * Dz1;
_Dx = Ct * Dx1;
_Dy = Ct * Dy1;
_Dz = Ct * Dz1;
_Pxi = Px; _Pyi = Py; _Pzi = Pz;
}
else{ // generating piecewise straight line
num_f = 3 * m + 3; // All fixed 3 + 3 + (m - 1) * 3
num_p = 0; // No free derivatives
num_d = 6 * m;
Ct = MatrixXd::Zero(num_d, num_d);
for(int j = 1; j < (m + 1); j ++ ){
Ct( 6 * (j - 1) + 0, 6 * (j - 1) + 0 ) = 1;
Ct( 6 * (j - 1) + 1, 6 * (j - 1) + 3 ) = 1;
Ct( 6 * (j - 1) + 2, 6 * (j - 1) + 1 ) = 1;
Ct( 6 * (j - 1) + 3, 6 * (j - 1) + 4 ) = 1;
Ct( 6 * (j - 1) + 4, 6 * (j - 1) + 2 ) = 1;
Ct( 6 * (j - 1) + 5, 6 * (j - 1) + 5 ) = 1;
}
C = Ct.transpose();
Px = A.inverse() * Dx;
Py = A.inverse() * Dy;
Pz = A.inverse() * Dz;
_Dx = Dx;
_Dy = Dy;
_Dz = Dz;
_Pxi = Px; _Pyi = Py; _Pzi = Pz;
}
for(int i = 0; i < m; i ++){
PolyCoeff.block(i, 0, 1, 6) = Px.segment( i * 6, 6 ).transpose();
PolyCoeff.block(i, 6, 1, 6) = Py.segment( i * 6, 6 ).transpose();
PolyCoeff.block(i, 12, 1, 6) = Pz.segment( i * 6, 6 ).transpose();
}
ROS_WARN("[Generator] Unconstrained QP solved");
return PolyCoeff;
}
void TrajectoryGenerator::StackOptiDep(){
double num_f = 6; // 4 + 4 : only start and target position has fixed derivatives
double num_p = 3 * m - 3; // All other derivatives are free
double num_d = 6 * m;
MatrixXd Ct;
Ct = MatrixXd::Zero(num_d, num_f + num_p);
Ct( 0, 0 ) = 1; Ct( 2, 1 ) = 1; Ct( 4, 2 ) = 1; // Stack the start point
Ct( 1, 6 ) = 1; Ct( 3, 7 ) = 1; Ct( 5, 8 ) = 1;
Ct(6 * (m - 1) + 0, 3 * m + 0 ) = 1;
Ct(6 * (m - 1) + 2, 3 * m + 1 ) = 1;
Ct(6 * (m - 1) + 4, 3 * m + 2 ) = 1;
Ct(6 * (m - 1) + 1, 3) = 1; // Stack the end point
Ct(6 * (m - 1) + 3, 4) = 1;
Ct(6 * (m - 1) + 5, 5) = 1;
for(int j = 2; j < m; j ++ ){
Ct( 6 * (j - 1) + 0, 6 + 3 * (j - 2) + 0 ) = 1;
Ct( 6 * (j - 1) + 1, 6 + 3 * (j - 1) + 0 ) = 1;
Ct( 6 * (j - 1) + 2, 6 + 3 * (j - 2) + 1 ) = 1;
Ct( 6 * (j - 1) + 3, 6 + 3 * (j - 1) + 1 ) = 1;
Ct( 6 * (j - 1) + 4, 6 + 3 * (j - 2) + 2 ) = 1;
Ct( 6 * (j - 1) + 5, 6 + 3 * (j - 1) + 2 ) = 1;
}
_C = Ct.transpose();
_L = _A.inverse() * Ct;
MatrixXd B = _A.inverse();
_R = _C * B.transpose() * _Q * (_A.inverse()) * Ct;
_Rff.resize(6, 6);
_Rfp.resize(6, 3 * m - 3);
_Rpf.resize(3 * m - 3, 6);
_Rpp.resize(3 * m - 3, 3 * m - 3);
_Rff = _R.block(0, 0, 6, 6);
_Rfp = _R.block(0, 6, 6, 3 * m - 3);
_Rpf = _R.block(6, 0, 3 * m - 3, 6);
_Rpp = _R.block(6, 6, 3 * m - 3, 3 * m - 3);
ROS_WARN("[Generator] Stack finish");
}
std::pair< Eigen::MatrixXd, Eigen::MatrixXd > TrajectoryGenerator::getInitialD()
{
// Return Format: row(0) -> X | row(1) -> Y | row(2) -> Z
VectorXd Dxf = VectorXd::Zero(6);
VectorXd Dyf = VectorXd::Zero(6);
VectorXd Dzf = VectorXd::Zero(6);
VectorXd Dxp = VectorXd::Zero(3 * m - 3);
VectorXd Dyp = VectorXd::Zero(3 * m - 3);
VectorXd Dzp = VectorXd::Zero(3 * m - 3);
Dxf(0) = _Dx(0); Dxf(3) = _Dx( _Dx.size() - 5 );
Dyf(0) = _Dy(0); Dyf(3) = _Dy( _Dy.size() - 5 );
Dzf(0) = _Dz(0); Dzf(3) = _Dz( _Dz.size() - 5 );
Dxf(1) = startVel(0);
Dyf(1) = startVel(1);
Dzf(1) = startVel(2);
Dxf(2) = startAcc(0);
Dyf(2) = startAcc(1);
Dzf(2) = startAcc(2);
for (int k = 1; k < m; k ++ ){
for (int i = 0; i < 3; i ++ ){
Dxp( (k - 1) * 3 + i) = _Dx((k - 1) * 6 + 2 * i + 1);
Dyp( (k - 1) * 3 + i) = _Dy((k - 1) * 6 + 2 * i + 1);
Dzp( (k - 1) * 3 + i) = _Dz((k - 1) * 6 + 2 * i + 1);
}
}
MatrixXd Dp(3, Dxp.size()), Df(3, Dxf.size());
Dp.row(0) = Dxp;
Dp.row(1) = Dyp;
Dp.row(2) = Dzp;
Df.row(0) = Dxf;
Df.row(1) = Dyf;
Df.row(2) = Dzf;
return make_pair(Dp, Df);
}
Eigen::MatrixXd TrajectoryGenerator::getA(){ return _A; }
Eigen::MatrixXd TrajectoryGenerator::getQ(){ return _Q; }
Eigen::MatrixXd TrajectoryGenerator::getC(){ return _C; }
Eigen::MatrixXd TrajectoryGenerator::getL(){ return _L; }
Eigen::MatrixXd TrajectoryGenerator::getR(){ return _R; }
Eigen::MatrixXd TrajectoryGenerator::getRff(){ return _Rff; }
Eigen::MatrixXd TrajectoryGenerator::getRpp(){ return _Rpp; }
Eigen::MatrixXd TrajectoryGenerator::getRpf(){ return _Rpf; }
Eigen::MatrixXd TrajectoryGenerator::getRfp(){ return _Rfp; } |
7e82b7eaa2f4c7d88dac3fb77ae628a25fab4ca7 | 97478f3322b1120f7bda1ce87e2f2de93ea8b1cb | /ast.hh | 81f0f171e91ea04a52e2db7e864c211c852f4513 | [
"MIT"
] | permissive | piotrbla/simplePoly | e1c0a9b33bfe3ef466b0c94ad582d0dafe1a8bda | 0b26e555d390dde81fbc23d71cf1b490d1204504 | refs/heads/master | 2021-07-15T02:24:43.420409 | 2021-06-16T22:31:15 | 2021-06-16T22:31:15 | 85,855,498 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,216 | hh | ast.hh | #ifndef TC_AST_H
#define TC_AST_H
#include <isl/ctx.h>
#include <isl/id.h>
#include <isl/ast.h>
#include <pet.h>
struct tc_ast_stmt_annotation
{
struct pet_stmt* stmt;
isl_id_to_ast_expr* id2expr;
};
struct tc_ast_for_annotation
{
isl_id_list* nested_iterators;
isl_bool is_parallel;
};
struct tc_ast_visitor_context
{
isl_id_list* annotations_stack;
isl_id_list* parallel_iterators;
};
struct tc_ast_visitor_context* tc_ast_visitor_context_alloc(__isl_keep isl_ctx* ctx);
void tc_ast_visitor_context_free(struct tc_ast_visitor_context* context);
__isl_give isl_ast_node* tc_ast_visitor_at_each_domain(__isl_take isl_ast_node* node, __isl_keep isl_ast_build* build, void* user);
__isl_give isl_id* tc_ast_visitor_before_for(__isl_keep isl_ast_build* build, void* user);
__isl_give isl_ast_node* tc_ast_visitor_after_for(__isl_take isl_ast_node* node, __isl_keep isl_ast_build* build, void* user);
struct tc_ast_stmt_annotation* tc_ast_stmt_annotation_alloc();
void tc_ast_stmt_annotation_free(void* user);
struct tc_ast_for_annotation* tc_ast_for_annotation_alloc(__isl_keep isl_ctx* ctx);
void tc_ast_for_annotation_free(void* user);
#endif // TC_AST_H
|
885c067dcb4360c80191a7afb57d0d4a06ecea5b | d51f3b5d0a8b85d0de7f275f59f65a9b7b978b8a | /UVA/1237/19817384_AC_10ms_0kB.cpp | 6cd4faa4604c2c8255659b34beea569681adadb3 | [] | no_license | CIA66/Competitive-Programming | 418af2c3eb30f78fc5e143d47972fb202f0b61c0 | 9afd528959a7fc2c31cafb143ed0a87e2a10ef88 | refs/heads/main | 2023-02-09T08:09:06.874776 | 2020-10-30T06:52:14 | 2020-10-30T06:52:14 | 308,543,870 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 691 | cpp | 19817384_AC_10ms_0kB.cpp | #include<stdio.h>
struct Data{
char name[26];
int low;
int hi;
}data[10006];
int main(){
int T = 0;
scanf("%d", &T);
for(int a=0; a<T; a++){
int D = 0;
scanf("%d", &D);
for(int b = 0; b<D; b++){
scanf("%s %d %d", data[b].name, &data[b].low, &data[b].hi);
}
int Q = 0, count = 0, idx = 0;
scanf("%d", &Q);
for(int c=0; c<Q; c++){
int P = 0;
scanf("%d", &P);
count = 0;
for(int d=0; d<D; d++){
if(data[d].low <= P && P <= data[d].hi){
count++;
idx = d;
}
if(count > 1){
break;
}
}
if(count == 1) printf("%s\n", data[idx].name);
else printf("UNDETERMINED\n");
}
if(a != T-1) puts("");
}
return 0;
} |
e2f53513f750ffb1aa3b531caba93c309d472623 | 9dc602674d32e79112c3e5598977d9d69470fa90 | /ex8/Cell.h | eaaa78da1ba8eccde40a5397a6a20942a64fc814 | [] | no_license | meravboim/cpp-ariel | e2a992aa12143b5d196b13aa65085a50ece27687 | 1523fab6067ccf15395d8865b898a78b1246b79f | refs/heads/master | 2021-04-15T12:25:14.306114 | 2018-06-11T13:09:36 | 2018-06-11T13:09:36 | 126,877,150 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 657 | h | Cell.h | #pragma once
#include <iostream>
#include "IllegalCharException.h"
using namespace std;
class Cell {
friend class Board;
public:
Cell (char c) : my_char(c){ //construter
if(c!= 'X' && c!='O' && c!='.')
throw IllegalCharException(c);
}
Cell (){ //empty construter;
my_char='.';
}
Cell& operator=(char c){
if(c!= 'X' && c!='O' && c!='.')
throw IllegalCharException(c);
my_char=c;
return *this;
}
Cell& operator=(Cell c){
my_char=c.my_char;
return *this;
}
friend ostream& operator<< (ostream& os, const Cell& c){
os << c.my_char;
return os;
}
operator char() { return my_char; }
char my_char;
};
|
43ce43ab1ece3e2e9517ae2d5d77b1f4418d7419 | 006ff11fd8cfd5406c6f4318f1bafa1542095f2a | /CondTools/Hcal/bin/corrResps.cc | a1c842e2356b53d731ccf32d44f9161e5eb9031a | [] | permissive | amkalsi/cmssw | 8ac5f481c7d7263741b5015381473811c59ac3b1 | ad0f69098dfbe449ca0570fbcf6fcebd6acc1154 | refs/heads/CMSSW_7_4_X | 2021-01-19T16:18:22.857382 | 2016-08-09T16:40:50 | 2016-08-09T16:40:50 | 262,608,661 | 0 | 0 | Apache-2.0 | 2020-05-09T16:10:07 | 2020-05-09T16:10:07 | null | UTF-8 | C++ | false | false | 1,218 | cc | corrResps.cc | #include <stdlib.h>
#include <iostream>
#include <fstream>
#include <vector>
#include "CalibCalorimetry/HcalAlgos/interface/HcalDbASCIIIO.h"
#include "CondFormats/HcalObjects/interface/HcalRespCorrs.h"
#include "Geometry/CaloTopology/interface/HcalTopology.h"
int main (int argn, char* argv []) {
if (argn < 3) {
std::cerr << "Use: " << argv[0] << " <RespCorrs to scale (.txt)> <resultRespCorrs (.txt)> <correction-respcorr (.txt)>" << std::endl;
return 1;
}
HcalTopology topo(HcalTopologyMode::LHC,2,3);
std::ifstream inStream (argv[1]);
std::ofstream outStream (argv[2]);
std::ifstream inCorr (argv[3]);
HcalRespCorrs respIn(&topo);
HcalDbASCIIIO::getObject (inStream, &respIn);
HcalRespCorrs corrsIn(&topo);
HcalDbASCIIIO::getObject (inCorr, &corrsIn);
HcalRespCorrs respOut(&topo);
std::vector<DetId> channels = respIn.getAllChannels ();
for (unsigned i = 0; i < channels.size(); i++) {
DetId id = channels[i];
float scale = 1.0;
if (corrsIn.exists(id)) scale = corrsIn.getValues(id)->getValue();
HcalRespCorr item (id, respIn.getValues(id)->getValue() * scale);
respOut.addValues(item);
}
HcalDbASCIIIO::dumpObject (outStream, respOut);
return 0;
}
|
6e4373b81935266f80ae4c27bd05621147cf8bee | a309d6ea67b7caf7177bf34ccc064f46bfaad7b5 | /ServiceManager/Service.h | dea24e6b609c123f066f0468739519271509078d | [
"MIT"
] | permissive | fengjixuchui/JAV-AV-Engine | a968ecd18ad4954e3668030f92e5680d93cd0969 | c258c1bb283d2cccc358dab5d3a7bacd4fc35790 | refs/heads/master | 2020-04-30T16:08:46.699929 | 2018-08-25T09:28:44 | 2018-08-25T09:28:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 175 | h | Service.h |
#ifndef _SERVICE_
#define _SERVICE_
class Service
{
public:
virtual bool Start()=0;
virtual bool Stop()=0;
virtual bool Puase()=0;
virtual bool Continue()=0;
};
#endif |
9bbe8574515f5db7ff782bc830f7b441785dd0c4 | adc7281c7087675312a5b5f8d8eb746a228235ff | /library/fileOperations.cpp | 52519495f1530b0d231d3deee35ad2e1b0747e12 | [] | no_license | cerber-os/TIN | d43695f23cada6a7d71ac9f8235f30d71832b0c8 | 46f770cab4eae0bf494126f48b2482bd4d6f2b18 | refs/heads/master | 2023-02-25T10:58:22.659479 | 2021-01-31T22:27:22 | 2021-01-31T22:27:22 | 326,817,777 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,828 | cpp | fileOperations.cpp | #include "fileOperations.h"
using namespace std;
bool check_if_its_number(string str) {
for (int i = 0; i < str.length(); i++)
if (isdigit(str[i]) == false)
return false;
return true;
}
uint16_t getPortFromString(string host){
size_t pos = host.find_last_of(':');
string port = host.substr(pos + 1, host.length() - 1);
if(!port.empty() && check_if_its_number(port)){
return (uint16_t)stoul( port );
}
std::cerr << "Invalid port input" << std::endl;
return 0;
}
string getIpFromString (string host){
size_t pos = host.find_last_of(':');
string ip = host.substr(0, pos);
return ip;
}
int mynfs_open(char *host, char *path, int oflag, int mode, int *socketFd){
//obsluga komunikatu podrzednego
int path_length = strlen(path);
int sub_msg_size = sizeof (mynfs_open_t) + path_length + 1; // +1, bo znak konca null
mynfs_open_t *clientSubMsg;
clientSubMsg = (mynfs_open_t *)malloc (sub_msg_size);
strcpy((char*)clientSubMsg->name, path);
clientSubMsg->path_length = path_length;
clientSubMsg->oflag = oflag;
clientSubMsg->mode = mode;
//obsluga komunikatu nadrzednego
mynfs_message_t *clientMsg;
clientMsg = (mynfs_message_t *)malloc (sizeof (mynfs_message_t) + sub_msg_size);
memcpy(clientMsg->data, clientSubMsg, sub_msg_size);
free(clientSubMsg);
clientMsg->cmd= MYNFS_CMD_OPEN;
clientMsg->handle = 0;
clientMsg->data_length = sub_msg_size;
mynfs_message_t *serverMsg;
*socketFd = createSocket((char*)getIpFromString(string(host)).c_str(), getPortFromString(string(host)));
if(*socketFd == -1){
free(clientMsg);
return -1;
}
if(sendAndGetResponse(*socketFd, clientMsg, &serverMsg) == -1){
free(clientMsg);
return -1;
}
free(clientMsg);
return serverMsg->return_value;
}
int mynfs_read(int socketFd, int fd, void *buf, size_t count)
{
//obsluga komunikatu podrzednego
mynfs_read_t clientSubMsg;
clientSubMsg.length = count;
//obsluga komunikatu nadrzednego
mynfs_message_t *clientMsg;
clientMsg = (mynfs_message_t *)malloc (sizeof (mynfs_message_t) + sizeof(mynfs_read_t));
memcpy(clientMsg->data, &clientSubMsg, sizeof(mynfs_read_t));
clientMsg->cmd= MYNFS_CMD_READ;
clientMsg->handle = fd;
clientMsg->data_length = sizeof(mynfs_read_t);
mynfs_message_t *serverMsg;
if(sendAndGetResponse(socketFd, clientMsg, &serverMsg) == -1){
free(clientMsg);
return -1;
}
memcpy(buf, serverMsg->data, serverMsg->data_length);
free(clientMsg);
return serverMsg->return_value;
}
ssize_t mynfs_write(int socketFd, int fd, void *buf, size_t count)
{
char *bufor = (char *)buf;
int buf_length = count;
int sub_msg_size = sizeof(mynfs_write_t) + buf_length + 1;
//obsluga komunikatu podrzednego
mynfs_write_t *clientSubMsg = (mynfs_write_t *)malloc (sub_msg_size);
clientSubMsg->length = count;
strcpy((char*)clientSubMsg->buffer, bufor);
clientSubMsg->length = buf_length;
//obsluga komunikatu nadrzednego
mynfs_message_t *clientMsg;
clientMsg = (mynfs_message_t *)malloc (sizeof (mynfs_message_t) + sub_msg_size);
memcpy(clientMsg->data, clientSubMsg, sub_msg_size);
free(clientSubMsg);
clientMsg->cmd= MYNFS_CMD_WRITE;
clientMsg->handle = fd;
clientMsg->data_length = sub_msg_size;
mynfs_message_t *serverMsg;
if(sendAndGetResponse(socketFd, clientMsg, &serverMsg) == -1){
free(clientMsg);
return -1;
}
free(clientMsg);
return serverMsg->return_value;
}
off_t mynfs_lseek(int socketFd, int fd, off_t offset, int whence){
//obsluga komunikatu podrzednego
mynfs_lseek_t clientSubMsg;
clientSubMsg.offset = offset;
clientSubMsg.whence = whence;
//obsluga komunikatu nadrzednego
mynfs_message_t *clientMsg;
clientMsg = (mynfs_message_t *)malloc (sizeof (mynfs_message_t) + sizeof(mynfs_lseek_t));
memcpy(clientMsg->data, &clientSubMsg, sizeof(mynfs_lseek_t));
clientMsg->cmd= MYNFS_CMD_LSEEK;
clientMsg->handle = fd;
clientMsg->data_length = sizeof(mynfs_lseek_t);
mynfs_message_t *serverMsg;
if(sendAndGetResponse(socketFd, clientMsg, &serverMsg) == -1){
free(clientMsg);
return -1;
}
free(clientMsg);
return serverMsg->return_value;
}
int mynfs_close(int socketFd, int fd)
{
//brak komunikatu podrzednego
//obsluga komunikatu nadrzednego
mynfs_message_t *clientMsg;
clientMsg = (mynfs_message_t *)malloc (sizeof (mynfs_message_t));
clientMsg->cmd= MYNFS_CMD_CLOSE;
clientMsg->handle = fd;
clientMsg->data_length = 0;
mynfs_message_t *serverMsg;
if(sendAndGetResponse(socketFd, clientMsg, &serverMsg) == -1){
free(clientMsg);
return -1;
}
free(clientMsg);
return serverMsg->return_value;
}
int mynfs_unlink(char *host, char *pathname)
{
//obsluga komunikatu podrzednego
int path_length = strlen(pathname);
int sub_msg_size = sizeof (mynfs_unlink_t) + path_length + 1; // +1, bo znak konca null
mynfs_unlink_t *clientSubMsg;
clientSubMsg = (mynfs_unlink_t *)malloc (sub_msg_size);
strcpy((char*)clientSubMsg->name, pathname);
clientSubMsg->path_length = path_length;
//obsluga komunikatu nadrzednego
mynfs_message_t *clientMsg;
clientMsg = (mynfs_message_t *)malloc (sizeof (mynfs_message_t) + sub_msg_size);
memcpy(clientMsg->data, clientSubMsg, sub_msg_size);
free(clientSubMsg);
clientMsg->cmd= MYNFS_CMD_UNLINK;
clientMsg->handle = 0;
clientMsg->data_length = sub_msg_size;
mynfs_message_t *serverMsg;
int socketFd = createSocket((char*)getIpFromString(string(host)).c_str(), getPortFromString(string(host)));
if(socketFd == -1){
free(clientMsg);
return -1;
}
if(sendAndGetResponse(socketFd, clientMsg, &serverMsg) == -1){
free(clientMsg);
return -1;
}
if(closeSocket(socketFd) == -1){
free(clientMsg);
return -1;
}
free(clientMsg);
return serverMsg->return_value;
}
int mynfs_fstat(int socketFd, int fd, struct stat *buf)
{
//brak komunikatu podrzednego
//obsluga komunikatu nadrzednego
mynfs_message_t *clientMsg;
clientMsg = (mynfs_message_t *)malloc (sizeof (mynfs_message_t));
clientMsg->cmd= MYNFS_CMD_FSTAT;
clientMsg->handle = fd;
clientMsg->data_length = 0;
mynfs_message_t *serverMsg;
if(sendAndGetResponse(socketFd, clientMsg, &serverMsg) == -1){
free(clientMsg);
return -1;
}
stat *stat_table = (stat *) serverMsg->data;
memcpy(buf, stat_table, serverMsg->data_length);
free(clientMsg);
return serverMsg->return_value;
} |
dfd40131070ae1ed6ffd0b090ffd01d7a911d3c6 | 1c7acbcbbd55ce560deee761d93dc6996660b88a | /Tutorial 7/Ejemplo1/Ejemplo1.ino | f9969335177543ce964c618bc8e6041a65f381d8 | [
"MIT"
] | permissive | ESIBot/taller-microcontroladores | a8f7a3f8232a00e8e4f974a76bc71d5e61902ab2 | bb94e692490a8a0b95107de5848dc3ba275bfb37 | refs/heads/master | 2021-01-09T05:52:54.392394 | 2017-02-03T12:45:15 | 2017-02-03T12:47:56 | 80,828,168 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,132 | ino | Ejemplo1.ino | /*
Tutorial 7 - Ejemplo 1
Comunicación con ADXL345 mediante I2C
Taller de uControladores ESIBot 2013
*/
#include <Wire.h>
#define ADXL345ADDRESS 0x53 //Dirección del acelerómetro
#define DATAADDRESS 0x32 //Primer registro con los datos de los ejes
#define POWER_CTL 0x2D //Registro de control de energía
#define POWER_CTL_VALUE 8 //Valor que cargaremos en POWER_CTL
#define SCALE2G 0.0039
#define LENGTH 6
void setup()
{
Serial.begin(9600);
Wire.begin(); //Iniciamos el bus I2C en modo maestro
writeTo(ADXL345ADDRESS,POWER_CTL, POWER_CTL_VALUE); //Antes de poder realizar mediciones se necesita configurar el registro de control de energía
}
uint8_t* p_buffer = NULL;
int xAxis; //Variables que usaremos para imprimir el resultado
int yAxis;
int zAxis;
float scaledXAxis; //Variables que usaremos para imprimir el resultado con una escala mas intuitiva
float scaledYAxis;
float scaledZAxis;
void loop(){
p_buffer = readFrom(ADXL345ADDRESS, DATAADDRESS, LENGTH); //Lectura de los datos del acelerómetro
xAxis = (p_buffer[1] << 8) | p_buffer[0]; //El acelerómetro almacena el valor de cada eje en dos bytes por lo que
yAxis = (p_buffer[3] << 8) | p_buffer[2]; //necesitamos hacer esto para tener el dato completo
zAxis = (p_buffer[5] << 8) | p_buffer[4];
scaledXAxis = SCALE2G * xAxis; //Escalamos el valor en "G"
scaledYAxis = SCALE2G * yAxis;
scaledZAxis = SCALE2G * zAxis;
Serial.print("Raw:\t"); //Imprimimos los valores obtenidos
Serial.print(xAxis);
Serial.print(" ");
Serial.print(yAxis);
Serial.print(" ");
Serial.print(zAxis);
Serial.print(" \tScaled:\t");
Serial.print(scaledXAxis);
Serial.print("G ");
Serial.print(scaledYAxis);
Serial.print("G ");
Serial.print(scaledZAxis);
Serial.println("G");
delay(200);
}
/****************************** FUNCIONES *******************************/
void writeTo(int slave_Address, int address, int data){
Wire.beginTransmission(slave_Address); //Ponemos en el bus la dirección del dispositivo con el que nos quereos comunicar
Wire.write(address); //Registro al que queremos acceder
Wire.write(data); //Dato que queremos poner en el registro
Wire.endTransmission(); //Terminar la transmisión
}
uint8_t* readFrom(int slave_Address, int address, int length){
uint8_t buffer[length]; //Buffer donde iremos guardando los datos que recibamos
Wire.beginTransmission(slave_Address); //Dirección del dispositivo con el que nos queremos comunicar
Wire.write(address); //Que registro al que queremos acceder
Wire.endTransmission();
Wire.beginTransmission(slave_Address); //Start repetido
Wire.requestFrom(slave_Address, length); //Modo lectura y cuantos bytes queremos
if(Wire.available() == length){
for(uint8_t i = 0; i < length; i++){ //Leemos cada byte y rellenamos el buffer
buffer[i] = Wire.read();
}
}
Wire.endTransmission();
return buffer;
}
|
335580b52853a5f558cb677f1d44661d32a79100 | 0dc20516079aaae4756d28e67db7cae9c0d33708 | /jxy/jxy_src/jxysvr/src/server/gameserver/logic/awaken/awakenpropmgr.h | fe2cf824335cb6fa201293f1a7fa062289b6ce14 | [] | no_license | psymicgit/dummy | 149365d586f0d4083a7a5719ad7c7268e7dc4bc3 | 483f2d410f353ae4c42abdfe4c606ed542186053 | refs/heads/master | 2020-12-24T07:48:56.132871 | 2017-08-05T07:20:18 | 2017-08-05T07:20:18 | 32,851,013 | 3 | 8 | null | null | null | null | GB18030 | C++ | false | false | 5,548 | h | awakenpropmgr.h |
#ifndef _AWAKENBASEPROPPROPMGR_H_
#define _AWAKENBASEPROPPROPMGR_H_
#include <sddb.h>
#include <sdsingleton.h>
#include <sdtype.h>
#include <sdhashmap.h>
#include <common/server/utility.h>
#include <common/client/commondef.h>
#include <logic/base/basepropmgr.h>
using namespace SGDP;
#define GOLD_RUDING_PROP 110 //悟道等级配置元宝悟道入定状态配置
#define GOLD_CHEWU_PROP 111 //悟道等级配置元宝悟道彻悟状态配置
//基本配置
struct SAwakenBaseProp
{
UINT32 dwGoldAwaken; //元宝悟道进入入定状态所需元宝
UINT32 dwGenStudyCoin; //悟道心得获得铜钱时的铜钱
UINT8 byMaxStudyLevel; //心得最大等级
};
//悟道等级配置
struct SAwakenLevelProp
{
UINT8 byAwakenLevel; // 悟到道别(从1开始,共5级(瞌睡/神游/冥思/入定/彻悟), (配置中110为元宝悟道入定状态配置,111为彻悟)
UINT32 dwNeedCoin; // 悟道所需铜币
UINT8 byNextLevelRate; // 跳到下一级概率(失败则返回第一级)
UINT8 byCoinRate; // 铜钱概率
UINT8 byBuleStudyRate; // 蓝色心得碎片概率
UINT8 byPurpleStudyRate; // 紫色心得碎片概率
UINT8 byRedStudyRate; // 红色心得碎片概率
UINT8 byOrangeStudyRate; // 橙色心得碎片概率
CRandomVec vecRandom; //心得概率,按颜色插入顺序
};
//心得生成概率及解锁配置(该等级有则表示已解锁)
struct SAwakenStudyGenUnlockProp
{
UINT16 wPlayerLevel; // 玩家等级
UINT8 byStudyColorKind; // 心得颜色类型
UINT8 byStudyAttrKind; // 心得属性类型
UINT8 byGenRate; // 生成概率
};
typedef vector<SAwakenStudyGenUnlockProp> CAwakenStudyGenUnlockPropVec;
//玩家每等级心得生成概率及解锁配置
struct SPlayerAwakenStudyGenUnlockProp
{
UINT16 wPlayerLevel;
CAwakenStudyGenUnlockPropVec avecAwakenStudyGenUnlockProp[EC_ORANGE+1]; //4种颜色的配置,下标为颜色
CRandomVec avecRandom[EC_ORANGE+1]; //4种颜色生成概率,按vecAwakenStudyGenUnlockProp插入顺序
};
//心得生成概率及解锁配置(该等级有的心得则表示已解锁)
typedef HashMap<UINT16, SPlayerAwakenStudyGenUnlockProp> CLevel2UnlockStudyColorProMap; //key为玩家等级wPlayerLevel
typedef CLevel2UnlockStudyColorProMap::iterator CLevel2UnlockStudyColorProMapItr;
//心得属性配置
struct SAwakenStudyAttrProp
{
UINT8 byStudyColorKind; // 心得颜色类型
UINT8 byStudyAttrKind; // 心得属性类型
UINT8 byStudyLevel; // 心得等级
UINT32 dwAttrValue; // 心得属性值
UINT32 dwHaveExp; // 拥有的经验
};
typedef HashMap<UINT32, SAwakenStudyAttrProp> CAwakenStudyAttrPropMap; //key为byStudyColorKind+byStudyAttrKind+byStudyLevel
typedef CAwakenStudyAttrPropMap::iterator CAwakenStudyAttrPropMapItr;
class CAwakenPropMgr : public CBasePopMgr
{
public:
DECLARE_SINGLETON_PROPMGR(CAwakenPropMgr);
public:
virtual EConfigModule GetConfigModuleType() { return ECM_AWAKEN ; }
BOOL Init();
VOID UnInit();
public:
inline UINT32 GetAwakenGold() { return m_stAwakenBaseProp.dwGoldAwaken; }
inline VOID GetwLevelStudyUnlockLevelInfo(UINT16 awStudyUnlockLevelInfo[MAX_HERO_STUDY_GRID_NUM]) { memcpy(awStudyUnlockLevelInfo, m_awStudyUnlockLevelInfo, sizeof(m_awStudyUnlockLevelInfo)); }
inline UINT16 GetMaxStudyLevel() { return m_stAwakenBaseProp.byMaxStudyLevel; }
//////////////////////////
UINT32 GetAwakenCoin(UINT8 byGoldFlag, UINT8 byAwakenLevel);
VOID GetAwakenCoin(UINT32 adwAwakenCoin[MAX_AWAKEN_NUM]) { memcpy(adwAwakenCoin, m_adwAwakenCoin, sizeof(m_adwAwakenCoin)); }
UINT8 AwakenStudy(UINT16 wPlayerLevel, UINT8 byAwakenLevel, UINT8 byGoldFlag, UINT8& byStudyColorKind, UINT8& byStudyAttrKind, UINT32& dwGenCoin);
UINT32 GetStudyExp(UINT8 byStudyColorKind, UINT8 byStudyAttrKind, UINT8 byStudyLevel);
UINT32 GetStudyUpgradeNeedExp(UINT8 byStudyColorKind, UINT8 byStudyAttrKind, UINT8 byStudyCurLevel);
BOOL CkUnlockHeroGrid(UINT16 wHeroLevel, UINT8 byGridIdx);
UINT32 GetStudyAttrValue(UINT8 byStudyColorKind, UINT8 byStudyAttrKind, UINT8 byStudyLevel);
public:
CAwakenPropMgr();
virtual ~CAwakenPropMgr();
protected:
BOOL LoadBaseFromDB();
BOOL LoadAwakenLevelFromDB();
BOOL LoadUnlockHeroStudyGridFromDB();
BOOL LoadLevel2UnlockAwakenStudyFromDB();
BOOL LoadAwakenStudyAttrFromDB();
private:
SAwakenBaseProp m_stAwakenBaseProp; //基本配置
SAwakenLevelProp m_astAwakenLevelProp[MAX_AWAKEN_LEVEL+1];//悟道等级配置,下标为悟道等级
SAwakenLevelProp m_stRudingGoldAwakenLevelProp; //元宝悟道入定状态悟道配置
SAwakenLevelProp m_stChewuGoldAwakenLevelProp; //元宝悟道彻悟状态悟道配置
UINT32 m_adwAwakenCoin[MAX_AWAKEN_NUM];//悟道所需铜钱
C1616Map m_mapLevel2OpenNumProp; //key为伙伴等级,value为开放的心得格子数
C1616Map m_mapOpenNum2LevelProp; //key为开放的心得格子数, value为解锁的伙伴等级
UINT16 m_awStudyUnlockLevelInfo[MAX_HERO_STUDY_GRID_NUM]; //心得解锁等级信息
UINT16 m_wMaxOpenNumHeroLevel;//最大开放心得格子数的武将等级
CLevel2UnlockStudyColorProMap m_mapLevel2AwakenStudyGenUnlockPropMap; //心得生成概率及解锁配置,key为玩家等级(该等级有的心得则表示已解锁)
CAwakenStudyAttrPropMap m_mapAwakenStudyAttrProp; //心得属性配置,key为byStudyColorKind+byStudyAttrKind+byStudyLevel
};
#endif // #ifndef _AWAKENBASEPROPPROPMGR_H_ |
fb4886d6c8904c4bede8a936504531935e2579fe | dc11b7e4255bf76ac757a4512accfcd5728ee728 | /complex.cpp | 57e04281596a69043c32cb947803e1b5a7fe5218 | [] | no_license | Hostridet/complex | 870d2c22df39d773d73dc40d7b3df5566ea0d4ab | ca727965ea278d465c769ec5c1d43e17307ae016 | refs/heads/main | 2023-02-17T20:50:52.639332 | 2021-01-14T18:26:28 | 2021-01-14T18:26:28 | 329,700,391 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,013 | cpp | complex.cpp | #include "complex.h"
#include <iostream>
#include <cmath>
using namespace std;
Complex operator + (const Complex& a, const Complex& b)
{
Complex result;
result.real = a.real + b.real;
result.imaginary = a.imaginary + b.imaginary;
return result;
}
Complex operator - (const Complex& a, const Complex& b)
{
Complex result;
result.real = a.real - b.real;
result.imaginary = a.imaginary - b.imaginary;
return result;
}
Complex operator * (const Complex& a, const Complex& b)
{
Complex result;
result.real = a.real * b.real - a.imaginary * b.imaginary;
result.imaginary = a.real * b.imaginary + a.imaginary * b.real;
result.real = round(result.real * 100) / 100;
result.imaginary = round(result.imaginary * 100) / 100;
return result;
}
Complex operator / (const Complex& a, const Complex& b)
{
if (b.real != 0 && b.imaginary != 0) {
Complex result;
result.real = (a.real * b.real + a.imaginary * b.imaginary) /
(b.real * b.real + b.imaginary * b.imaginary);
result.imaginary = (b.real * a.imaginary - b.imaginary * a.real) /
(b.real * b.real + b.imaginary * b.imaginary);
result.real = std::round(result.real * 100) / 100;
result.imaginary = std::round(result.imaginary * 100) / 100;
return result;
}
else
throw logic_error("Can`t division by zero");
}
Complex operator << (std::ostream& out, const Complex& a) {
if (a.real == 0 && a.imaginary == 0) {
out << 0;
} else {
if (a.real != 0) {
out << a.real;
if (a.imaginary > 0) {
out << '+';
}
}
if (a.imaginary != 0) {
if (a.imaginary == 1) {
out << 'i';
} else if (a.imaginary == -1) {
out << "-i";
} else {
out << a.imaginary << 'i';
}
}
}
return reinterpret_cast<Complex &&>(out);
}
|
3fb7a84f667d30e568e8396e91a4278292eff09d | 880f7eaab1e8808288e2bf613235e5e933c47af4 | /nre/apps/unittests/tests/RegMngTest.cc | c8d5ab51bdcb574557761d1ecaa0c843ca77e194 | [] | no_license | blitz/NRE | ddfcdad048ed50205d30cce7671e506da02ff676 | 0b6869d808f41ffa3aaaeea50cbbb45ea5b1bb14 | refs/heads/master | 2021-01-18T07:49:58.502808 | 2012-11-02T13:30:50 | 2012-11-02T13:30:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,548 | cc | RegMngTest.cc | /*
* Copyright (C) 2012, Nils Asmussen <nils@os.inf.tu-dresden.de>
* Economic rights: Technische Universitaet Dresden (Germany)
*
* This file is part of NRE (NOVA runtime environment).
*
* NRE is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* NRE is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License version 2 for more details.
*/
#include <mem/RegionManager.h>
#include <util/ScopedPtr.h>
#include "RegMngTest.h"
using namespace nre;
using namespace nre::test;
static void test_regmng();
const TestCase regmng = {
"RegionManager", test_regmng
};
void test_regmng() {
uintptr_t addr1, addr2, addr3;
{
ScopedPtr<RegionManager> rm(new RegionManager());
rm->free(0x100000, 0x3000);
rm->free(0x200000, 0x1000);
rm->free(0x280000, 0x2000);
addr1 = rm->alloc(0x1000);
addr2 = rm->alloc(0x2000);
addr3 = rm->alloc(0x2000);
rm->free(addr1, 0x1000);
rm->free(addr2, 0x2000);
rm->free(addr3, 0x2000);
RegionManager::iterator it = rm->begin();
WVPASSEQ(it->addr, static_cast<uintptr_t>(0x100000));
WVPASSEQ(it->size, static_cast<size_t>(0x3000));
++it;
WVPASSEQ(it->addr, static_cast<uintptr_t>(0x200000));
WVPASSEQ(it->size, static_cast<size_t>(0x1000));
++it;
WVPASSEQ(it->addr, static_cast<uintptr_t>(0x280000));
WVPASSEQ(it->size, static_cast<size_t>(0x2000));
}
{
ScopedPtr<RegionManager> rm(new RegionManager());
rm->free(0x100000, 0x3000);
rm->free(0x200000, 0x1000);
rm->free(0x280000, 0x2000);
addr1 = rm->alloc(0x1000);
addr2 = rm->alloc(0x1000);
addr3 = rm->alloc(0x1000);
rm->free(addr1, 0x1000);
rm->free(addr3, 0x1000);
rm->free(addr2, 0x1000);
RegionManager::iterator it = rm->begin();
WVPASSEQ(it->addr, static_cast<uintptr_t>(0x100000));
WVPASSEQ(it->size, static_cast<size_t>(0x3000));
++it;
WVPASSEQ(it->addr, static_cast<uintptr_t>(0x200000));
WVPASSEQ(it->size, static_cast<size_t>(0x1000));
++it;
WVPASSEQ(it->addr, static_cast<uintptr_t>(0x280000));
WVPASSEQ(it->size, static_cast<size_t>(0x2000));
}
}
|
12fb72ad5771fe3b20bfdad22a9002fe810acd4f | d5dcf4ca3dac2976e99e9fae2bf4e5e45fe94de5 | /rest.hpp | 4cb3cef428c190b3734461389f9ccfb6a1622d89 | [] | no_license | peterdran/pitronome30 | 68267c3945e163139affc4549ed95ba0c491106a | 0695d61147519157eaef61e399c2e07740aec012 | refs/heads/master | 2023-08-07T06:55:57.774448 | 2021-10-10T18:46:27 | 2021-10-10T18:46:27 | 415,427,917 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,106 | hpp | rest.hpp | #include <string>
#include <cpprest/http_listener.h>
using http_listener = web::http::experimental::listener::http_listener;
class rest {
public:
static http_listener make_endpoint(const std::string& path) {
web::uri_builder builder;
builder.set_scheme("http");
builder.set_host("0.0.0.0");
builder.set_port(8080);
builder.set_path(path);
auto listener = http_listener(builder.to_uri());
listener.support(web::http::methods::OPTIONS, allowAll);
return listener;
}
private:
static void allowAll(web::http::http_request msg) {
web::http::http_response response(200);
response.headers().add("Access-Control-Allow-Origin", "*");
response.headers().add("Access-Control-Allow-Methods", "GET, PUT, DELETE");
response.headers().add("Access-Control-Allow-Headers", "Content-Type");
msg.reply(response);
}
private:
rest();
};
|
2366aefc471af07e629d3711b52aafdf828e0984 | 3f89b357ca579858722982c744e98a96ebe2791c | /src/FileSystem/FileFilter.h | 325cb28d4aabdfef2b66f10e6923632e61f91b24 | [] | no_license | jofrantoba/blazingdb-io | 25ca696a0e69a4e7fa1039a870f9495bd69b49cb | 10b552d0db66a7ce52630f7bcf819d4fc7990e20 | refs/heads/master | 2020-06-30T22:52:17.067046 | 2018-11-23T15:32:12 | 2018-11-23T15:32:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,137 | h | FileFilter.h | /*
* FileFilter.h
*
* Created on: Dec 20, 2017
*/
#ifndef _BLAZING_FILE_FILTER_H_
#define _BLAZING_FILE_FILTER_H_
#include <functional>
#include "FileSystem/FileStatus.h"
using FileFilter = std::function< bool (const FileStatus &fileStatus) >;
using FileFilterFunctor = std::unary_function<FileStatus, bool>;
struct FilesFilter : FileFilterFunctor {
bool operator()(const FileStatus &fileStatus) const;
};
struct DirsFilter : FileFilterFunctor {
bool operator()(const FileStatus &fileStatus) const;
};
struct WildcardFilter : FileFilterFunctor {
static bool match(const std::string &input, const std::string &wildcard);
WildcardFilter(const std::string &wildcard);
bool operator()(const FileStatus &fileStatus) const;
std::string wildcard;
};
struct FileTypeWildcardFilter : FileFilterFunctor {
FileTypeWildcardFilter(FileType fileType, const std::string &wildcard);
bool operator()(const FileStatus &fileStatus) const;
FileType fileType;
std::string wildcard;
};
struct FileOrFolderFilter : FileFilterFunctor {
bool operator()(const FileStatus &fileStatus) const;
};
#endif /* _BLAZING_FILE_FILTER_H_ */
|
57e332c03620d986b138e0d66c53fddc00aa5556 | 3c301163c5b3745b296ac0b01026e03e9d17cd7b | /j06_Casts/ex00/Converter.cpp | 1cff1d82cbbbed78b60435bc696b524a50287d31 | [] | no_license | Ngoguey42/piscine_cpp | 572c4994908ebe869669163e8fa89266fe0473a0 | 371c6f6f15e2b84991ec6aa7d5df3293a780bb9a | refs/heads/master | 2016-09-06T19:26:48.226323 | 2015-05-01T18:01:43 | 2015-05-01T18:01:43 | 31,645,174 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 9,465 | cpp | Converter.cpp | // ************************************************************************** //
// //
// ::: :::::::: //
// Converter.cpp :+: :+: :+: //
// +:+ +:+ +:+ //
// By: ngoguey <ngoguey@student.42.fr> +#+ +:+ +#+ //
// +#+#+#+#+#+ +#+ //
// Created: 2015/03/24 08:45:05 by ngoguey #+# #+# //
// Updated: 2015/04/14 18:21:47 by ngoguey ### ########.fr //
// //
// ************************************************************************** //
#include <sstream>
#include <cmath>
#include <limits>
#include <iomanip>
#include <string>
#include "Converter.hpp"
// **************************************** STATICS *** STATICS *** STATICS * //
// ************************* CONSTRUCTORS *** CONSTRUCTORS *** CONSTRUCTORS * //
Converter::Converter(std::string const &str) :
_ref(str),
_asChar(0),
_asInt(0),
_asFloat(0.),
_asDouble(0.),
_mainType(0)
{
this->_mainType = this->detectCharMainType();
if (this->_mainType == 0)
this->_mainType = this->detectIntMainType();
if (this->_mainType == 0)
this->_mainType = this->detectFloatDoubleMainType();
return ;
}
// **************************** DESTRUCTORS *** DESTRUCTORS *** DESTRUCTORS * //
Converter::~Converter()
{
// std::cout << "[Converter]() Dtor called" << std::endl;
return ;
}
// ********************************** OPERATORS *** OPERATORS *** OPERATORS * //
// **************************************** GETTERS *** GETTERS *** GETTERS * //
// **************************************** SETTERS *** SETTERS *** SETTERS * //
// ********************************** FUNCTIONS *** FUNCTIONS *** FUNCTIONS * //
static int convertCharToNumber(char c)
{
if (c >= 'A' && c <= 'F')
return (c - 'A' + 10);
if (c >= 'a' && c <= 'f')
return (c - 'a' + 10);
return (c - '0');
}
int Converter::detectCharMainType()
{
if (this->_ref.length() == 1 && std::isprint(this->_ref[0]))
{
this->_asChar = this->_ref[0];
return (std::isdigit(this->_ref[0]) ? 0 : 1);
}
else if (this->_ref.length() == 2 && this->_ref[0] == '\\' &&
std::strspn(this->_ref.c_str(), "abfnrtv\\\'\"\?") == 2)
{
if (this->_ref == "\\a")
this->_asChar = '\a';
else if (this->_ref == "\\b")
this->_asChar = '\b';
else if (this->_ref == "\\f")
this->_asChar = '\f';
else if (this->_ref == "\\n")
this->_asChar = '\n';
else if (this->_ref == "\\r")
this->_asChar = '\r';
else if (this->_ref == "\\t")
this->_asChar = '\t';
else if (this->_ref == "\\v")
this->_asChar = '\v';
else if (this->_ref == "\\\\")
this->_asChar = '\\';
else if (this->_ref == "\\\'")
this->_asChar = '\'';
else if (this->_ref == "\\\"")
this->_asChar = '\"';
else if (this->_ref == "\\?")
this->_asChar = '\?';
return (2);
}
else if (this->_ref.length() > 1 && this->_ref[0] == '\\')
{
std::string cpy(this->_ref.substr(1));
bool hexa = false;
int nbr = 0;
if (cpy[0] == 'x')
{
hexa = true;
cpy = cpy.substr(1);
if (std::strspn(cpy.c_str(), "0123456789abcdefABCDEF") != cpy.length())
return (0);
}
else if (std::strspn(cpy.c_str(), "01234567") != cpy.length())
return (0);
while (cpy[0] != '\0' && nbr < 1000)
{
nbr = nbr * (hexa ? 16 : 8) + convertCharToNumber(cpy[0]);
cpy = cpy.substr(1);
}
if (nbr > 0x7F)
return (0);
this->_asChar = static_cast<char>(nbr);
if (hexa)
return (4);
return (3);
}
return (0);
}
int Converter::detectIntMainType()
{
int type = 5;
std::string cpy(this->_ref);
int nbr = 0;
int sign = 1;
int multiplier = 10;
int curNbr;
if (cpy[0] == '0')
{
type = 6;
multiplier = 8;
cpy = cpy.substr(1);
if (cpy[0] == 'x')
{
type = 7;
multiplier = 16;
cpy = cpy.substr(1);
}
}
else if (cpy[0] == '-' || cpy[0] == '+')
{
if (cpy[0] == '-')
sign = -1;
cpy = cpy.substr(1);
}
if ((cpy.length() == 0 && type != 6) ||
(type == 6 && std::strspn(cpy.c_str(), "01234567") !=
cpy.length()) ||
(type == 7 && std::strspn(cpy.c_str(), "0123456789abcdefABCDEF") !=
cpy.length()) ||
(type == 5 && std::strspn(cpy.c_str(), "0123456789") !=
cpy.length()))
return (0);
while (cpy[0] != '\0')
{
curNbr = convertCharToNumber(cpy[0]);
if (sign == -1 &&
std::numeric_limits<int>::min() - nbr * multiplier + curNbr > 0)
return (0);
else if (sign == 1 &&
std::numeric_limits<int>::max() - nbr * multiplier - curNbr < 0)
return (0);
nbr = nbr * multiplier + sign * curNbr;
cpy = cpy.substr(1);
}
this->_asInt = nbr;
return (type);
}
int Converter::detectFloatDoubleMainType()
{
int type = 11;
std::string cpy(this->_ref);
if (cpy == "nan"|| cpy == "NAN")
{
this->_asDouble = NAN;
return (10);
}
if (cpy == "nanf"|| cpy == "NANf")
{
this->_asFloat = NAN;
return (8);
}
if (cpy == "+inf"|| cpy == "+INF")
{
this->_asDouble = 1./0.;
return (10);
}
if (cpy == "+inff"|| cpy == "+INFf")
{
this->_asFloat = 1./0.;
return (8);
}
if (cpy == "-inf"|| cpy == "-INF")
{
this->_asDouble = -1./0.;
return (10);
}
if (cpy == "-inff"|| cpy == "-INFf")
{
this->_asFloat = -1./0.;
return (8);
}
if (cpy[cpy.length() - 1] == 'f')
{
type -= 2;
cpy.resize(cpy.length() - 1);
}
if (cpy.find('.') == std::string::npos ||
cpy.find_first_of('.') != cpy.find_last_of('.'))
return (0);
if (cpy.find_first_not_of("0123456789.", 1) != std::string::npos ||
cpy.find_first_not_of("0123456789.+-") != std::string::npos)
return (0);
if (type == 11)
return (detectDouble(cpy));
return (detectFloat(cpy));
}
int Converter::detectFloat(std::string cpy)
{
std::istringstream iss;
iss.str(cpy);
iss.clear();
iss >> this->_asFloat;
if (iss.fail())
return (0);
return (9);
}
int Converter::detectDouble(std::string cpy)
{
std::istringstream iss;
iss.str(cpy);
iss.clear();
iss >> this->_asDouble;
if (iss.fail())
return (0);
return (11);
}
static void printTruc(char c)
{
std::cout << "'";
if (c >= ' ' && c <= '~')
std::cout << c;
else if (c == '\a')
std::cout << "\\a";
else if (c == '\b')
std::cout << "\\b";
else if (c == '\f')
std::cout << "\\f";
else if (c == '\n')
std::cout << "\\n";
else if (c == '\r')
std::cout << "\\r";
else if (c == '\t')
std::cout << "\\t";
else if (c == '\v')
std::cout << "\\v";
else if (c == '\\')
std::cout << "\\\\";
else if (c == '\'')
std::cout << "\\'";
else if (c == '\"')
std::cout << "\\\"";
else if (c == '\?')
std::cout << "\\?";
else
std::cout << '\\' << std::oct << static_cast<int>(c);
std::cout << "'";
return ;
}
void Converter::describeAsChar(void)
{
std::cout << "char: ";
if (this->_mainType == 0 || this->_mainType == 8 || this->_mainType == 10)
std::cout << "impossible";
else if (this->_mainType >= 5)
{
if (this->_mainType == 9)
this->_asInt = static_cast<int>(this->_asFloat);
else if (this->_mainType == 11)
this->_asInt = static_cast<int>(this->_asDouble);
if (this->_asInt >= 0 && this->_asInt <= 0177)
printTruc(static_cast<char>(this->_asInt));
else
std::cout << "impossible";
}
else
printTruc(_asChar);
std::cout << std::endl;
return ;
}
void Converter::describeAsInt(void) const
{
std::cout << "int: ";
if (this->_mainType <= 4 && this->_mainType > 0)
std::cout << static_cast<int>(this->_asChar);
else if (
this->_mainType == 9 &&
this->_asFloat > static_cast<float>(std::numeric_limits<int>::min()) &&
this->_asFloat < static_cast<float>(std::numeric_limits<int>::max()))
std::cout << static_cast<int>(this->_asFloat);
else if (
this->_mainType == 11 &&
this->_asDouble > static_cast<double>(std::numeric_limits<int>::min()) &&
this->_asDouble < static_cast<double>(std::numeric_limits<int>::max()))
std::cout << static_cast<int>(this->_asDouble);
else if (this->_mainType <= 7 && this->_mainType > 0)
std::cout << std::dec << this->_asInt;
else
std::cout << "impossible";
std::cout << std::endl;
return ;
}
void Converter::describeAsFloat(void) const
{
std::cout << "float: ";
std::cout.setf(std::ios_base::showpoint);
if (this->_mainType >= 10)
std::cout << static_cast<float>(this->_asDouble) << 'f';
else if (this->_mainType >= 8)
std::cout << _asFloat << 'f';
else if (this->_mainType >= 5)
std::cout << static_cast<float>(this->_asInt) << 'f';
else if (this->_mainType >= 1)
std::cout << static_cast<float>(this->_asChar) << 'f';
else
std::cout << "impossible";
std::cout << std::endl;
return ;
}
void Converter::describeAsDouble(void) const
{
std::cout << "double: ";
std::cout.setf(std::ios_base::showpoint);
if (this->_mainType >= 10)
std::cout << _asDouble;
else if (this->_mainType >= 8)
std::cout << static_cast<double>(this->_asFloat);
else if (this->_mainType >= 5)
std::cout << static_cast<double>(this->_asInt);
else if (this->_mainType >= 1)
std::cout << static_cast<double>(this->_asChar);
else
std::cout << "impossible";
std::cout << std::endl;
return ;
}
// ******************* NESTED_CLASSES *** NESTED_CLASSES *** NESTED_CLASSES * //
|
e9451a27bdd78a017ef1cd957c8ca41ee986bd35 | 6bf727dcda5b617a7883f7f866afe30bb2bc9ef2 | /src/cpp/include/Mesh.h | 7dad3058a722f7484ffcbc37937307f439dc1d7f | [] | no_license | adam-howlett/DDMRes-2D | 6cfe3c810e3f08958b7a78abe7c942dcb467ee07 | ad22d2b0f8bfbb0167cfde1dfe2b0f621cc41946 | refs/heads/main | 2023-01-24T13:01:18.741397 | 2020-12-07T02:20:02 | 2020-12-07T02:20:02 | 318,888,798 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 728 | h | Mesh.h | #ifndef MESH_H
#define MESH_H
#include "Matrix.h"
class Mesh
{
public:
Mesh();
virtual ~Mesh();
void Peterson(int n);
void dispElements();
void dispVertices();
void Output_Data();
void Refine();
void Vertical_Refine(int n);
//Access Methods
int getConnectivity(int i, int j);
double getVertex(int i, int j);
int getNum_Elements();
int getNum_Vertices();
Vector getNode(int i);
Vector getMidpoint(int i);
protected:
private:
int Num_Elements;
int Num_Vertices;
int triangulation_degree;
Matrix Vertices;
Matrix Connectivity_Array;
};
#endif // MESH_H
|
93f06249240696bc7daaab1a372959dcb07cd261 | fab52219940b76df9a69a33bca34a8481f6184ae | /UVa 10250.cpp | fa24dc5b72781912de351d4cf6df6e83111891a3 | [] | no_license | KimDinh/UVa-Online-Judge-Practice | 1bced3408f33f6190f7cb972d309a9ad38c0bfe2 | b3f40f27cc18a5f6959733db7fd90fe4a2a25135 | refs/heads/master | 2020-04-05T09:01:08.783492 | 2019-08-21T01:41:32 | 2019-08-21T01:41:32 | 156,738,974 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,282 | cpp | UVa 10250.cpp | #include <iostream>
#include <fstream>
#include <cstring>
#include <string>
#include <algorithm>
#include <cmath>
#include <climits>
#include <vector>
#include <map>
#include <unordered_map>
#include <set>
#include <queue>
#include <deque>
#include <unordered_set>
#include <stack>
#include <iomanip>
using namespace std;
#define PI acos(-1.0)
#define EPS 1e-9
double DEG_to_RAD(double d){
return d*PI/180.0;
}
struct point{
double x, y;
point(){}
point(double _x, double _y){
x = _x; y = _y;
}
};
point rotate(point p, double theta){
double rad = DEG_to_RAD(theta);
return point(p.x*cos(rad) - p.y*sin(rad),
p.x*sin(rad) + p.y*cos(rad));
}
int main(){
point p1, p2, p3, p4;
while(!cin.eof()){
cin >> p1.x >> p1.y >> p2.x >> p2.y;
if(fabs(p1.x-p2.x)<EPS && fabs(p1.y-p2.y)<EPS){
cout << "Impossible.\n";
continue;
}
point mid((p1.x+p2.x)/2, (p1.y+p2.y)/2);
p3 = rotate(point(p1.x-mid.x, p1.y-mid.y), 90.0);
p4 = rotate(point(p2.x-mid.x, p2.y-mid.y), 90.0);
cout.precision(10);
cout << fixed;
cout << p3.x+mid.x << " " << p3.y+mid.y << " ";
cout << p4.x+mid.x << " " << p4.y+mid.y << "\n";
}
return 0;
} |
d33e1f513c673f18ddaf7017b8d21ec61312f10c | ebe36eba494b9ab9bb658686e69c9253c43cb524 | /Practice/GeeksForGeeks/Subarray_with_sum_0.cpp | b11df5c69d2fb12da63994568ac8ce7491f26c08 | [] | no_license | Dutta-SD/CC_Codes | 4840d938de2adc5a2051a32b48c49390e6ef877f | ec3652ec92d0d371fd3ce200f393f3f69ed27a68 | refs/heads/main | 2023-07-03T11:46:30.868559 | 2021-08-19T12:03:56 | 2021-08-19T12:03:56 | 316,813,717 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 477 | cpp | Subarray_with_sum_0.cpp | # include <iostream>
# include <unordered_set>
using namespace std;
bool subArrayZeroSum(int arr[], int n){
unordered_set <int> prev_sums;
int sum = 0;
for(int i = 0; i < n; ++i){
sum += arr[i];
if (!sum || prev_sums.find(sum) != prev_sums.end()) return true;
prev_sums.insert(sum);
}
return false;
}
int main(){
int arr[] = {-1, -2, 3, 1, 3, 2};
cout << subArrayZeroSum(arr, sizeof(arr) / sizeof(int));
return 0;
} |
e569aa0c44a01e8e3f970fd8bea9880316c7150b | be1b7883f4284a96cddb3aa2d2ded6c65e4908b6 | /ch5Warmup.cpp | 17c7fccd59d317b2b3ceaca4d1c15514d542b72a | [] | no_license | tccmobile/Fall2018CPP | 084736ecdb9b348495ee2641f97b45aec3e92c36 | 8bd705e4623240d95e65b2916ee8134d5e6c6c6d | refs/heads/master | 2020-03-27T16:01:36.304541 | 2018-12-04T16:16:06 | 2018-12-04T16:16:06 | 146,754,976 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 741 | cpp | ch5Warmup.cpp | //
// Created by T10115885 on 9/25/2018.
//
#include <iostream>
#include <vector>
using namespace std;
int main(){
vector<double> weights(5);
double total = 0, average = 0, max =0;
for (int i = 0; i < weights.size(); ++i) {
cout<<"Enter weight "<<(i+1)<<":"<<endl;
cin>> weights.at(i);
total+=weights.at(i); // total = total + weights.at(i)
if (weights.at(i)>max){
max = weights.at(i);
}
}
cout<<"You entered: ";
for (int j = 0; j < weights.size(); ++j) {
cout<<weights.at(j)<<" ";
}
cout<<endl<<endl;
cout<<"Total weight: "<<total<<endl;
cout<<"Average weight: "<<total/5<<endl;
cout<<"Max weight: "<<max<<endl;
return 0;
}
|
647b982c71883820fdf4a2c91e45dddc8528ce63 | 79e897a9e762282bc5a9795dc8378355dc827f1a | /Module-cpp-03/ex04/ClapTrap.hpp | b8058665441c41b5a95f4b111848c796b71f46ed | [] | no_license | sphaxou/CPP-42 | 37a807c8c3799b93da681bec732ba0b6eab6777d | dee5653046d890737ffec93651696fb326a970aa | refs/heads/master | 2023-01-13T19:40:32.988592 | 2020-11-19T16:28:17 | 2020-11-19T16:28:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,596 | hpp | ClapTrap.hpp | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ClapTrap.hpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: rchallie <rchallie@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/03/15 20:33:03 by rchallie #+# #+# */
/* Updated: 2020/10/12 22:37:53 by rchallie ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef CLAPTRAP_HPP
# define CLAPTRAP_HPP
// LIBS ========================================================================
#include <iostream>
#include <string>
#include <stdlib.h>
#include <time.h>
// =============================================================================
// PROTOTYPES ==================================================================
class ClapTrap;
// =============================================================================
// PROTOTYPES ==================================================================
class ClapTrap
{
protected:
unsigned int _hit_points;
unsigned int _max_hit_points;
unsigned int _energy_points;
unsigned int _max_energy_points;
unsigned int _level;
std::string _name;
unsigned int _melee_attack_damage;
unsigned int _ranged_attack_damage;
unsigned int _armor_damage_reduction;
public:
ClapTrap();
ClapTrap(
unsigned int hit_points,
unsigned int max_hit_points,
unsigned int energy_points,
unsigned int max_energy_points,
unsigned int level,
std::string name,
unsigned int melee_attack_damage,
unsigned int ranged_attack_damage,
unsigned int armor_damage_reduction
);
ClapTrap(const ClapTrap&);
virtual ~ClapTrap();
ClapTrap &operator=(const ClapTrap& op);
unsigned int getHitPoints(void);
unsigned int getMaxHitPoints(void);
unsigned int getEnergyPoints(void);
unsigned int getMaxEnergyPoints(void);
unsigned int getLevel(void);
std::string getName(void);
unsigned int getMeleeAttackDamage(void);
unsigned int getRangedAttackDamage(void);
unsigned int getArmorDamageReduction(void);
void setHitPoints(unsigned int hit_points);
void setMaxHitPoints(unsigned int max_hit_points);
void setEnergyPoints(unsigned int energy_points);
void setMaxEnergyPoints(unsigned int max_energy_points);
void setLevel(unsigned int level);
void setName(std::string name);
void setMeleeAttackDamage(unsigned int melee_attack_damage);
void setRangedAttackDamage(unsigned int ranged_attack_damage);
void setArmorDamageReduction(unsigned int armor_damage_reduction);
void rangedAttack(std::string const & target);
void meleeAttack(std::string const & target);
void takeDamage(unsigned int amount);
void beRepaired(unsigned int amount);
};
// =============================================================================
// FUNCTIONS PROTOYPES =========================================================
void _print_suffix(const std::string& name, unsigned int hp);
// =============================================================================
#endif |
83d416988db71d8626b105e428f1cf84d57d38c9 | 6ed43fd283d29dff95ca3340a9cf94473aeadc4e | /BaekJoon/p_13458 시험 감독.cpp | db33cc3b36173a1fd2bf090c7f569e074c10887c | [] | no_license | codehopper93/algorithm | 5d32e13c647e4afa6cf96a0f745ef004fd84a29e | f650661b78e69c71c0a7d189ca12a87c8c58110a | refs/heads/master | 2021-09-17T15:00:52.772022 | 2018-07-03T04:45:50 | 2018-07-03T04:45:50 | 114,850,686 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 454 | cpp | p_13458 시험 감독.cpp | #include<iostream>
#include<vector>
using namespace std;
int main() {
int N;
int B, C;
long long ans=0;
cin >> N;
vector<int> A(N);
for (int i = 0; i < N; i++) {
cin >> A[i];
}
cin >> B >> C;
for (int i = 0; i < N; i++) {
A[i] -= B;
if (A[i] < 0) {
A[i] = 0;
}
ans++;
}
for (int i = 0; i < N; i++) {
ans += A[i] / C;
if (A[i] % C > 0) {
ans++;
}
}
cout << ans;
return 0;
} |
1c41a7cfb5e7c9465ead8a892d3dc614c6025bc2 | 92c4eb7b4e66e82fda6684d7c98a6a66203d930a | /src/sean/cc/keys.h | 294b241ba16a48d5f58adb0de60903c4eb7a8693 | [] | no_license | grouptheory/SEAN | 5ea2ab3606898d842b36d5c4941a5685cda529d9 | 6aa7d7a81a6f71a5f2a4f52f15d8e50b863f05b4 | refs/heads/master | 2020-03-16T23:15:51.392537 | 2018-05-11T17:49:18 | 2018-05-11T17:49:18 | 133,071,079 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,531 | h | keys.h | // -*- C++ -*-
// +++++++++++++++
// S E A N --- Signalling Entity for ATM Networks ---
// +++++++++++++++
// Version: 1.0.1
//
// Copyright (c) 1998
// Naval Research Laboratory (NRL/CCS)
// and the
// Defense Advanced Research Projects Agency (DARPA)
//
// All Rights Reserved.
//
// Permission to use, copy, and modify this software and its
// documentation is hereby granted, provided that both the copyright notice and
// this permission notice appear in all copies of the software, derivative
// works or modified versions, and any portions thereof, and that both notices
// appear in supporting documentation.
//
// NRL AND DARPA ALLOW FREE USE OF THIS SOFTWARE IN ITS "AS IS" CONDITION AND
// DISCLAIM ANY LIABILITY OF ANY KIND FOR ANY DAMAGES WHATSOEVER RESULTING FROM
// THE USE OF THIS SOFTWARE.
//
// NRL and DARPA request users of this software to return modifications,
// improvements or extensions that they make to:
//
// sean-dev@cmf.nrl.navy.mil
// -or-
// Naval Research Laboratory, Code 5590
// Center for Computation Science
// Washington, D.C. 20375
//
// and grant NRL and DARPA the rights to redistribute these changes in
// future upgrades.
//
// -*- C++ -*-
#ifndef __CCD_KEYS_H__
#define __CCD_KEYS_H__
#ifndef LINT
static char const _ccd_keys_h_rcsid_[] =
"$Id: keys.h,v 1.3 1998/08/18 15:06:00 bilal Exp $";
#endif
class abstract_local_id;
#include <codec/uni_ie/ie_base.h>
//---------------------------------------------------
class appid_and_int {
friend int compare(appid_and_int * const & a, appid_and_int * const & b);
public:
appid_and_int(const abstract_local_id* id, int x);
appid_and_int(const appid_and_int & rhs);
~appid_and_int();
int equals(const appid_and_int & rhs);
int get_int(void) const;
const abstract_local_id * get_id(void) const;
private:
const abstract_local_id * _id;
int _x;
};
//---------------------------------------------------
class setup_attributes {
public:
setup_attributes(InfoElem** iearray, int crv);
~setup_attributes();
friend int compare(setup_attributes *const & a, setup_attributes *const & b);
int score( setup_attributes* incoming_call_attributes );
bool is_distinguishable_from( setup_attributes* incoming_call_attributes );
int crv(void) { return _crv; }
int call_id(void);
int seqnum(void);
private:
InfoElem* _ie[num_ie];
int _crv;
};
#endif
|
5708e4007737a3079b0b036a5e32c3671256e12b | 1b9d5e7e7707d852ac48e008ae3141719ac894c2 | /db_proxy_server/db_proxy_server/handler/Login.h | cfae8e8b3efe3ecbe7d80ffa48cb09f346af6fe1 | [] | no_license | LyslwQ/Iterm01 | f7a011a31cf5bd48d01fc7cdb4130757de44343d | 89747d1f2b3feed46b33462a6413128afc6483b9 | refs/heads/master | 2021-10-24T13:48:23.335503 | 2019-03-26T09:26:53 | 2019-03-26T09:26:53 | 177,750,907 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 362 | h | Login.h |
#ifndef LOGIN_H_
#define LOGIN_H_
#include "../../base/ImPduBase.h"
#include <boost/shared_ptr.hpp>
#include "../../muduo/net/TcpConnection.h"
typedef muduo::net::TcpConnectionPtr TcpConnectionPtr;
namespace DB_PROXY {
void doLogin(CImPdu* pPdu, const TcpConnectionPtr& conn);
};
#endif /* LOGIN_H_ */
|
d58f7d0d8367b33a6b62d1a97a02cfb3ed819ae1 | b8b3913b510c2979b03f755e5981fdbb4406ebad | /剑指offer/032_02-把二叉树打印成多行/src/cpp/032_02-把二叉树打印成多行.cpp | d3230079187dc4813dd3e001cf602090285d2e52 | [] | no_license | Richard-coder/Programming-Practice | ca489d16e0dec70699239c0e4a31d29c6d0b72e9 | ae93a271fc552fcf85c306bd5573533344eae8fb | refs/heads/master | 2021-01-23T02:15:50.288066 | 2019-07-31T02:07:33 | 2019-07-31T02:07:33 | 102,436,144 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,358 | cpp | 032_02-把二叉树打印成多行.cpp | /*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
*/
class Solution {
public:
vector<vector<int> > Print(TreeNode* pRoot) {
vector<vector<int>> res;
if(pRoot==nullptr)
return res;
int currentLevelNum=1;
int nextLevelNum=0;
queue<TreeNode*> nodeQueue;
nodeQueue.push(pRoot);
vector<int> level;
while(!nodeQueue.empty()){
TreeNode* node=nodeQueue.front();
nodeQueue.pop();
currentLevelNum--;
level.push_back(node->val);
if(node->left!=nullptr){
nodeQueue.push(node->left);
nextLevelNum++;
}
if(node->right!=nullptr){
nodeQueue.push(node->right);
nextLevelNum++;
}
if(currentLevelNum==0){
res.push_back(level);
vector<int>().swap(level);
currentLevelNum=nextLevelNum;
nextLevelNum=0;
}
}
return res;
}
}; |
0b358dcd66140cc58ab98b66f3734afd3bba8301 | 80da287d87edcc6eff034d3c14f9c4810e3aabe9 | /source/client/cl_view.hpp | 02e9909ece72376d71e3a6164088701ab473ec74 | [] | no_license | iomeone/vkPhysics | a5bf701499cf41dbe2130ea3de988819976d99c0 | 3df9a648c239476ad1330c235d595cf548c6e2df | refs/heads/master | 2023-02-07T04:44:39.454380 | 2020-12-24T15:03:30 | 2020-12-24T15:03:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 316 | hpp | cl_view.hpp | #pragma once
// View describes not only some aspects of how to render the scene
// But also dictates how the user will be sending input
enum game_view_type_t {
GVT_MENU,
GVT_IN_GAME,
GVT_INVALID
};
void cl_change_view_type(game_view_type_t view_type);
game_view_type_t cl_get_current_game_view_type();
|
c1ad86a2aaeb272e49b1013aec0cce53b76a354a | 822756674e3233619116b4283a85c773431d4f69 | /RCJoy/STM32F407DISC_RC_JOY/PPMGenerator.h | 496fdfaf32039ab682505c538edd49258f2b89cb | [] | no_license | jgilbertfpv/rcjoy | 211517f80d24aacb13a7ead538dc0ee46c6b5e72 | 1cebe2f3302b2778ce78a4fd03e015f7273a90d1 | refs/heads/master | 2020-03-21T04:52:05.178242 | 2016-04-16T13:18:00 | 2016-04-16T13:18:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 374 | h | PPMGenerator.h | #pragma once
#include <stdint.h>
class PPMGenerator
{
private:
public:
PPMGenerator(void);
void init(uint16_t channels);
void start();
void stop();
void setChannels(uint8_t channels);
void setChan(uint16_t chan, uint16_t val);
};
extern PPMGenerator PPMGen;
#ifdef __cplusplus
extern "C"
{
#endif
extern void TIM3_IRQHandler();
#ifdef __cplusplus
}
#endif |
355662c7c9afeccfa32120c84795e945741c7ed6 | 3c91a668c7c3720faf033a3395fac992e9abdee4 | /object/pyString.cpp | eb9027c6f3f541cff7955922906d36ba1f947a99 | [] | no_license | xiaoqixian/Armor | 9d449eff01ebb9ee35ec64b65bcc37459aa63681 | 171f675c60a932920d02720d15f32ff40f9d3b7c | refs/heads/master | 2021-07-14T12:19:11.478333 | 2020-05-12T13:12:13 | 2020-05-12T13:12:13 | 237,584,708 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,310 | cpp | pyString.cpp | #include "object/pyString.hpp"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include "runtime/universe.hpp"
#include "object/pyInteger.hpp"
#include "object/pyDict.hpp"
#include "runtime/functionObject.hpp"
#include <iostream>
using namespace std;
PyObject* string_upper(ObjList args);
StringKlass* StringKlass::instance = NULL;
StringKlass::StringKlass() {
}
void StringKlass::initialize() {
(new TypeObject())->set_own_klass(this);
PyDict* klass_dict = new PyDict();
//klass_dict->put(new PyString)
set_klass_dict(klass_dict);
klass_dict->put(new PyString("upper"),new FunctionObject(string_upper));
set_name(new PyString("str"));
add_super(ObjectKlass::get_instance());
}
StringKlass* StringKlass::get_instance() {
if (instance == NULL) {
instance = new StringKlass();
}
return instance;
}
PyObject* StringKlass::allocate_instance(ArrayList<PyObject*>* args) {
if (!args || args->length() == 0) {
return new PyString("");
}
}
PyString::PyString(const char *x) {
_length = strlen(x);
_value = new char[_length];
strcpy(_value,x);
set_klass(StringKlass::get_instance());
}
PyString::PyString(const char *x, int length) {
_length = length;
_value = new char[_length];
for (int i = 0;i < length;i++) {
_value[i] = x[i];
}
set_klass(StringKlass::get_instance());
}
void StringKlass::print(PyObject* o) {
PyString* so = (PyString*)o;
assert(so && so->klass() == (Klass*)this);
for (int i = 0;i < so->length();i++) {
printf("%c",so->value()[i]);
}
}
PyObject* StringKlass::equal(PyObject* x,PyObject* y) {
if (x->klass() != y->klass()) {
return Universe::pfalse;
}
PyString* sx = (PyString*)x;
PyString* sy = (PyString*)y;
assert(sx && (sx->klass() == (Klass*)this));
assert(sy && (sy->klass() == (Klass*)this));
if (sx->length() != sy->length()) {
return Universe::pfalse;
}
for (int i = 0;i < sx->length();i++) {
if (sx->value()[i] != sy->value()[i]) {
return Universe::pfalse;
}
}
return Universe::ptrue;
}
PyObject* StringKlass::subscr(PyObject* x,PyObject* y) {
assert(x && x->klass() == (Klass*)this);
assert(y && y->klass() == (Klass*)IntegerKlass::get_instance());
PyString* sx = (PyString*)x;
PyInteger* iy = (PyInteger*)y;
return new PyString(&(sx->value()[iy->value()]),1);
}
PyObject* StringKlass::contains(PyObject* x,PyObject* y) {
assert(x && x->klass() == (Klass*)this);
assert(y && y->klass() == (Klass*)this);
PyString* sx = (PyString*)x;
PyString* sy = (PyString*)y;
int xsize = sx->length();
int ysize = sy->length();
bool flag = true;
for (int i = 0;i < xsize - ysize;i++) {
for (int j = 0;j < ysize;j++) {
if (sx->value()[i + j] != sy->value()[j]) {
flag = false;
break;
}
}
if (flag) {
return Universe::ptrue;
}
flag = true;
}
return Universe::pfalse;
}
PyObject* StringKlass::len(PyObject* x) {
return new PyInteger(((PyString*)x)->length());
}
PyObject* StringKlass::slice(PyObject* object,PyObject* x,PyObject* y) {
assert(object && object->klass() == (Klass*)this);
assert(x && x->klass() == IntegerKlass::get_instance());
assert(y && y->klass() == IntegerKlass::get_instance());
PyString* str = (PyString*)object;
PyInteger* ix = (PyInteger*)x;
PyInteger* iy = (PyInteger*)y;
int len = iy->value() - ix->value();
if (len <= 0) {
printf("len <= 0");
return Universe::pNone;
}
char* res = new char[len];
for (int i = ix->value();i < iy->value();i++) {
res[i-ix->value()] = str->value()[i];
}
PyString* s = new PyString(res,len);
delete[] res;
return s;
}
/*PyObject* StringKlass::add(PyObject* x,PyObject* y) {
assert(x && x->klass() == this);
assert(y && y->klass() == this);
PyString* sx = (PyString*)x;
PyString* sy = (PyString*)y;
}*/
/*PyObject* PyString::add(PyObject* x) {
const int new_len = _length + ((PyString*)x)->length();
const char* new_str = new char[new_len];
return new PyString(new_str);
}*/
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.