blob_id stringlengths 40 40 | language stringclasses 1
value | repo_name stringlengths 5 117 | path stringlengths 3 268 | src_encoding stringclasses 34
values | length_bytes int64 6 4.23M | score float64 2.52 5.19 | int_score int64 3 5 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | text stringlengths 13 4.23M | download_success bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
dc0add341acad2cd7f0f777b9ec98b23b14c1a99 | C++ | as99if/Algorithm | /C++/02. queue enqueue dequeue using array.cpp | UTF-8 | 1,304 | 3.53125 | 4 | [] | no_license | #include<iostream>
using namespace std;
#define size 4
int a[size+1] ;
int f=0, r=0;
void display(){
int i, s;
cout<<"\nArray : ";
if(f==r){
cout<<"Queue is empty"<<endl;
}
if(f!=r){
for(i=f; i<r; i=s){
s=(i+1)%(size+1);
cout<<a[s]<<" ";
}
}
}
void show_menu(){
cout<<"\n1. Insert \n2. Delete \n3. Exit"<<endl;
}
void enqueue(int item){
int s;
s=(r+1)%(size+1);
if(s==f)
cout<<"Queue is full"<<endl;
else{
a[s]=item;
r=s;
}
}
void dequeue(){
int s;
s=(f+1)%(size+1);
if(f==r){
cout<<"Queue is empty"<<endl;
}
else{
a[s]=0;
f=s;
}
}
int main(){
int i=1, choice, item;
do{
show_menu();
cin>>choice;
if(choice==1){
cout<<"Value : ";
cin>>item;
enqueue(item);
display();
}
else if(choice==2){
dequeue();
display();
}
else if(choice=3){
i=-1;
}
else{
cout<<"Wrong Choice"<<endl;
}
}while(i==1);
return 0;
}
| true |
51e17841c82f7134b8f3d91510a209bb58d2d395 | C++ | gyunderscorebe/ActionFPS-Game | /source/src/command.cpp | UTF-8 | 63,002 | 2.640625 | 3 | [
"BSD-3-Clause",
"Cube",
"Zlib"
] | permissive | // command.cpp: implements the parsing and execution of a tiny script language which
// is largely backwards compatible with the quake console language.
#include "cube.h"
bool allowidentaccess(ident *id);
char *exchangestr(char *o, const char *n) { delete[] o; return newstring(n); }
void scripterr();
vector<int> contextstack;
bool contextsealed = false;
bool contextisolated[IEXC_NUM] = { false };
int execcontext;
char *commandret = NULL;
bool loop_break = false, loop_skip = false; // break or continue (skip) current loop
int loop_level = 0; // avoid bad calls of break & continue
hashtable<const char *, ident> *idents = NULL; // contains ALL vars/commands/aliases
VAR(persistidents, 0, 1, 1);
bool per_idents = true, neverpersist = false;
COMMANDF(per_idents, "i", (int *on) {
per_idents = neverpersist ? false : (*on != 0);
});
void clearstack(ident &id)
{
identstack *stack = id.stack;
while(stack)
{
delete[] stack->action;
identstack *tmp = stack;
stack = stack->next;
delete tmp;
}
id.stack = NULL;
}
void pushident(ident &id, char *val, int context = execcontext)
{
if(id.type != ID_ALIAS) { delete[] val; return; }
identstack *stack = new identstack;
stack->action = id.executing==id.action ? newstring(id.action) : id.action;
stack->context = id.context;
stack->next = id.stack;
id.stack = stack;
id.action = val;
id.context = context;
}
void popident(ident &id)
{
if(id.type != ID_ALIAS || !id.stack) return;
if(id.action != id.executing) delete[] id.action;
identstack *stack = id.stack;
id.action = stack->action;
id.stack = stack->next;
id.context = stack->context;
delete stack;
}
ident *newident(const char *name, int context = execcontext)
{
ident *id = idents->access(name);
if(!id)
{
ident init(ID_ALIAS, newstring(name), newstring(""), per_idents, context);
id = &idents->access(init.name, init);
}
return id;
}
void pusha(const char *name, char *action)
{
ident *id = newident(name, execcontext);
if(contextisolated[execcontext] && execcontext > id->context)
{
conoutf("cannot redefine alias %s in this execution context", id->name);
scripterr();
return;
}
pushident(*id, action);
}
void push(const char *name, const char *action)
{
pusha(name, newstring(action));
}
void pop(const char *name)
{
ident *id = idents->access(name);
if(!id) return;
if(contextisolated[execcontext] && execcontext > id->context)
{
conoutf("cannot redefine alias %s in this execution context", id->name);
scripterr();
return;
}
popident(*id);
}
COMMAND(push, "ss");
COMMANDF(pop, "v", (char **args, int numargs)
{
if(numargs > 0)
{
const char *beforepopval = getalias(args[0]);
if(beforepopval) commandret = newstring(beforepopval);
}
loopi(numargs) pop(args[i]);
});
void delalias(const char *name)
{
ident *id = idents->access(name);
if(!id || id->type != ID_ALIAS) return;
if(contextisolated[execcontext] && execcontext > id->context)
{
conoutf("cannot remove alias %s in this execution context", id->name);
scripterr();
return;
}
idents->remove(name);
}
COMMAND(delalias, "s");
void alias(const char *name, const char *action, bool temp, bool constant)
{
ident *b = idents->access(name);
if(!b)
{
ident b(ID_ALIAS, newstring(name), newstring(action), persistidents && !constant && !temp, execcontext);
b.isconst = constant;
b.istemp = temp;
idents->access(b.name, b);
return;
}
else if(b->type==ID_ALIAS)
{
if(contextisolated[execcontext] && execcontext > b->context)
{
conoutf("cannot redefine alias %s in this execution context", b->name);
scripterr();
return;
}
if(b->isconst)
{
conoutf("alias %s is a constant and cannot be redefined", b->name);
scripterr();
return;
}
b->isconst = constant;
if(temp) b->istemp = true;
if(!constant || (action && action[0]))
{
if(b->action!=b->executing) delete[] b->action;
b->action = newstring(action);
b->persist = persistidents != 0;
}
if(b->istemp) b->persist = false;
}
else
{
conoutf("cannot redefine builtin %s with an alias", name);
scripterr();
}
}
COMMANDF(alias, "ss", (const char *name, const char *action) { alias(name, action, false, false); });
COMMANDF(tempalias, "ss", (const char *name, const char *action) { alias(name, action, true, false); });
COMMANDF(const, "ss", (const char *name, const char *action) { alias(name, action, false, true); });
COMMANDF(checkalias, "s", (const char *name) { intret(getalias(name) ? 1 : 0); });
COMMANDF(isconst, "s", (const char *name) { ident *id = idents->access(name); intret(id && id->isconst ? 1 : 0); });
// variable's and commands are registered through globals, see cube.h
int variable(const char *name, int minval, int cur, int maxval, int *storage, void (*fun)(), bool persist)
{
if(!idents) idents = new hashtable<const char *, ident>;
ident v(ID_VAR, name, minval, maxval, storage, cur, fun, persist, IEXC_CORE);
idents->access(name, v);
return cur;
}
float fvariable(const char *name, float minval, float cur, float maxval, float *storage, void (*fun)(), bool persist)
{
if(!idents) idents = new hashtable<const char *, ident>;
ident v(ID_FVAR, name, minval, maxval, storage, cur, fun, persist, IEXC_CORE);
idents->access(name, v);
return cur;
}
char *svariable(const char *name, const char *cur, char **storage, void (*fun)(), void (*getfun)(), bool persist)
{
if(!idents) idents = new hashtable<const char *, ident>;
ident v(ID_SVAR, name, storage, fun, getfun, persist, IEXC_CORE);
idents->access(name, v);
return newstring(cur);
}
#define _GETVAR(id, vartype, name, retval) \
ident *id = idents->access(name); \
ASSERT(id && id->type == vartype); \
if(!id || id->type!=vartype) return retval;
#define GETVAR(id, name, retval) _GETVAR(id, ID_VAR, name, retval)
void setvar(const char *name, int i, bool dofunc)
{
GETVAR(id, name, );
*id->storage.i = clamp(i, id->minval, id->maxval);
if(dofunc && id->fun) ((void (__cdecl *)())id->fun)(); // call trigger function if available
}
void setfvar(const char *name, float f, bool dofunc)
{
_GETVAR(id, ID_FVAR, name, );
*id->storage.f = clamp(f, id->minvalf, id->maxvalf);
if(dofunc && id->fun) ((void (__cdecl *)())id->fun)(); // call trigger function if available
}
void setsvar(const char *name, const char *str, bool dofunc)
{
_GETVAR(id, ID_SVAR, name, );
*id->storage.s = exchangestr(*id->storage.s, str);
if(dofunc && id->fun) ((void (__cdecl *)())id->fun)(); // call trigger function if available
}
void modifyvar(const char *name, int arg, char op)
{
ident *id = idents->access(name);
if(!id) return;
if(!allowidentaccess(id))
{
conoutf("not allowed in this execution context: %s", id->name);
scripterr();
return;
}
if((id->type == ID_VAR && id->minval > id->maxval) || (id->type == ID_FVAR && id->minvalf > id->maxvalf)) { conoutf("variable %s is read-only", id->name); return; }
int val = 0;
switch(id->type)
{
case ID_VAR: val = *id->storage.i; break;
case ID_FVAR: val = int(*id->storage.f); break;
case ID_SVAR: { { if(id->getfun) ((void (__cdecl *)())id->getfun)(); } val = ATOI(*id->storage.s); break; }
case ID_ALIAS: val = ATOI(id->action); break;
}
switch(op)
{
case '+': val += arg; break;
case '-': val -= arg; break;
case '*': val *= arg; break;
case '/': val = arg ? val/arg : 0; break;
}
switch(id->type)
{
case ID_VAR: *id->storage.i = clamp(val, id->minval, id->maxval); break;
case ID_FVAR: *id->storage.f = clamp((float)val, id->minvalf, id->maxvalf); break;
case ID_SVAR: { string str; itoa(str, val); *id->storage.s = exchangestr(*id->storage.s, str); break; }
case ID_ALIAS: { string str; itoa(str, val); alias(name, str); return; }
default: return;
}
if(id->fun) ((void (__cdecl *)())id->fun)();
}
void modifyfvar(const char *name, float arg, char op)
{
ident *id = idents->access(name);
if(!id) return;
if(!allowidentaccess(id))
{
conoutf("not allowed in this execution context: %s", id->name);
scripterr();
return;
}
if((id->type == ID_VAR && id->minval > id->maxval) || (id->type == ID_FVAR && id->minvalf > id->maxvalf)) { conoutf("variable %s is read-only", id->name); return; }
float val = 0;
switch(id->type)
{
case ID_VAR: val = *id->storage.i; break;
case ID_FVAR: val = *id->storage.f; break;
case ID_SVAR: { { if(id->getfun) ((void (__cdecl *)())id->getfun)(); } val = atof(*id->storage.s); break; }
case ID_ALIAS: val = atof(id->action); break;
}
switch(op)
{
case '+': val += arg; break;
case '-': val -= arg; break;
case '*': val *= arg; break;
case '/': val = (arg == 0.0f) ? 0 : val/arg; break;
}
switch(id->type)
{
case ID_VAR: *id->storage.i = clamp((int)val, id->minval, id->maxval); break;
case ID_FVAR: *id->storage.f = clamp(val, id->minvalf, id->maxvalf); break;
case ID_SVAR: *id->storage.s = exchangestr(*id->storage.s, floatstr(val)); break;
case ID_ALIAS: alias(name, floatstr(val)); return;
default: return;
}
if(id->fun) ((void (__cdecl *)())id->fun)();
}
void addeq(char *name, int *arg) { modifyvar(name, *arg, '+'); }
void subeq(char *name, int *arg) { modifyvar(name, *arg, '-'); }
void muleq(char *name, int *arg) { modifyvar(name, *arg, '*'); }
void diveq(char *name, int *arg) { modifyvar(name, *arg, '/'); }
void addeqf(char *name, float *arg) { modifyfvar(name, *arg, '+'); }
void subeqf(char *name, float *arg) { modifyfvar(name, *arg, '-'); }
void muleqf(char *name, float *arg) { modifyfvar(name, *arg, '*'); }
void diveqf(char *name, float *arg) { modifyfvar(name, *arg, '/'); }
COMMANDN(+=, addeq, "si");
COMMANDN(-=, subeq, "si");
COMMANDN(*=, muleq, "si");
COMMANDN(div=, diveq, "si");
COMMANDN(+=f, addeqf, "sf");
COMMANDN(-=f, subeqf, "sf");
COMMANDN(*=f, muleqf, "sf");
COMMANDN(div=f, diveqf, "sf");
int getvar(const char *name)
{
GETVAR(id, name, 0);
return *id->storage.i;
}
bool identexists(const char *name) { return idents->access(name)!=NULL; }
const char *getalias(const char *name)
{
ident *i = idents->access(name);
return i && i->type==ID_ALIAS ? i->action : NULL;
}
void _getalias(char *name)
{
string o;
ident *id = idents->access(name);
const char *action = getalias(name);
if(id)
{
switch(id->type)
{
case ID_VAR:
formatstring(o)("%d", *id->storage.i);
result(o);
break;
case ID_FVAR:
formatstring(o)("%.3f", *id->storage.f);
result(o);
break;
case ID_SVAR:
if(id->getfun) ((void (__cdecl *)())id->getfun)();
formatstring(o)("%s", *id->storage.s);
result(o);
break;
case ID_ALIAS:
result(action ? action : "");
break;
default: break;
}
}
}
COMMANDN(getalias, _getalias, "s");
#ifndef STANDALONE
void getvarrange(char *_what, char *name)
{
ident *id = idents->access(name);
const char *attrs[] = { "min", "max", "default", "" };
int what = getlistindex(_what, attrs, false, -1);
if(id)
{
int *i = NULL;
switch(what)
{
case 0: i = &(id->minval); break;
case 1: i = &(id->maxval); break;
case 2: i = &(id->defaultval); break;
}
if(i) switch(id->type)
{
case ID_VAR: intret(*i); return;
case ID_FVAR: floatret(*((float *) i), true); return;
}
}
result("");
}
COMMAND(getvarrange, "ss");
#endif
COMMANDF(isIdent, "s", (char *name) { intret(identexists(name) ? 1 : 0); });
bool addcommand(const char *name, void (*fun)(), const char *sig)
{
if(!idents) idents = new hashtable<const char *, ident>;
ident c(ID_COMMAND, name, fun, sig, IEXC_CORE);
idents->access(name, c);
return false;
}
char *parseexp(const char *&p, int right) // parse any nested set of () or []
{
int left = *p++;
const char *word = p;
bool quot = false;
for(int brak = 1; brak; )
{
int c = *p++;
if(c==left && !quot) brak++;
else if(c=='"') quot = !quot;
else if(c==right && !quot) brak--;
else if(!c)
{
p--;
conoutf("missing \"%c\"", right);
scripterr();
return NULL;
}
}
char *s = newstring(word, p-word-1);
if(left=='(')
{
char *ret = executeret(s); // evaluate () exps directly, and substitute result
delete[] s;
s = ret ? ret : newstring("");
}
return s;
}
char *lookup(char *n) // find value of ident referenced with $ in exp
{
if(n[1] == '$') // nested ("$$var")
{
char *nn = lookup(newstring(n + 1));
delete[] n;
int nnl = strlen(nn);
n = newstring(nnl + 1);
n[0] = '$';
copystring(n + 1, nn, nnl + 1);
delete[] nn;
}
ident *id = idents->access(n+1);
if(id) switch(id->type)
{
case ID_VAR: { string t; itoa(t, *id->storage.i); return exchangestr(n, t); }
case ID_FVAR: return exchangestr(n, floatstr(*id->storage.f));
case ID_SVAR: { { if(id->getfun) ((void (__cdecl *)())id->getfun)(); } return exchangestr(n, *id->storage.s); }
case ID_ALIAS: return exchangestr(n, id->action);
}
conoutf("unknown alias lookup: %s", n+1);
scripterr();
return n;
}
char *parseword(const char *&p, int arg, int &infix) // parse single argument, including expressions
{
p += strspn(p, " \t\r");
if(p[0]=='/' && p[1]=='/') p += strcspn(p, "\n\0");
if(*p=='\"')
{
const char *word = p + 1;
do
{
p++;
p += strcspn(p, "\"\n\r");
}
while(*p == '\"' && p[-1] == '\\'); // skip escaped quotes
char *s = newstring(word, p - word);
if(*p=='\"') p++;
#ifndef STANDALONE
filterrichtext(s, s, strlen(s));
#endif
return s;
}
if(*p=='(') return parseexp(p, ')');
if(*p=='[') return parseexp(p, ']');
const char *word = p;
p += strcspn(p, "; \t\r\n\0");
if(p-word==0) return NULL;
if(arg==1 && p-word==1) switch(*word)
{
case '=': infix = *word; break;
}
char *s = newstring(word, p-word);
if(*s=='$') return lookup(s);
return s;
}
char *conc(const char **w, int n, bool space)
{
if(n < 0)
{ // auto-determine number of strings
n = 0;
while(w[n] && w[n][0]) n++;
}
int len = space ? max(n-1, 0) : 0;
loopj(n) len += (int)strlen(w[j]);
char *r = newstring("", len);
loopi(n)
{
strcat(r, w[i]); // make string-list out of all arguments
if(i==n-1) break;
bool col = w[i][0] == '\f' && w[i][1] && w[i][2] == '\0';
if(space && !col) strcat(r, " ");
}
return r;
}
VARN(numargs, _numargs, 25, 0, 0);
void intret(int v)
{
string t;
itoa(t, v);
commandret = newstring(t);
}
const char *floatstr(float v, bool neat)
{
static string s;
static int i = 0;
if(i > MAXSTRLEN - 100) i = 0;
char *t = s + i;
sprintf(t, !neat && (v) == int(v) ? "%.1f" : "%.7g", v); // was ftoa()
i += strlen(t) + 1;
return t;
}
void floatret(float v, bool neat)
{
commandret = newstring(floatstr(v, neat));
}
void result(const char *s) { commandret = newstring(s); }
#if 0
// seer : script evaluation excessive recursion
static int seer_count = 0; // count calls to executeret, check time every n1 (100) calls
static int seer_index = -1; // position in timestamp vector
vector<long long> seer_t1; // timestamp of last n2 (10) level-1 calls
vector<long long> seer_t2; // timestamp of last n3 (10) level-2 calls
#endif
char *executeret(const char *p) // all evaluation happens here, recursively
{
if(!p || !p[0]) return NULL;
bool noproblem = true;
#if 0
if(execcontext>IEXC_CFG) // only PROMPT and MAP-CFG are checked for this, fooling with core/cfg at your own risk!
{
seer_count++;
if(seer_count>=100)
{
seer_index = (seer_index+1)%10;
long long cts = (long long) time(NULL);
if(seer_t1.length()>=10) seer_t1[seer_index] = cts;
seer_t1.add(cts);
int lc = (seer_index+11)%10;
if(lc<=seer_t1.length())
{
int dt = seer_t1[seer_index] - seer_t1[lc];
if(abs(dt)<2)
{
conoutf("SCRIPT EXECUTION warning [%d:%s]", &p, p);
seer_t2.add(seer_t1[seer_index]);
if(seer_t2.length() >= 10)
{
if(seer_t2[0] == seer_t2.last())
{
conoutf("SCRIPT EXECUTION in danger of crashing the client - dropping script [%s].", p);
noproblem = false;
seer_t2.shrink(0);
seer_t1.shrink(0);
seer_index = 0;
}
}
}
}
seer_count = 0;
}
}
#endif
const int MAXWORDS = 25; // limit, remove
char *w[MAXWORDS], emptychar = '\0';
char *retval = NULL;
#define setretval(v) { char *rv = v; if(rv) retval = rv; }
if(noproblem) // if the "seer"-algorithm doesn't object
{
for(bool cont = true; cont;) // for each ; seperated statement
{
if(loop_level && loop_skip) break;
int numargs = MAXWORDS, infix = 0;
loopi(MAXWORDS) // collect all argument values
{
w[i] = &emptychar;
if(i>numargs) continue;
char *s = parseword(p, i, infix); // parse and evaluate exps
if(s) w[i] = s;
else numargs = i;
}
p += strcspn(p, ";\n\0");
cont = *p++!=0; // more statements if this isn't the end of the string
const char *c = w[0];
if(!*c) continue; // empty statement
DELETEA(retval);
if(infix)
{
switch(infix)
{
case '=':
DELETEA(w[1]);
_swap(w[0], w[1]);
c = "alias";
break;
}
}
ident *id = idents->access(c);
if(!id)
{
if(!isdigit(*c) && ((*c!='+' && *c!='-' && *c!='.') || !isdigit(c[1])))
{
conoutf("unknown command: %s", c);
scripterr();
}
setretval(newstring(c));
}
else if(!allowidentaccess(id))
{
conoutf("not allowed in this execution context: %s", id->name);
scripterr();
}
else
{
switch(id->type)
{
case ID_COMMAND: // game defined commands
{
if(strstr(id->sig, "v")) ((void (__cdecl *)(char **, int))id->fun)(&w[1], numargs-1);
else if(strstr(id->sig, "c") || strstr(id->sig, "w"))
{
char *r = conc((const char **)w+1, numargs-1, strstr(id->sig, "c") != NULL);
((void (__cdecl *)(char *))id->fun)(r);
delete[] r;
}
else if(strstr(id->sig, "d"))
{
#ifndef STANDALONE
((void (__cdecl *)(bool))id->fun)(addreleaseaction(id->name)!=NULL);
#endif
}
else
{
int ib1, ib2, ib3, ib4, ib5, ib6, ib7, ib8;
float fb1, fb2, fb3, fb4, fb5, fb6, fb7, fb8;
#define ARG(i) (id->sig[i-1] == 'i' ? ((void *)&(ib##i=strtol(w[i], NULL, 0))) : (id->sig[i-1] == 'f' ? ((void *)&(fb##i=atof(w[i]))) : (void *)w[i]))
switch(strlen(id->sig)) // use very ad-hoc function signature, and just call it
{
case 0: ((void (__cdecl *)())id->fun)(); break;
case 1: ((void (__cdecl *)(void*))id->fun)(ARG(1)); break;
case 2: ((void (__cdecl *)(void*, void*))id->fun)(ARG(1), ARG(2)); break;
case 3: ((void (__cdecl *)(void*, void*, void*))id->fun)(ARG(1), ARG(2), ARG(3)); break;
case 4: ((void (__cdecl *)(void*, void*, void*, void*))id->fun)(ARG(1), ARG(2), ARG(3), ARG(4)); break;
case 5: ((void (__cdecl *)(void*, void*, void*, void*, void*))id->fun)(ARG(1), ARG(2), ARG(3), ARG(4), ARG(5)); break;
case 6: ((void (__cdecl *)(void*, void*, void*, void*, void*, void*))id->fun)(ARG(1), ARG(2), ARG(3), ARG(4), ARG(5), ARG(6)); break;
case 7: ((void (__cdecl *)(void*, void*, void*, void*, void*, void*, void*))id->fun)(ARG(1), ARG(2), ARG(3), ARG(4), ARG(5), ARG(6), ARG(7)); break;
case 8: ((void (__cdecl *)(void*, void*, void*, void*, void*, void*, void*, void*))id->fun)(ARG(1), ARG(2), ARG(3), ARG(4), ARG(5), ARG(6), ARG(7), ARG(8)); break;
default: fatal("command %s has too many arguments (signature: %s)", id->name, id->sig); break;
}
#undef ARG
}
setretval(commandret);
commandret = NULL;
break;
}
case ID_VAR: // game defined variables
if(!w[1][0]) conoutf("%s = %d", c, *id->storage.i); // var with no value just prints its current value
else if(id->minval>id->maxval) conoutf("variable %s is read-only", id->name);
else
{
int i1 = ATOI(w[1]);
if(i1<id->minval || i1>id->maxval)
{
i1 = i1<id->minval ? id->minval : id->maxval; // clamp to valid range
conoutf("valid range for %s is %d..%d", id->name, id->minval, id->maxval);
}
*id->storage.i = i1;
if(id->fun) ((void (__cdecl *)())id->fun)(); // call trigger function if available
}
break;
case ID_FVAR: // game defined variables
if(!w[1][0]) conoutf("%s = %s", c, floatstr(*id->storage.f)); // var with no value just prints its current value
else if(id->minvalf>id->maxvalf) conoutf("variable %s is read-only", id->name);
else
{
float f1 = atof(w[1]);
if(f1<id->minvalf || f1>id->maxvalf)
{
f1 = f1<id->minvalf ? id->minvalf : id->maxvalf; // clamp to valid range
conoutf("valid range for %s is %s..%s", id->name, floatstr(id->minvalf), floatstr(id->maxvalf));
//scripterr(); // Why throw this error here when it's not done for ID_VAR above? Only difference is datatype, both are "valid range errors". // Bukz 2011june04
}
*id->storage.f = f1;
if(id->fun) ((void (__cdecl *)())id->fun)(); // call trigger function if available
}
break;
case ID_SVAR: // game defined variables
if(!w[1][0])
{
if(id->getfun) ((void (__cdecl *)())id->getfun)();
conoutf(strchr(*id->storage.s, '"') ? "%s = [%s]" : "%s = \"%s\"", c, *id->storage.s); // var with no value just prints its current value
}
else
{
*id->storage.s = exchangestr(*id->storage.s, newstring(w[1]));
if(id->fun) ((void (__cdecl *)())id->fun)(); // call trigger function if available
}
break;
case ID_ALIAS: // alias, also used as functions and (global) variables
delete[] w[0];
static vector<ident *> argids;
for(int i = 1; i<numargs; i++)
{
if(i > argids.length())
{
defformatstring(argname)("arg%d", i);
argids.add(newident(argname, IEXC_CORE));
}
pushident(*argids[i-1], w[i]); // set any arguments as (global) arg values so functions can access them
}
int old_numargs = _numargs;
_numargs = numargs-1;
char *wasexecuting = id->executing;
id->executing = id->action;
setretval(executeret(id->action));
if(id->executing!=id->action && id->executing!=wasexecuting) delete[] id->executing;
id->executing = wasexecuting;
_numargs = old_numargs;
for(int i = 1; i<numargs; i++) popident(*argids[i-1]);
continue;
}
}
loopj(numargs) if(w[j]) delete[] w[j];
}
}
return retval;
}
int execute(const char *p)
{
char *ret = executeret(p);
int i = 0;
if(ret) { i = ATOI(ret); delete[] ret; }
return i;
}
#ifndef STANDALONE
bool exechook(int context, const char *ident, const char *body,...) // execute cubescript hook if available and allowed in current context/gamemode
{ // always use one of HOOK_SP_MP, HOOK_SP or HOOK_MP and then OR them (as needed) with HOOK_TEAM, HOOK_NOTEAM, HOOK_BOTMODE, HOOK_FLAGMODE, HOOK_ARENA
if(multiplayer(NULL) && (context & HOOK_FLAGMASK) != HOOK_MP && (context & HOOK_FLAGMASK) != HOOK_SP_MP) return false; // hook is singleplayer-only
if(((context & HOOK_TEAM) && !m_teammode) ||
((context & HOOK_NOTEAM) && m_teammode) ||
((context & HOOK_BOTMODE) && !m_botmode) ||
((context & HOOK_FLAGMODE) && m_flags) ||
((context & HOOK_ARENA) && m_arena)) return false; // wrong gamemode
if(identexists(ident))
{
defvformatstring(arglist, body, body);
defformatstring(execbody)("%s%c%s", ident, *arglist ? ' ' : '\0', arglist);
execute(execbody);
return true;
}
return false;
}
// tab-completion of all idents
// always works at the end of the command line - the cursor position does not matter
static int completesize = -1, nickcompletesize = -1;
void resetcomplete()
{
nickcompletesize = completesize = -1;
}
bool nickcomplete(char *s, bool reversedirection)
{
static int nickcompleteidx;
if(!players.length()) return false;
char *cp = strrchr(s, ' '); // find last space
cp = cp ? cp + 1 : s;
if(nickcompletesize < 0)
{
nickcompletesize = (int)strlen(cp);
nickcompleteidx = reversedirection ? 0 : -1;
}
vector<int> matchingnames;
loopv(players) if(players[i] && !strncasecmp(players[i]->name, cp, nickcompletesize)) matchingnames.add(i); // find all matching player names first
if(matchingnames.length())
{
nickcompleteidx += reversedirection ? matchingnames.length() - 1 : 1;
nickcompleteidx %= matchingnames.length();
const char *fillin = players[matchingnames[nickcompleteidx]]->name;
if(*fillin == '/' && cp == s) *cp++ = ' ';
*cp = '\0';
concatstring(s, fillin);
return true;
}
return false;
}
enum { COMPLETE_FILE = 0, COMPLETE_LIST, COMPLETE_NICK };
struct completekey
{
int type;
const char *dir, *ext;
completekey() {}
completekey(int type, const char *dir, const char *ext) : type(type), dir(dir), ext(ext) {}
};
struct completeval
{
int type;
char *dir, *ext;
vector<char *> dirlist;
vector<char *> list;
completeval(int type, const char *dir, const char *ext) : type(type), dir(dir && dir[0] ? newstring(dir) : NULL), ext(ext && ext[0] ? newstring(ext) : NULL) {}
~completeval() { DELETEA(dir); DELETEA(ext); dirlist.deletearrays(); list.deletearrays(); }
};
static inline bool htcmp(const completekey &x, const completekey &y)
{
return x.type==y.type && (x.dir == y.dir || (x.dir && y.dir && !strcmp(x.dir, y.dir))) && (x.ext == y.ext || (x.ext && y.ext && !strcmp(x.ext, y.ext)));
}
static inline uint hthash(const completekey &k)
{
return k.dir ? hthash(k.dir) + k.type : k.type;
}
static hashtable<completekey, completeval *> completedata;
static hashtable<char *, completeval *> completions;
void addcomplete(char *command, int type, char *dir, char *ext)
{
if(type==COMPLETE_FILE)
{
int dirlen = (int)strlen(dir);
while(dirlen > 0 && (dir[dirlen-1] == '/' || dir[dirlen-1] == '\\'))
dir[--dirlen] = '\0';
if(ext)
{
if(strchr(ext, '*')) ext[0] = '\0';
if(!ext[0]) ext = NULL;
}
}
completekey key(type, dir, ext);
completeval **val = completedata.access(key);
if(!val)
{
completeval *f = new completeval(type, dir, ext);
if(type==COMPLETE_LIST) explodelist(dir, f->list);
if(type==COMPLETE_FILE)
{
explodelist(dir, f->dirlist);
loopv(f->dirlist)
{
char *dir = f->dirlist[i];
int dirlen = (int)strlen(dir);
while(dirlen > 0 && (dir[dirlen-1] == '/' || dir[dirlen-1] == '\\'))
dir[--dirlen] = '\0';
}
}
val = &completedata[completekey(type, f->dir, f->ext)];
*val = f;
}
completeval **hascomplete = completions.access(command);
if(hascomplete) *hascomplete = *val;
else completions[newstring(command)] = *val;
}
void addfilecomplete(char *command, char *dir, char *ext)
{
addcomplete(command, COMPLETE_FILE, dir, ext);
}
void addlistcomplete(char *command, char *list)
{
addcomplete(command, COMPLETE_LIST, list, NULL);
}
void addnickcomplete(char *command)
{
addcomplete(command, COMPLETE_NICK, NULL, NULL);
}
COMMANDN(complete, addfilecomplete, "sss");
COMMANDN(listcomplete, addlistcomplete, "ss");
COMMANDN(nickcomplete, addnickcomplete, "s");
void commandcomplete(char *s, bool reversedirection)
{ // s is required to be of size "string"!
static int completeidx;
if(*s != '/')
{
string t;
copystring(t, s);
copystring(s, "/");
concatstring(s, t);
}
if(!s[1]) return;
// find start position of last command
char *cmd = strrchr(s, ';'); // find last ';' (this will not always work properly, because it doesn't take quoted texts into account)
if(!cmd) cmd = s; // no ';' found: command starts after '/'
char *openblock = strrchr(cmd + 1, '('), *closeblock = strrchr(cmd + 1, ')'); // find last open and closed parenthesis
if(openblock && (!closeblock || closeblock < openblock)) cmd = openblock; // found opening parenthesis inside the command: assume, a new command starts here
cmd += strspn(cmd + 1, " ") + 1; // skip blanks and one of "/;( ", cmd now points to the first char of the command
// check, if the command is complete, and we want argument completion instead
char *arg = strrchr(cmd, ' '); // find last space in command -> if there is one, we use argument completion
completeval *cdata = NULL;
if(arg) // full command is present
{ // extract command name to find argument list
string command;
copystring(command, cmd);
command[strcspn(cmd, " ")] = '\0';
completeval **hascomplete = completions.access(command);
if(hascomplete) cdata = *hascomplete;
if(completesize < 0 && cdata && cdata->type == COMPLETE_FILE)
{ // get directory contents on first run
cdata->list.deletearrays();
vector<char *> files;
loopv(cdata->dirlist)
{
listfiles(cdata->dirlist[i], cdata->ext, files);
files.sort(stringsort);
loopv(files) cdata->list.add(files[i]);
files.setsize(0);
}
}
}
char *cp = arg ? arg + 1 : cmd; // part of string to complete
bool firstrun = false;
if(completesize < 0)
{ // first run since resetcomplete()
completesize = (int)strlen(cp);
completeidx = reversedirection ? 0 : -1;
firstrun = true;
}
if(!arg)
{ // commandname completion
vector<const char *> matchingidents;
enumerate(*idents, ident, id,
if(!strncasecmp(id.name, cp, completesize) && (id.type != ID_ALIAS || *id.action)) matchingidents.add(id.name); // find all matching possibilities to get the list length (and give an opportunity to sort the list first)
);
if(matchingidents.length())
{
completeidx += reversedirection ? matchingidents.length() - 1 : 1;
completeidx %= matchingidents.length();
matchingidents.sort(stringsortignorecase);
if(firstrun && !reversedirection && !strcmp(matchingidents[completeidx], cp)) completeidx = min(completeidx + 1, matchingidents.length() - 1);
*cp = '\0';
concatstring(s, matchingidents[completeidx]);
}
}
else if(!cdata) return;
else if(cdata->type == COMPLETE_NICK) nickcomplete(s, reversedirection);
else
{ // argument completion
vector<int> matchingargs;
loopv(cdata->list) if(!strncasecmp(cdata->list[i], cp, completesize)) matchingargs.add(i); // find all matching args first
if(matchingargs.length())
{
completeidx += reversedirection ? matchingargs.length() - 1 : 1;
completeidx %= matchingargs.length();
*cp = '\0';
concatstring(s, cdata->list[matchingargs[completeidx]]);
}
}
}
void complete(char *s, bool reversedirection)
{
if(*s == '/' || !nickcomplete(s, reversedirection))
{
commandcomplete(s, reversedirection);
}
}
#endif
const char *curcontext = NULL, *curinfo = NULL;
void scripterr()
{
if(curcontext) conoutf("(%s: %s)", curcontext, curinfo);
else conoutf("(from console or builtin)");
}
void setcontext(const char *context, const char *info)
{
curcontext = context;
curinfo = info;
}
void resetcontext()
{
curcontext = curinfo = NULL;
}
bool execfile(const char *cfgfile)
{
string s;
copystring(s, cfgfile);
setcontext("file", cfgfile);
char *buf = loadfile(path(s), NULL);
if(!buf)
{
resetcontext();
return false;
}
execute(buf);
delete[] buf;
resetcontext();
return true;
}
void exec(const char *cfgfile)
{
if(!execfile(cfgfile)) conoutf("could not read \"%s\"", cfgfile);
}
void execdir(const char *dir)
{
if(dir[0])
{
vector<char *> files;
listfiles(dir, "cfg", files);
loopv(files)
{
defformatstring(d)("%s/%s.cfg",dir,files[i]);
exec(d);
delstring(files[i]);
}
}
}
COMMAND(execdir, "s");
// below the commands that implement a small imperative language. thanks to the semantics of
// () and [] expressions, any control construct can be defined trivially.
void ifthen(char *cond, char *thenp, char *elsep) { commandret = executeret(cond[0]!='0' ? thenp : elsep); }
void loopa(char *var, int *times, char *body)
{
int t = *times;
if(t<=0) return;
ident *id = newident(var, execcontext);
if(id->type!=ID_ALIAS) return;
char *buf = newstring("0", 16);
pushident(*id, buf);
loop_level++;
execute(body);
if(loop_skip) loop_skip = false;
if(loop_break) loop_break = false;
else
{
loopi(t-1)
{
if(buf != id->action)
{
if(id->action != id->executing) delete[] id->action;
id->action = buf = newstring(16);
}
itoa(id->action, i+1);
execute(body);
if(loop_skip) loop_skip = false;
if(loop_break)
{
loop_break = false;
break;
}
}
}
popident(*id);
loop_level--;
}
void whilea(char *cond, char *body)
{
loop_level++;
while(execute(cond))
{
execute(body);
if(loop_skip) loop_skip = false;
if(loop_break)
{
loop_break = false;
break;
}
}
loop_level--;
}
void breaka() { if(loop_level) loop_skip = loop_break = true; }
void continuea() { if(loop_level) loop_skip = true; }
void concat(char *s) { result(s); }
void concatword(char *s) { result(s); }
void format(char **args, int numargs)
{
if(numargs < 1)
{
result("");
return;
}
vector<char> s;
char *f = args[0];
while(*f)
{
int c = *f++;
if(c == '%')
{
int i = *f++;
if(i >= '1' && i <= '9')
{
i -= '0';
const char *sub = i < numargs ? args[i] : "";
while(*sub) s.add(*sub++);
}
else s.add(i);
}
else s.add(c);
}
s.add('\0');
result(s.getbuf());
}
#define whitespaceskip do { s += strspn(s, "\n\t \r"); } while(s[0] == '/' && s[1] == '/' && (s += strcspn(s, "\n\0")))
#define elementskip { if(*s=='"') { do { ++s; s += strcspn(s, "\"\n"); } while(*s == '\"' && s[-1] == '\\'); s += *s=='"'; } else s += strcspn(s, "\r\n\t "); }
void explodelist(const char *s, vector<char *> &elems)
{
whitespaceskip;
while(*s)
{
const char *elem = s;
elementskip;
char *newelem = *elem == '"' ? newstring(elem + 1, s - elem - (s[-1]=='"' ? 2 : 1)) : newstring(elem, s-elem);
#ifndef STANDALONE
if(*elem == '\"') filterrichtext(newelem, newelem, strlen(newelem));
#endif
elems.add(newelem);
whitespaceskip;
}
}
void looplist(char *list, char *varlist, char *body)
{
vector<char *> vars;
explodelist(varlist, vars);
if(vars.length() < 1) return;
vector<ident *> ids;
bool ok = true;
loopv(vars) if(ids.add(newident(vars[i]))->type != ID_ALIAS) { conoutf("looplist error: \"%s\" is readonly", vars[i]); ok = false; }
if(ok)
{
vector<char *> elems;
explodelist(list, elems);
loopv(ids) pushident(*ids[i], newstring(""));
loop_level++;
for(int i = 0; i <= elems.length() - vars.length(); i += vars.length())
{
loopvj(vars)
{
if(ids[j]->action != ids[j]->executing) delete[] ids[j]->action;
ids[j]->action = elems[i + j];
elems[i + j] = NULL;
}
execute(body);
loop_skip = false;
if(loop_break) break;
}
loopv(ids) popident(*ids[i]);
loopv(elems) if(elems[i]) delete[] elems[i];
loop_break = false;
loop_level--;
}
loopv(vars) delete[] vars[i];
}
COMMAND(looplist, "sss");
char *indexlist(const char *s, int pos)
{
whitespaceskip;
loopi(pos)
{
elementskip;
whitespaceskip;
if(!*s) break;
}
const char *e = s;
char *res;
elementskip;
if(*e=='"')
{
e++;
if(s[-1]=='"') --s;
res = newstring(e, s - e);
#ifndef STANDALONE
filterrichtext(res, res, s - e);
#endif
}
else res = newstring(e, s-e);
return res;
}
COMMANDF(at, "si", (char *s, int *pos) { commandret = indexlist(s, *pos); });
int listlen(const char *s)
{
int n = 0;
whitespaceskip;
for(; *s; n++) { elementskip; whitespaceskip; }
return n;
}
int find(char *s, const char *key)
{
whitespaceskip;
int len = strlen(key);
for(int i = 0; *s; i++)
{
char *e = s;
elementskip;
char *a = s;
if(*e == '"')
{
e++;
if(s[-1] == '"') --s;
if(s - e >= len)
{
*s = '\0';
#ifndef STANDALONE
filterrichtext(e, e, s - e);
#endif
if(int(strlen(e)) == len && !strncmp(e, key, len)) return i;
*s = ' ';
}
}
else if(s - e == len && !strncmp(e, key, s - e)) return i;
s = a;
whitespaceskip;
}
return -1;
}
COMMANDF(findlist, "ss", (char *s, char *key) { intret(find(s, key)); });
void colora(char *s)
{
if(s[0] && s[1]=='\0')
{
defformatstring(x)("\f%c",s[0]);
commandret = newstring(x);
}
}
#ifndef STANDALONE
// Easily inject a string into various CubeScript punctuations
const char *punctnames[] = { "QUOTES", "BRACKETS", "PARENTHESIS", "_$_", "QUOTE", "PERCENT", "" };
void addpunct(char *s, char *type)
{
int t = getlistindex(type, punctnames, true, 0);
const char *puncts[] = { "\"%s\"", "[%s]", "(%s)", "$%s", "\"", "%" }, *punct = puncts[t];
if(strchr(punct, 's'))
{
defformatstring(res)(punct, s);
result(res);
}
else result(punct);
}
COMMAND(addpunct, "ss");
#endif
void toLower(char *s) { result(strcaps(s, false)); }
void toUpper(char *s) { result(strcaps(s, true)); }
void testchar(char *s, int *type)
{
bool istrue = false;
switch(*type) {
case 1:
if(isalpha(s[0]) != 0) { istrue = true; }
break;
case 2:
if(isalnum(s[0]) != 0) { istrue = true; }
break;
case 3:
if(islower(s[0]) != 0) { istrue = true; }
break;
case 4:
if(isupper(s[0]) != 0) { istrue = true; }
break;
case 5:
if(isprint(s[0]) != 0) { istrue = true; }
break;
case 6:
if(ispunct(s[0]) != 0) { istrue = true; }
break;
case 7:
if(isspace(s[0]) != 0) { istrue = true; }
break;
case 8: // Without this it is impossible to determine if a character === " in cubescript
if(!strcmp(s, "\"")) { istrue = true; }
break;
default:
if(isdigit(s[0]) != 0) { istrue = true; }
break;
}
if(istrue)
intret(1);
else
intret(0);
}
char *strreplace(char *dest, const char *source, const char *search, const char *replace)
{
vector<char> buf;
int searchlen = strlen(search);
if(!searchlen) { copystring(dest, source); return dest; }
for(;;)
{
const char *found = strstr(source, search);
if(found)
{
while(source < found) buf.add(*source++);
for(const char *n = replace; *n; n++) buf.add(*n);
source = found + searchlen;
}
else
{
while(*source) buf.add(*source++);
buf.add('\0');
return copystring(dest, buf.getbuf());
}
}
}
int stringsort(const char **a, const char **b) { return strcmp(*a, *b); }
int stringsortrev(const char **a, const char **b) { return strcmp(*b, *a); }
int stringsortignorecase(const char **a, const char **b) { return strcasecmp(*a, *b); }
int stringsortignorecaserev(const char **a, const char **b) { return strcasecmp(*b, *a); }
void sortlist(char *list)
{
vector<char *> elems;
explodelist(list, elems);
elems.sort(stringsort);
commandret = conc((const char **)elems.getbuf(), elems.length(), true);
elems.deletearrays();
}
COMMAND(sortlist, "c");
void swapelements(char *list, char *v)
{
vector<char *> elems;
explodelist(list, elems);
vector<char *> swap;
explodelist(v, swap);
vector<int> swapi;
loopv(swap) swapi.add(atoi(swap[i]));
if(swapi.length() && !(swapi.length() & 1)) // swap needs to have an even number of elements
{
for(int i = 0; i < swapi.length(); i += 2)
{
if (elems.inrange(swapi[i]) && elems.inrange(swapi[i + 1]))
{
char *tmp = elems[swapi[i]];
elems[swapi[i]] = elems[swapi[i + 1]];
elems[swapi[i + 1]] = tmp;
}
}
}
commandret = conc((const char **)elems.getbuf(), elems.length(), true);
elems.deletearrays();
swap.deletearrays();
}
COMMAND(swapelements, "ss");
COMMANDN(c, colora, "s");
COMMANDN(loop, loopa, "sis");
COMMANDN(while, whilea, "ss");
COMMANDN(break, breaka, "");
COMMANDN(continue, continuea, "");
COMMANDN(if, ifthen, "sss");
COMMAND(exec, "s");
COMMAND(concat, "c");
COMMAND(concatword, "w");
COMMAND(format, "v");
COMMAND(result, "s");
COMMANDF(execute, "s", (char *s) { intret(execute(s)); });
COMMANDF(listlen, "s", (char *l) { intret(listlen(l)); });
COMMANDN(tolower, toLower, "s");
COMMANDN(toupper, toUpper, "s");
COMMAND(testchar, "si");
COMMANDF(strreplace, "sss", (const char *source, const char *search, const char *replace) { string d; result(strreplace(d, source, search, replace)); });
void add(int *a, int *b) { intret(*a + *b); } COMMANDN(+, add, "ii");
void mul(int *a, int *b) { intret(*a * *b); } COMMANDN(*, mul, "ii");
void sub(int *a, int *b) { intret(*a - *b); } COMMANDN(-, sub, "ii");
void div_(int *a, int *b) { intret(*b ? (*a)/(*b) : 0); } COMMANDN(div, div_, "ii");
void mod_(int *a, int *b) { intret(*b ? (*a)%(*b) : 0); } COMMANDN(mod, mod_, "ii");
void addf(float *a, float *b) { floatret(*a + *b); } COMMANDN(+f, addf, "ff");
void mulf(float *a, float *b) { floatret(*a * *b); } COMMANDN(*f, mulf, "ff");
void subf(float *a, float *b) { floatret(*a - *b); } COMMANDN(-f, subf, "ff");
void divf_(float *a, float *b) { floatret(*b ? (*a)/(*b) : 0); } COMMANDN(divf, divf_, "ff");
void modf_(float *a, float *b) { floatret(*b ? fmod(*a, *b) : 0); } COMMANDN(modf, modf_, "ff");
void powf_(float *a, float *b) { floatret(powf(*a, *b)); } COMMANDN(powf, powf_, "ff");
void not_(int *a) { intret((int)(!(*a))); } COMMANDN(!, not_, "i");
void equal(int *a, int *b) { intret((int)(*a == *b)); } COMMANDN(=, equal, "ii");
void notequal(int *a, int *b) { intret((int)(*a != *b)); } COMMANDN(!=, notequal, "ii");
void lt(int *a, int *b) { intret((int)(*a < *b)); } COMMANDN(<, lt, "ii");
void gt(int *a, int *b) { intret((int)(*a > *b)); } COMMANDN(>, gt, "ii");
void lte(int *a, int *b) { intret((int)(*a <= *b)); } COMMANDN(<=, lte, "ii");
void gte(int *a, int *b) { intret((int)(*a >= *b)); } COMMANDN(>=, gte, "ii");
COMMANDF(round, "f", (float *a) { intret(int(*a + 0.5f)); });
COMMANDF(ceil, "f", (float *a) { intret((int)ceil(*a)); });
COMMANDF(floor, "f", (float *a) { intret((int)floor(*a)); });
#define COMPAREF(opname, func, op) \
void func(float *a, float *b) { intret((int)((*a) op (*b))); } \
COMMANDN(opname, func, "ff")
COMPAREF(=f, equalf, ==);
COMPAREF(!=f, notequalf, !=);
COMPAREF(<f, ltf, <);
COMPAREF(>f, gtf, >);
COMPAREF(<=f, ltef, <=);
COMPAREF(>=f, gtef, >=);
void anda (char *a, char *b) { intret(execute(a)!=0 && execute(b)!=0); }
void ora (char *a, char *b) { intret(execute(a)!=0 || execute(b)!=0); }
COMMANDN(&&, anda, "ss");
COMMANDN(||, ora, "ss");
COMMANDF(strcmp, "ss", (char *a, char *b) { intret((strcmp(a, b) == 0) ? 1 : 0); });
COMMANDF(rnd, "i", (int *a) { intret(*a>0 ? rnd(*a) : 0); });
#ifndef STANDALONE
const char *escapestring(const char *s, bool force, bool noquotes)
{
static vector<char> strbuf[3];
static int stridx = 0;
if(noquotes) force = false;
if(!s) return force ? "\"\"" : "";
if(!force && !*(s + strcspn(s, "\"/\\;()[] \f\t\r\n"))) return s;
stridx = (stridx + 1) % 3;
vector<char> &buf = strbuf[stridx];
buf.setsize(0);
if(!noquotes) buf.add('"');
for(; *s; s++) switch(*s)
{
case '\n': buf.put("\\n", 2); break;
case '\r': buf.put("\\n", 2); break;
case '\t': buf.put("\\t", 2); break;
case '\a': buf.put("\\a", 2); break;
case '\f': buf.put("\\f", 2); break;
case '"': buf.put("\\\"", 2); break;
case '\\': buf.put("\\\\", 2); break;
default: buf.add(*s); break;
}
if(!noquotes) buf.add('"');
buf.add(0);
return buf.getbuf();
}
COMMANDF(escape, "s", (const char *s) { result(escapestring(s));});
int sortident(ident **a, ident **b) { return strcasecmp((*a)->name, (*b)->name); }
VARP(omitunchangeddefaults, 0, 0, 1);
VAR(groupvariables, 0, 4, 10);
void writecfg()
{
filerotate("config/saved", "cfg", CONFIGROTATEMAX); // keep five old config sets
stream *f = openfile(path("config/saved.cfg", true), "w");
if(!f) return;
f->printf("// automatically written on exit, DO NOT MODIFY\n// delete this file to have defaults.cfg overwrite these settings\n// modify settings in game, or put settings in autoexec.cfg to override anything\n\n");
f->printf("// basic settings\n\n");
f->printf("name %s\n", escapestring(player1->name, false));
f->printf("skin_cla %d\nskin_rvsf %d\n", player1->skin(TEAM_CLA), player1->skin(TEAM_RVSF));
for(int i = CROSSHAIR_DEFAULT; i < CROSSHAIR_NUM; i++) if(crosshairs[i] && crosshairs[i] != notexture)
{
f->printf("loadcrosshair %s %s\n", crosshairnames[i], behindpath(crosshairs[i]->name));
}
extern int lowfps, highfps;
f->printf("fpsrange %d %d\n", lowfps, highfps);
extern string myfont;
f->printf("setfont %s\n", myfont);
f->printf("\n");
audiomgr.writesoundconfig(f);
f->printf("\n");
f->printf("// crosshairs and kill messages for each weapon\n\nlooplist [\n");
loopi(NUMGUNS) f->printf(" %-7s %-11s %-12s %s\n", gunnames[i], crosshairs[i] && crosshairs[i] != notexture ? behindpath(crosshairs[i]->name) : "\"\"", escapestring(killmessage(i, false)), escapestring(killmessage(i, true)));
f->printf("] [ w cc f g ] [ loadcrosshair $w $cc ; fragmessage $w $f ; gibmessage $w $g ]\n");
f->printf("\n\n// client variables (unchanged default values %s)\n", omitunchangeddefaults ? "omitted" : "commented out");
vector<ident *> sids;
enumerate(*idents, ident, id,
if(id.persist) switch(id.type)
{
case ID_VAR:
case ID_FVAR:
case ID_SVAR:
sids.add(&id);
break;
}
);
sids.sort(sortident);
const char *rep = "";
int repn = 0;
bool lastdef = false, curdef;
loopv(sids)
{
ident &id = *sids[i];
curdef = (id.type == ID_VAR && *id.storage.i == id.defaultval) || (id.type == ID_FVAR && *id.storage.f == id.defaultvalf);
if(curdef && omitunchangeddefaults) continue;
f->printf("%s", !strncmp(rep, id.name, curdef ? 1 : 3) && ++repn < groupvariables && lastdef == curdef ? " ; " : (repn = 0, "\n"));
rep = id.name;
lastdef = curdef;
if(curdef && repn == 0) f->printf("// ");
switch(id.type)
{
case ID_VAR: f->printf("%s %d", id.name, *id.storage.i); break;
case ID_FVAR: f->printf("%s %s", id.name, floatstr(*id.storage.f)); break;
case ID_SVAR: f->printf("%s %s", id.name, escapestring(*id.storage.s, false)); break;
}
if(!groupvariables)
{
if(id.type == ID_VAR) f->printf(" // min: %d, max: %d, def: %d", id.minval, id.maxval, id.defaultval);
if(id.type == ID_FVAR) f->printf(" // min: %s, max: %s, def: %s", floatstr(id.minvalf), floatstr(id.maxvalf), floatstr(id.defaultvalf));
const char *doc = docgetdesc(id.name);
if(doc) f->printf(id.type == ID_SVAR ? " // %s" : ", %s", doc);
}
}
f->printf("\n\n// weapon settings\n\n");
loopi(NUMGUNS) if(guns[i].isauto)
{
f->printf("burstshots %s %d\n", gunnames[i], burstshotssettings[i]);
}
f->printf("\n// key binds\n\n");
writebinds(f);
f->printf("\n// aliases\n\n");
sids.setsize(0);
enumerate(*idents, ident, id, if(id.type == ID_ALIAS && id.persist) sids.add(&id); );
sids.sort(sortident);
loopv(sids)
{
ident &id = *sids[i];
if(strncmp(id.name, "demodesc_", 9))
{
const char *action = id.action;
for(identstack *s = id.stack; s; s = s->next) action = s->action;
if(action[0]) f->printf("alias %s %s\n", escapestring(id.name, false), escapestring(action, false));
sids.remove(i--);
}
}
if(sids.length())
{
f->printf("\n// demo descriptions\n\n");
loopv(sids)
{
ident &id = *sids[i];
const char *action = id.action;
for(identstack *s = id.stack; s; s = s->next) action = s->action;
if(action[0]) f->printf("alias %s %s\n", escapestring(id.name, false), escapestring(action, false));
}
}
f->printf("\n");
delete f;
writeauthkey();
}
COMMAND(writecfg, "");
void deletecfg()
{
string configs[] = { "config/saved.cfg", "config/init.cfg" };
loopj(2) // delete files in homedir and basedir if possible
{
loopi(sizeof(configs)/sizeof(configs[0]))
{
const char *file = findfile(path(configs[i], true), "r");
if(!file || findfilelocation == FFL_ZIP) continue;
delfile(file);
}
}
}
#endif
void identnames(vector<const char *> &names, bool builtinonly)
{
enumeratekt(*idents, const char *, name, ident, id,
{
if(!builtinonly || id.type != ID_ALIAS) names.add(name);
});
}
void pushscontext(int newcontext)
{
contextstack.add(execcontext);
execcontext = newcontext;
}
int popscontext()
{
ASSERT(contextstack.length() > 0);
int old = execcontext;
execcontext = contextstack.pop();
if(execcontext < old && old >= IEXC_MAPCFG) // clean up aliases created in the old (map cfg) context
{
int limitcontext = max(execcontext + 1, (int) IEXC_MAPCFG); // don't clean up below IEXC_MAPCFG
enumeratekt(*idents, const char *, name, ident, id,
{
if(id.type == ID_ALIAS && id.context >= limitcontext)
{
while(id.stack && id.stack->context >= limitcontext)
popident(id);
if(id.context >= limitcontext)
{
if(id.action != id.executing) delete[] id.action;
idents->remove(name);
}
}
});
}
return execcontext;
}
void scriptcontext(int *context, char *idname)
{
if(contextsealed) return;
ident *id = idents->access(idname);
if(!id) return;
int c = *context;
if(c >= 0 && c < IEXC_NUM) id->context = c;
}
void isolatecontext(int *context)
{
if(*context >= 0 && *context < IEXC_NUM && !contextsealed) contextisolated[*context] = true;
}
void sealcontexts() { contextsealed = true; }
bool allowidentaccess(ident *id) // check if ident is allowed in current context
{
ASSERT(execcontext >= 0 && execcontext < IEXC_NUM);
if(!id) return false;
if(!contextisolated[execcontext]) return true; // only check if context is isolated
return execcontext <= id->context;
}
COMMAND(scriptcontext, "is");
COMMAND(isolatecontext, "i");
COMMAND(sealcontexts, "");
#ifndef STANDALONE
COMMANDF(watchingdemo, "", () { intret(watchingdemo); });
void systime()
{
result(numtime());
}
void timestamp_()
{
result(timestring(true, "%Y %m %d %H %M %S"));
}
void datestring()
{
result(timestring(true, "%c"));
}
void timestring_()
{
const char *res = timestring(true, "%H:%M:%S");
result(res[0] == '0' ? res + 1 : res);
}
extern int millis_() { extern int totalmillis; return totalmillis; }
void strlen_(char *s) { intret(strlen(s)); }
void substr_(char *fs, int *pa, int *len)
{
int ia = *pa;
int ilen = *len;
int fslen = (int)strlen(fs);
if(ia<0) ia += fslen;
if(ia>fslen || ia < 0 || ilen < 0) return;
if(!ilen) ilen = fslen-ia;
if(ilen >= 0 && ilen < int(strlen(fs+ia))) (fs+ia)[ilen] = '\0';
result(fs+ia);
}
void strpos_(char *haystack, char *needle, int *occurence)
{
int position = -1;
char *ptr = haystack;
if(haystack && needle)
for(int iocc = *occurence; iocc >= 0; iocc--)
{
ptr = strstr(ptr, needle);
if (ptr)
{
position = ptr-haystack;
ptr += strlen(needle);
}
else
{
position = -1;
break;
}
}
intret(position);
}
void l0(int *p, int *v) { string f; string r; formatstring(f)("%%0%dd", *p); formatstring(r)(f, *v); result(r); }
void getscrext()
{
switch(screenshottype)
{
case 2: result(".png"); break;
case 1: result(".jpg"); break;
case 0:
default: result(".bmp"); break;
}
}
COMMANDF(millis, "", () { intret(millis_()); });
COMMANDN(strlen, strlen_, "s");
COMMANDN(substr, substr_, "sii");
COMMANDN(strpos, strpos_, "ssi");
COMMAND(l0, "ii");
COMMAND(systime, "");
COMMANDN(timestamp, timestamp_, "");
COMMAND(datestring, "");
COMMANDN(timestring, timestring_, "");
COMMANDF(getmode, "i", (int *acr) { result(modestr(gamemode, *acr != 0)); });
COMMAND(getscrext, "");
void listoptions(char *s)
{
extern const char *menufilesortorders[], *texturestacktypes[];
const char *optionnames[] = { "entities", "ents", "weapons", "teamnames", "teamnames-abbrv", "punctuations", "crosshairnames", "menufilesortorders", "texturestacktypes", "" };
const char **optionlists[] = { optionnames, entnames + 1, entnames + 1, gunnames, teamnames, teamnames_s, punctnames, crosshairnames, menufilesortorders, texturestacktypes };
const char **listp = optionlists[getlistindex(s, optionnames, true, -1) + 1];
commandret = conc(listp, -1, true);
}
COMMAND(listoptions, "s");
const char *currentserver(int i) // [client version]
{
static string curSRVinfo;
// using the curpeer directly we can get the info of our currently connected server
string r;
r[0] = '\0';
extern ENetPeer *curpeer;
if(curpeer)
{
switch(i)
{
case 1: // IP
{
uchar *ip = (uchar *)&curpeer->address.host;
formatstring(r)("%d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]);
break;
}
case 2: // HOST
{
char hn[1024];
formatstring(r)("%s", (enet_address_get_host(&curpeer->address, hn, sizeof(hn))==0) ? hn : "unknown");
break;
}
case 3: // PORT
{
formatstring(r)("%d", curpeer->address.port);
break;
}
case 4: // STATE
{
const char *statenames[] =
{
"disconnected",
"connecting",
"acknowledging connect",
"connection pending",
"connection succeeded",
"connected",
"disconnect later",
"disconnecting",
"acknowledging disconnect",
"zombie"
};
if(curpeer->state>=0 && curpeer->state<int(sizeof(statenames)/sizeof(statenames[0])))
copystring(r, statenames[curpeer->state]);
break; // 5 == Connected (compare ../enet/include/enet/enet.h +165)
}
// CAUTION: the following are only filled if the serverbrowser was used or the scoreboard shown
// SERVERNAME
case 5: { serverinfo *si = getconnectedserverinfo(); if(si) copystring(r, si->name); break; }
// DESCRIPTION (3)
case 6: { serverinfo *si = getconnectedserverinfo(); if(si) copystring(r, si->sdesc); break; }
case 7: { serverinfo *si = getconnectedserverinfo(); if(si) copystring(r, si->description); break; }
// CAUTION: the following is only the last full-description _seen_ in the serverbrowser!
case 8: { serverinfo *si = getconnectedserverinfo(); if(si) copystring(r, si->full); break; }
// just IP & PORT as default response - always available, no lookup-delay either
default:
{
uchar *ip = (uchar *)&curpeer->address.host;
formatstring(r)("%d.%d.%d.%d %d", ip[0], ip[1], ip[2], ip[3], curpeer->address.port);
break;
}
}
}
copystring(curSRVinfo, r);
return curSRVinfo;
}
COMMANDF(curserver, "i", (int *i) { result(currentserver(*i)); });
#endif
void debugargs(char **args, int numargs)
{
printf("debugargs: ");
loopi(numargs)
{
if(i) printf(", ");
printf("\"%s\"", args[i]);
}
printf("\n");
}
COMMAND(debugargs, "v"); | true |
e1166b8780e2692c255ff48d79f6713c339f1e75 | C++ | tlund80/automated-colour-calibration | /src/experiments/classifyBall.cpp | UTF-8 | 3,243 | 2.953125 | 3 | [] | no_license | #include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
#include <stdio.h>
using namespace cv;
using namespace std;
/** @function main */
int main(int argc, char** argv)
{
Mat srcOrig;
/// Read the image
srcOrig = imread( argv[1], 1 );
//src_grayOrig = imread(argv[1], 0);
if( !srcOrig.data )
{ return -1; }
namedWindow("trackbar",CV_WINDOW_NORMAL);
namedWindow("bwImage",CV_WINDOW_NORMAL);
namedWindow("src with detected Hough Circles", CV_WINDOW_NORMAL);
namedWindow("edgeMap",CV_WINDOW_NORMAL);
namedWindow("saturated", CV_WINDOW_NORMAL);
double alpha=1.0; // 1.0 - 3.0
double beta=0; // 0-100
int alphaLevel=0;
int betaLevel=255;
createTrackbar("alpha","trackbar", &alphaLevel, 255);
createTrackbar("beta","trackbar", &betaLevel, 255);
int thresholdType = 0;
int thresholdValue = 0;
int max_binary_value = 255;
string trackbar_type = "Type: \n 0: Binary \n 1: Binary Inverted \n 2: Truncate \n 3: To Zero \n 4: To Zero Inverted";
createTrackbar(trackbar_type,"trackbar",&thresholdType,5);
createTrackbar("Threshold Value","trackbar",&thresholdValue,255);
/// Initialize values
// std::cout<<"* Enter the alpha value [1.0-3.0]: ";std::cin>>alpha;
// std::cout<<"* Enter the beta value [0-100]: "; std::cin>>beta;
do {
alpha = (double)alphaLevel/255 * 2.0 + 1.0;
beta = (double)betaLevel/255 * 100;
Mat src = srcOrig.clone();
Mat saturated = Mat::zeros( src.size(), src.type() );
/// Do the operation saturated(i,j) = alpha*image(i,j) + beta
for( int y = 0; y < src.rows; y++ ) {
for( int x = 0; x < src.cols; x++ ) {
for( int c = 0; c < 3; c++ ) {
saturated.at<Vec3b>(y,x)[c] =
saturate_cast<uchar>( alpha*( src.at<Vec3b>(y,x)[c] ) + beta );
}
}
}
Mat src_gray,bwImage;
cvtColor(src,src_gray,CV_RGB2GRAY);
threshold(src_gray, bwImage, thresholdValue, max_binary_value,thresholdType);
Mat edgeMap;
//Canny(saturated,edgeMap, 150,200,3);
Canny(bwImage,edgeMap, 150,200,3);
/// Reduce the noise so we avoid false circle detection
GaussianBlur( edgeMap, edgeMap, Size(7, 7), 2, 2 );
#if 1
vector<Vec3f> circles;
/// Apply the Hough Transform to find the circles
HoughCircles(edgeMap, circles, CV_HOUGH_GRADIENT, 1, 1, 200, 100, 0, 0 );
cout << circles.size() << endl;
/// Draw the circles detected
for( size_t i = 0; i < circles.size(); i++ )
{
Point center(cvRound(circles[i][0]), cvRound(circles[i][1]));
int radius = cvRound(circles[i][2]);
// circle center
circle( src, center, 3, Scalar(0,255,0), -1, 8, 0 );
// circle outline
circle( src, center, radius, Scalar(255,0,0), 3, 8, 0 );
}
#endif
imshow("src with detected Hough Circles",src);
imshow("bwImage",bwImage);
imshow("edgeMap", edgeMap);
imshow("saturated", saturated);
} while(waitKey(0) != 27);
return 0;
}
| true |
ea1e00b92621861295937fb7ca3dea7c5d5f9e01 | C++ | yangjufo/LeetCode | /2021/1228. Missing Number In Arithmetic Progression.cpp | UTF-8 | 544 | 2.84375 | 3 | [] | no_license | class Solution {
public:
int missingNumber(vector<int>& arr) {
int firstDiff = arr[1] - arr[0], secondDiff = arr[2] - arr[1];
if (abs(firstDiff) < abs(secondDiff)) {
return arr[1] + firstDiff;
}
if (abs(firstDiff) > abs(secondDiff)) {
return arr[1] - secondDiff;
}
for (int i = 3; i < arr.size(); i++) {
if (arr[i] - arr[i - 1] != firstDiff) {
return arr[i - 1] + firstDiff;
}
}
return arr[0];
}
}; | true |
74c2d2e2db046a06335df940dc189f53bf700ac1 | C++ | GeorgiMinkov/SD-Practicum-2016-2017 | /HW01/Request.cpp | UTF-8 | 13,434 | 2.984375 | 3 | [] | no_license | #include "stdafx.h"
#include "Request.h"
// In every request we check some equals condition: if file we want to read from, exist in directory, if it is open.
// We have check if there is already output file request then we check for infile equality and if it is not equal we delete file and write over it, to
// save condition from task.
void requestByType(const Type &type, const std::string fileName)
{
if (!checkFileExist(fileName))
{
throw "FileExistanceExseption";
}
else
{
std::ifstream fi(fileName.c_str(), std::ios::in);
if (!fi.is_open())
{
throw "FileOpenExseption";
}
else
{
Type tmpType = E;
char tmpTypeChar = 'E';
std::string line = "", fileOutputName = __FUNCTION__; // file name with the name of the current function
fileOutputName += ".txt";
if (checkFileExist(fileOutputName))
{
std::ifstream fiTMP(fileOutputName.c_str(), std::ios::in);
fiTMP >> tmpTypeChar;
tmpType = getType(tmpTypeChar);
if (tmpType == type)
{
fiTMP.close();
return;
}
else
{
fiTMP.close();
}
}
std::ofstream fo(fileOutputName, std::ios::out | std::ios::trunc);
if (!fo.is_open())
{
throw "FileToWriteExseption";
}
else
{
while (!fi.eof())
{
// take type and create needed arguments
fi >> tmpTypeChar;
fi.seekg(-1, std::ios::cur);
tmpType = getType(tmpTypeChar);
switch (tmpType)
{
case P:
{
PC tmp;
// full object from file
fi >> tmp;
// check condition
if (tmp.getType() == type)
{
fo << tmp << std::endl;
} break;
}
case L:
{
Laptop tmp;
// full object from file
fi >> tmp;
// check condition
if (tmp.getType() == type)
{
fo << tmp << std::endl;
} break;
}
case S:
{
Smartphone tmp;
// full object from file
fi >> tmp;
// check condition
if (tmp.getType() == type)
{
fo << tmp << std::endl;
} break;
}
default : if (fi.eof()) break;
}
}
fo.close();
fi.close();
}
}
}
}
void requsetByBrand(const std::string & brand, const std::string fileName)
{
if (!checkFileExist(fileName))
{
throw "FileExistanceExseption";
}
else
{
std::ifstream fi(fileName.c_str(), std::ios::in);
if (!fi.is_open())
{
throw "FileOpenExseption";
}
else
{
Type tmpType = E;
char tmpTypeChar = 'E';
std::string fileOutputName = __FUNCTION__;
fileOutputName += ".txt";
if (checkFileExist(fileOutputName))
{
std::ifstream fiTMP(fileOutputName.c_str(), std::ios::in);
fiTMP >> tmpTypeChar;
tmpType = getType(tmpTypeChar);
switch (tmpType)
{
case P:
{
PC tmp;
fiTMP >> tmp;
if (brand == tmp.getBrand())
{
fiTMP.close();
return;
}
else
{
fiTMP.close();
}
}
case L:
{
Laptop tmp;
fiTMP >> tmp;
if (brand == tmp.getBrand())
{
fiTMP.close();
return;
}
else
{
fiTMP.close();
}
}
case S:
{
Smartphone tmp;
fiTMP >> tmp;
if (brand == tmp.getBrand())
{
fiTMP.close();
return;
}
else
{
fiTMP.close();
}
}
}
}
std::ofstream fo(fileOutputName, std::ios::out | std::ios::trunc);
if (!fo.is_open())
{
throw "FileToWriteExseption";
}
else
{
while (!fi.eof())
{
// read type
fi >> tmpTypeChar;
fi.seekg(-1, std::ios::cur);
tmpType = getType(tmpTypeChar);
switch (tmpType)
{
case P:
{
PC tmp;
// full object from file
fi >> tmp;
// check condition
if (brand == tmp.getBrand())
{
fo << tmp << std::endl;
} break;
}
case L:
{
Laptop tmp;
// full object from file
fi >> tmp;
// check condition
if (brand == tmp.getBrand())
{
fo << tmp << std::endl;
} break;
}
case S:
{
Smartphone tmp;
// full object from file
fi >> tmp;
// check condition
if (brand == tmp.getBrand())
{
fo << tmp << std::endl;
} break;
}
default: if (fi.eof()) break;
}
}
fo.close();
fi.close();
}
}
}
}
void requestByModelAndBrand(const std::string &brand, const std::string &model, const std::string fileName)
{
if (!checkFileExist(fileName))
{
throw "FileExistanceExseption";
}
else
{
std::ifstream fi(fileName.c_str(), std::ios::in);
if (!fi.is_open())
{
throw "FileOpenExseption";
}
else
{
Type tmpType = E;
char tmpTypeChar = 'E';
std::string fileOutputName = __FUNCTION__;
fileOutputName += ".txt";
if (checkFileExist(fileOutputName))
{
std::ifstream fiTMP(fileOutputName.c_str(), std::ios::in);
fiTMP >> tmpTypeChar;
tmpType = getType(tmpTypeChar);
switch (tmpType)
{
case P:
{
PC tmp;
fiTMP >> tmp;
if (brand == tmp.getBrand() && model == tmp.getModel())
{
fiTMP.close();
return;
}
else
{
fiTMP.close();
}
}
case L:
{
Laptop tmp;
fiTMP >> tmp;
if (brand == tmp.getBrand() && model == tmp.getModel())
{
fiTMP.close();
return;
}
else
{
fiTMP.close();
}
}
case S:
{
Smartphone tmp;
fiTMP >> tmp;
if (brand == tmp.getBrand() && model == tmp.getModel())
{
fiTMP.close();
return;
}
else
{
fiTMP.close();
}
}
}
}
std::ofstream fo(fileOutputName, std::ios::out | std::ios::trunc);
if (!fo.is_open())
{
throw "FileToWriteExseption";
}
else
{
while (!fi.eof())
{
// read type
fi >> tmpTypeChar;
fi.seekg(-1, std::ios::cur);
tmpType = getType(tmpTypeChar);
switch (tmpType)
{
case P:
{
PC tmp;
// fill object
fi >> tmp;
// check condition
if (brand == tmp.getBrand() && model == tmp.getModel())
{
fo << tmp << std::endl;
} break;
}
case L:
{
Laptop tmp;
// fill object
fi >> tmp;
// check condition
if (brand == tmp.getBrand() && model == tmp.getModel())
{
fo << tmp << std::endl;
} break;
}
case S:
{
Smartphone tmp;
// fill object
fi >> tmp;
// check condition
if (brand == tmp.getBrand() && model == tmp.getModel())
{
fo << tmp << std::endl;
} break;
}
default: if (fi.eof()) break;
}
}
fo.close();
fi.close();
}
}
}
}
void requestByPrice(const Type & type, const float &price, const std::string fileName)
{
if (!checkFileExist(fileName))
{
throw "FileExistanceExseption";
}
else
{
std::ifstream fi(fileName.c_str(), std::ios::in);
if (!fi.is_open())
{
throw "FileOpenExseption";
}
else
{
Type tmpType = E;
char tmpTypeChar = 'E';
std::string fileOutputName = __FUNCTION__;
fileOutputName += ".txt";
std::string fileOutputNameInValue = __FUNCTION__;
fileOutputNameInValue += "InValue.txt";
if (checkFileExist(fileOutputNameInValue))
{
std::ifstream fiTmp(fileOutputNameInValue, std::ios::in);
float tmpPrice = 0.0f;
fiTmp >> tmpTypeChar >> tmpPrice;
tmpType = getType(tmpTypeChar);
if (tmpType == type && tmpPrice == price)
{
fiTmp.close();
return;
}
else
{
fiTmp.close();
}
}
std::ofstream foTmp(fileOutputNameInValue.c_str(), std::ios::out | std::ios::trunc);
foTmp << returnType(type) << " " << price;
foTmp.close();
std::ofstream fo(fileOutputName.c_str(), std::ios::out | std::ios::trunc);
if (!fo.is_open())
{
throw "FileToWriteExseption";
}
else
{
while (!fi.eof())
{
// read type
fi >> tmpTypeChar;
fi.seekg(-1, std::ios::cur);
tmpType = getType(tmpTypeChar);
switch (tmpType)
{
case P:
{
PC tmp;
// fill object
fi >> tmp;
// check condition
if (type == tmp.getType() && price >= tmp.getPrice())
{
fo << tmp << std::endl;
} break;
}
case L:
{
Laptop tmp;
// fill object
fi >> tmp;
// check condition
if (type == tmp.getType() && price >= tmp.getPrice())
{
fo << tmp << std::endl;
} break;
}
case S:
{
Smartphone tmp;
// fill object
fi >> tmp;
// check condition
if (type == tmp.getType() && price >= tmp.getPrice())
{
fo << tmp << std::endl;
} break;
}
default: if (fi.eof()) break;
}
}
fo.close();
fi.close();
}
}
}
}
void requestByPriceAndBrand(const Type & type, const std::string &brand, const float &price, const std::string fileName)
{
if (!checkFileExist(fileName))
{
throw "FileExistanceExseption";
}
else
{
std::ifstream fi(fileName.c_str(), std::ios::in);
if (!fi.is_open())
{
throw "FileOpenExseption";
}
else
{
Type tmpType = E;
char tmpTypeChar = 'E';
std::string fileOutputName = __FUNCTION__;
fileOutputName += ".txt";
std::string fileOutputNameInValue = __FUNCTION__;
fileOutputNameInValue += "InValue.txt";
if (checkFileExist(fileOutputNameInValue))
{
std::ifstream fiTmp(fileOutputNameInValue.c_str(), std::ios::in);
std::string tmpBrand = "";
float tmpPrice = 0.0f;
fiTmp >> tmpTypeChar >> tmpBrand >> tmpPrice;
tmpType = getType(tmpTypeChar);
if (tmpType == type && tmpPrice == price && tmpBrand == brand)
{
fiTmp.close();
return;
}
else
{
fiTmp.close();
}
}
std::ofstream foTmp(fileOutputNameInValue.c_str(), std::ios::out | std::ios::trunc);
foTmp << returnType(type) << " " << brand << " "<< price;
foTmp.close();
std::ofstream fo(fileOutputName.c_str(), std::ios::out | std::ios::trunc);
if (!fo.is_open())
{
throw "FileToWriteExseption";
}
else
{
while (!fi.eof())
{
// read type
fi >> tmpTypeChar;
fi.seekg(-1, std::ios::cur);
tmpType = getType(tmpTypeChar);
switch (tmpType)
{
case P:
{
PC tmp;
// fill object
fi >> tmp;
// check condition
if (type == tmp.getType() && price >= tmp.getPrice() && brand == tmp.getBrand())
{
fo << tmp << std::endl;
} break;
}
case L:
{
Laptop tmp;
// fill object
fi >> tmp;
// check condition
if (type == tmp.getType() && price >= tmp.getPrice() && brand == tmp.getBrand())
{
fo << tmp << std::endl;
} break;
}
case S:
{
Smartphone tmp;
// fill object
fi >> tmp;
// check condition
if (type == tmp.getType() && price >= tmp.getPrice() && brand == tmp.getBrand())
{
fo << tmp << std::endl;
} break;
}
default: if (fi.eof()) break;
}
}
fo.close();
fi.close();
}
}
}
}
void draw()
{
system("CLS");
std::cout << "Command | Request\n";
std::cout << std::setw(4) << "0" << std::setw(14) << "| Exit\n";
std::cout << std::setw(4) << "1" << std::setw(17) << "| By type\n";
std::cout << std::setw(4) << "2" << std::setw(18) << "| By brand\n";
std::cout << std::setw(4) << "3" << std::setw(28) << "| By model and brand\n";
std::cout << std::setw(4) << "4" << std::setw(27) << "| By type and price\n";
std::cout << std::setw(4) << "5" << std::setw(34) << "| By type, brand and price\n";
}
short getCommand()
{
draw();
short command = 0;
std::string fileName = "file.txt";
std::cout << "\nEnter command: ";
std::cin >> command;
switch (command)
{
case 1:
{
char input = ' ';
do
{
std::cout << "Enter type: P, L, S -> ";
std::cin >> input;
} while (input != 'P' && input != 'L' && input != 'S');
requestByType(getType(input), fileName);
}break;
case 2:
{
std::string brand = "";
std::cout << "Enter brand -> ";
std::cin >> brand;
requsetByBrand(brand, fileName);
}break;
case 3:
{
std::string brand = "", model = "";
std::cout << "Enter brand -> ";
std::cin >> brand;
std::cout << "Enter model -> ";
std::cin >> model;
requestByModelAndBrand(brand, model, fileName);
}break;
case 4:
{
char input = ' ';
float price = 0.0f;
do
{
std::cout << "Enter type: P, L, S -> ";
std::cin >> input;
} while (input != 'P' && input != 'L' && input != 'S');
do
{
std::cout << "Enter price(>=0) -> ";
std::cin >> price;
} while (price < 0);
requestByPrice(getType(input), price, fileName);
}break;
case 5:
{
char input = ' ';
float price = 0.0f;
std::string brand = "";
do
{
std::cout << "Enter type: P, L, S -> ";
std::cin >> input;
} while (input != 'P' && input != 'L' && input != 'S');
std::cout << "Enter brand -> ";
std::cin >> brand;
do
{
std::cout << "Enter price(>=0) -> ";
std::cin >> price;
} while (price < 0);
requestByPriceAndBrand(getType(input), brand, price, fileName);
}break;
}
std::cout << "Proccesing: ";
for (size_t i = 0; i < 35; ++i)
{
std::cout << "|";
Sleep(100);
}
std::cout << "\nReady\n";
Sleep(500);
return command;
}
| true |
2ea772ba5bbc91f550fbc8775837a8a138aedc0d | C++ | alloncm/spirit | /Engine/Font.h | UTF-8 | 489 | 2.546875 | 3 | [] | no_license | #pragma once
#include"Surface.h"
#include"Vec2.h"
#include"Graphics.h"
class Font
{
public:
Font(std::string filename, Color chroma = Colors::White);
void DrawText(std::string& src, Location& pos,Color color, Graphics& gfx);
private:
RectI MapGleaphRect(char c);
private:
Surface sprite;
int gliphHeight;
int gliphWidth;
Color chroma;
static constexpr int nColomns = 32;
static constexpr int nRows = 3;
static constexpr char first = ' ';
static constexpr char last = '~';
}; | true |
e541710426efc9ffcadaf87cfb6bd67c723a59bb | C++ | yok3r/COVID_Ambu | /Arduino/seguridad_v1/seguridad_v1.ino | UTF-8 | 1,118 | 2.8125 | 3 | [] | no_license |
const int endstopper1 = 2; // Endstopper 1
const int onoff = 3; // Endstopper 1
int endstopper1State = 0;
int onoffState = 0;
int lastendstopper = 1;
const int alarm = 12;// Alarm on pin 4
unsigned long previousMillis = 0;
unsigned long currentMillis = 0;
const long interval = 6000; // Set the Time in milliseconds to activate the alarm 1000 = 1 sec
void setup() {
pinMode(alarm, OUTPUT);
pinMode(endstopper1, INPUT);
pinMode(onoff, INPUT);
Serial.begin(9600);
}
void loop() {
onoffState = digitalRead(onoff);
if (onoffState == HIGH) {
currentMillis = millis();
Serial.println(currentMillis - previousMillis);
if (currentMillis - previousMillis >= interval) {
digitalWrite(alarm, HIGH);
delay(500);
digitalWrite(alarm, LOW);
}
endstopper1State = digitalRead(endstopper1);
if (endstopper1State != lastendstopper) {
if (lastendstopper == 0) {
lastendstopper = 1;
previousMillis = millis();
} else {
lastendstopper = 0;
previousMillis = millis();
}
}
} else {
delay(50);
}
}
| true |
3affb5ab6026407658671791447f85811b8909f1 | C++ | mooleetzi/ICPC | /contest/ac_automation/hdu2896.cpp | WINDOWS-1252 | 2,709 | 2.609375 | 3 | [] | no_license | #include<iostream>
#include<cstring>
#include<cstdio>
#include<queue>
#include<algorithm>
using namespace std;
const int maxn=5e5+10;
struct node{
node *fail;
node *next[180];
int cnt,num;
node(){
fail=NULL;
memset(this->next,NULL,sizeof this->next);
cnt=num=0;
}
}*q[maxn];
void insert(node *rt,char s[],int cnt){
node *p=rt;
int len=strlen(s);
for (int i=0;i<len;i++){
int cur=s[i]-31;
if (p->next[cur]==NULL)
p->next[cur]=new node();
p=p->next[cur];
}
p->cnt++;
p->num=cnt;
}
void build_ac_automation(node *root) // bfsfailָ
{
int head,tail;
head=tail=0;
root->fail = NULL;
q[tail++] = root;
while(head < tail) {
node *temp = q[head++];
node *p = NULL;
for(int i = 0; i < 128; i++) {
if(temp->next[i] != NULL) {
if(temp == root) temp->next[i]->fail = root;
else {
p = temp->fail;
while(p != NULL) {
if(p->next[i] != NULL) {
temp->next[i]->fail = p->next[i];
break;
}
p = p->fail;
}
if(p == NULL) temp->next[i]->fail = root;
}
q[tail++] = temp->next[i];
}
}
}
}
int query(node *rt,char s[],int a[],int &tot){
int len=strlen(s);
node *p=rt;
for (int i=0;i<len;i++){
int cur=s[i]-31;
while(p->next[cur]==NULL&&p!=rt)
p=p->fail;
p=p->next[cur];
if (p==NULL)
p=rt;
node *tmp=p;
while(tmp!=rt&&tmp->cnt!=-1){
if (tmp->cnt)
a[tot++]=tmp->num;
//tmp->cnt=0;
tmp=tmp->fail;
}
}
if (tot)
return 1;
return 0;
}
int main(){
int n,m,cnt=0;
scanf("%d",&n);
node *rt=new node();
getchar();
for (int i=1;i<=n;i++){
char *s=new char[110];
scanf("%s",s);
insert(rt,s,i);
}
//getchar();
build_ac_automation(rt);
scanf("%d",&m);
for (int i=1;i<=m;i++){
char *s=new char[10010];
scanf("%s",s);
int a[n+1];
int tot=0;
memset(a,0,sizeof a);
if (query(rt,s,a,tot)){
++cnt;
printf("web %d: ",i);
sort(a,a+tot);
a[tot]=0x3f3f3f3f;
for (int i=0;i<tot;i++)
if(a[i]!=a[i+1])
printf("%d ",a[i]);
printf("\n");
}
}
printf("total: %d\n",cnt);
return 0;
}
| true |
7cb7b87a19fa92be98379956f717b7b9cbff35d5 | C++ | OverlordOvl/MemoryModificator | /op_in.cpp | UTF-8 | 251 | 2.578125 | 3 | [] | no_license | #include <vector>
#include <string>
// verification of the occurrence
bool op_in(const std::string &verifiable, std::vector<std::string> &root)
{
for (const auto& i: root)
{
if (verifiable == i) return true;
}
return false;
} | true |
e075e1f31cc16549e441f9f0884776d55ad4362d | C++ | DanMitroshin/Tech1 | /game1.0.0.cpp | UTF-8 | 9,019 | 3.359375 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <ctime>
#include <random>
#include <string>
using namespace std;
class Hero {
public:
Hero() {
doll = 0;
}
bool doll;
string status;
};
// Абстрактный базовый класс видов людей
class Worker {
public:
virtual void info() = 0;
virtual ~Worker() {}
};
// Классы всех видов людей
class GoodWorker: public Worker {
public:
void info() {
cout << "GoodWorker" << endl;
}
};
class BadWorker: public Worker {
public:
void info() {
cout << "BadWorker" << endl;
}
};
class ManagerWorker: public Worker {
public:
void info() {
cout << "ManagerWorker" << endl;
}
};
//Абстрактная фабрика(класс!!???) для создания действий после посещения рабочего места
class Actions {
public:
virtual void info() = 0;
virtual int consequence() = 0; //последствия после захода в рабочую точку
};
class BadStep: public Actions {
public:
void info() {
cout << "Вы зашли не туда и вас выкинули из офиса..." << endl;
}
int consequence() {
return 0;
}
};
class GoodStep: public Actions {
public:
void info() {
cout << "Весьма успешно. Можете дальше добираться до кабинета." << endl;
}
int consequence() {
return 1;
}
};
class VeryGoodStep: public Actions {
public:
void info() {
cout << "Вы попали к очень хорошему человеку!" << endl;
cout << "Он дал вам куклу, чтобы во время неверного шага вы могли подкинуть ее злому человеку." << endl;
cout << "Тогда из офиса он выкенет ее, а не вас!" << endl;
}
int consequence() {
return 3;
}
};
class WinStep: public Actions {
public:
void info() {
cout << "Вы добрались до цели! Мои поздравления." << endl;
}
int consequence() {
return 2;
}
};
class BlefGoodStep: public Actions {
public:
void info() {
cout << "Вы еще в офисе! Тут очень дружелюбный человек." << endl;
}
int consequence() {
string s;
cout << "Привет! Хочешь чаю? (yes/no)" << endl;
cin >> s;
while (s != "no" or s != "yes") {
if (s == "yes") {
cout << "Вы пьете чай и долго разговариваете." << endl;
cout << "Рабочий день подошел к концу. Офис закрылся, вас выгнали." << endl;
return 0;
} else if (s == "no") {
cout << "Ну что ты такой злой? Нельзя так.";
return 1;
} else {
cout << "Сотрудник не понял ваш ответ :(" << endl;
cin >> s;
}
}
}
};
// Абстрактная фабрика для производства рабочих мест
class WorkplaceFactory {
public:
virtual Worker* createWorker() = 0;
virtual Actions* createActions() = 0;
virtual ~WorkplaceFactory() {}
virtual void info() = 0;
};
// Фабрика для создания плохих рабочих мест
class BadWorkplace: public WorkplaceFactory {
public:
Worker* createWorker() {
return new BadWorker;
}
Actions* createActions() {
return new BadStep;
}
void info() {
cout << "BadWP";
}
};
// Фабрика для создания хороших рабочих мест
class GoodWorkplace: public WorkplaceFactory {
public:
Worker* createWorker() {
return new GoodWorker;
}
Actions* createActions() {
return new GoodStep;
}
void info() {
cout << "GoodWP";
}
};
// Фабрика для создания ОЧЕНЬ хороших рабочих мест
class VeryGoodWorkplace: public WorkplaceFactory {
public:
Worker* createWorker() {
return new GoodWorker;
}
Actions* createActions() {
return new VeryGoodStep;
}
void info() {
cout << "VGoodWP";
}
};
class WinWorkplace: public WorkplaceFactory {
public:
Worker* createWorker() {
return new ManagerWorker;
}
Actions* createActions() {
return new WinStep;
}
void info() {
cout <<"WinWP";
}
};
class TeaWorkplace: public WorkplaceFactory {
public:
Worker* createWorker() {
return new GoodWorker;
}
Actions* createActions() {
return new BlefGoodStep;
}
void info() {
cout << "TeaWP";
}
};
// Офис (класс), содержащий все виды рабочих мест
class Office{
public:
Office(Hero* h, int n, int m): h(*h), place(n) {}
~Office() {}
void info() {
for(int i = 0; i < place.size(); i++) {
for (int j = 0; j < place[i].size(); j++) {
place[i][j]->info();
cout << '|';
}
cout << endl;
}
}
vector< vector<WorkplaceFactory*> > place; //карта офиса
protected:
int n;
int m;
Hero& h;
};
// Здесь создается наш офис
class Game {
public:
Game(Hero* h1, int n, int m): h1(h1), n(n), m(m) {}
Office* createOffice() { //Пример создания офиса
srand(time(0));
Office* o1 = new Office(h1, n, m);
WorkplaceFactory* b = new BadWorkplace();
WorkplaceFactory* g = new GoodWorkplace();
WorkplaceFactory* vg = new VeryGoodWorkplace();
WorkplaceFactory* w = new WinWorkplace();
WorkplaceFactory* t = new TeaWorkplace();
for (int i = 0; i < n; i++) {
o1->place[0].push_back(b);
o1->place[m - 1].push_back(b);
}
for (int i = 1; i < m - 1; i++) {
o1->place[i].push_back(b);
if (i == 1) {
o1->place[i].push_back(w);
for (int j = 2; j < n - 1; j++) {
o1->place[i].push_back(g);
}
} else {
for (int j = 1; j < n - 1; j++) {
int index = rand() % 100;
if (index > 10 && index < 65) {
o1->place[i].push_back(g);
} else if (index > 64 && index < 75) {
o1->place[i].push_back(t);
} else if (index > 74) {
o1->place[i].push_back(b);
} else {
o1->place[i].push_back(vg);
}
}
}
o1->place[i].push_back(b);
}
return o1;
}
void play(Office& of) {
cout << "Привет. Ты попал в офис, где стремишься найти кабинет для прохождения собеседования." << endl;
cout << "Избегай того, чтобы тебя выкинули из офиса." << endl;
cout << "Для ходов по лабиринту используй команды:" << endl;
cout << "w - вперд(forward)" << endl;
cout << "s - назад(back)" << endl;
cout << "a - налево(left)" << endl;
cout << "d - направо(right)" << endl;
WorkplaceFactory* it;
int line;
int column;
line = 1;
column = m - 2;
it = of.place[line][column];
while (true) {
bool flag = 1;
char step;
cout << "Куда пойдем? ";
cin >> step;
cout << endl;
switch (step) {
case 'w':
line--;
break;
case 's':
line++;
break;
case 'a':
column--;
break;
case 'd':
column++;
break;
default:
flag = 0;
cout << "Ты видимо врезался в стенку... Давай еще раз" << endl;
break;
}
bool flag2 = 1;
if (flag == 1) {
it = of.place[line][column];
it->createActions()->info();
switch (it->createActions()->consequence()) {
case 0:
if (h1->doll == 0) {
flag2 = 0;
} else {
h1->doll = 0;
cout << "Но нет :) У вас же есть кукла. Вы спасаетесь, отдавая ее." << endl;
}
break;
case 1:
break;
case 2:
flag2 = 0;
break;
case 3:
if (h1->doll == 0){
h1->doll = 1;
} else {
cout << "Вы взяли сразу 2 куклы. Вам очень тяжело их носить с собой." << endl;
cout << "Но вы не хотите оставлять ни одну из них и остаетесь сидеть с ними в офисе." << endl;
cout << "В конце рабочего дня вас заставляют покинуть офис..." << endl;
flag2 = 0;
}
break;
}
//int act;
//act = *it;
}
if (flag2 == 0)
break;
}
}
Hero* h1;
protected:
int n;
int m; // size of office
};
int main(){
setlocale(LC_ALL, "Russian");
srand(time(0));
Hero* h1 = new Hero;
Game game(h1, 10, 10);
GoodWorkplace gf;
Office * of = game.createOffice();
game.play(* of);
cout << "Office:" << endl;
of->info();
return 0;
}
| true |
78260e4dcbaeb8c739788415d5f7253169d9dcf6 | C++ | trungtle/Project3-CUDA-Path-Tracer | /src/shaderProgram.cpp | UTF-8 | 3,349 | 2.71875 | 3 | [] | no_license | /*
* Adpated from OpenGL Tutorial: http://www.opengl-tutorial.org/beginners-tutorials/tutorial-2-the-first-triangle/
*/
#include "shaderProgram.h"
ShaderProgram::ShaderProgram(
const char* vertFilePath,
const char* fragFilePath
)
{
m_programID = glslUtility::LoadShaders(vertFilePath, fragFilePath);
m_unifModel = glGetUniformLocation(m_programID, "u_model");
m_unifViewProj = glGetUniformLocation(m_programID, "u_viewProj");
}
void
ShaderProgram::DrawBBox(
const Camera& camera,
const Geom& geom,
const BBoxVAO& geomVao
) const
{
glUseProgram(m_programID);
// Enable attributes
enableVertexAttributes(
geomVao.vao,
geomVao.posBuf,
geomVao.norBuf,
geomVao.colBuf,
geomVao.idxBuf
);
// Set uniforms
if (m_unifModel != -1) {
glUniformMatrix4fv(
m_unifModel,
1,
GL_FALSE,
&(geom.transform[0][0])
);
}
if (m_unifViewProj != -1) {
glUniformMatrix4fv(
m_unifViewProj,
1,
GL_FALSE,
&camera.GetViewProj()[0][0]
);
}
// Render
glDrawElements(
GL_LINES,
geomVao.elementCount,
GL_UNSIGNED_SHORT,
nullptr
);
disableVertexAttributes();
}
void
ShaderProgram::CleanUp()
{
glDeleteProgram(m_programID);
}
// ============== OpenGL Specifics ===================== //
void
enableVertexAttributes(
GLuint vao,
GLuint posBuffer,
GLuint norBuffer,
GLuint colBuffer,
GLuint indexBuffer
)
{
glBindVertexArray(vao);
// Enable vertex attributes
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, posBuffer);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);
glEnableVertexAttribArray(1);
glBindBuffer(GL_ARRAY_BUFFER, norBuffer);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);
glEnableVertexAttribArray(2);
glBindBuffer(GL_ARRAY_BUFFER, colBuffer);
glVertexAttribPointer(2, 4, GL_FLOAT, GL_FALSE, 0, (void*)0);
// Bind element buffer
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer);
}
void
disableVertexAttributes()
{
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, NULL);
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);
glDisableVertexAttribArray(2);
glBindBuffer(GL_ARRAY_BUFFER, NULL);
glBindVertexArray(NULL);
}
void
updateVAO(
GLuint vao,
GLuint posBuffer,
const std::vector<glm::vec3>& newPositions,
GLuint norBuffer,
const std::vector<glm::vec3>& newNormals,
GLuint colBuffer,
const std::vector<glm::vec4>& newColors,
GLuint indexBuffer,
const std::vector<GLushort>& newIndices
)
{
glBindVertexArray(vao);
// -- Position
glBindBuffer(GL_ARRAY_BUFFER, posBuffer);
glBufferData(
GL_ARRAY_BUFFER,
newPositions.size() * sizeof(glm::vec3),
&newPositions[0],
GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, NULL);
// -- Normals
glBindBuffer(GL_ARRAY_BUFFER, norBuffer);
glBufferData(
GL_ARRAY_BUFFER,
newNormals.size() * sizeof(glm::vec3),
&newNormals[0],
GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, NULL);
// -- Colors
glBindBuffer(GL_ARRAY_BUFFER, colBuffer);
glBufferData(
GL_ARRAY_BUFFER,
newColors.size() * sizeof(glm::vec4),
&newColors[0],
GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, NULL);
// -- Index
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer);
glBufferData(
GL_ELEMENT_ARRAY_BUFFER,
newIndices.size() * sizeof(GLushort),
&newIndices[0],
GL_STATIC_DRAW
);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, NULL);
glBindVertexArray(NULL);
}
| true |
52990feb5f15ffc2b307d635afcf38c8e961b763 | C++ | xlu29466/TCI | /TCI/TDIC.cpp | UTF-8 | 23,064 | 2.59375 | 3 | [] | no_license | /*
* File: TDIC.cpp
* Author: Kevin Lu
*
* Created on April 25, 2015, 6:13 PM
*/
using namespace std;
#include "TDIC.h"
#include <fstream>
#include <math.h>
#include <iostream>
#include <fstream>
#include <string.h>
#include <string>
#include <vector>
#include <sstream>
#include <stdio.h>
#include <stdlib.h>
#include <float.h>
#include <algorithm>
/**
* This function performs tumor-specific driver identification. It calculate the causal score for all
* GT-vs-GE pairs observed in a given tumor, populate a GT-by-GE score matrix and output to file.
* @param gtMatrix An TDIMatrix reference, in which SGA data of a collection of tumors are stored
* in a tumor-by-gene matrix
* @param geMatrix An TDIMatrix reference, in which DEG data of a collection of tumors are stored
* in a tumor-by-gene matrix
* @param mapGlobDrivers A reference to a dictionary of global drivers of DEGs in the "geMatrix",
Each entry is keyed by the DEG gene name, and the value is a reference of a
vector<string> containing the two 2 global driver.
* @param tumorID The tumor to be process
*/
void TDIC(GTMatrix& gtMatrix, TDIMatrix& geMatrix, map<string,
vector<string> > & mapGlobDrivers, const int tumorID, const string outPath, const float v0){
// initializations
string curTumorName = gtMatrix.getTumorNameById(tumorID);
// Find the GTs and GEs of the current tumor
vector<int> tumorGtIndices, tumorGeIndices;
gtMatrix.findGeneWithOnesInTumor(tumorID, tumorGtIndices);
geMatrix.findGeneWithOnesInTumor(tumorID, tumorGeIndices);
bool* gtDataMatrix = gtMatrix.getMatPtr();
bool* geDataMatrix = geMatrix.getMatPtr();
float* priorMatrix = gtMatrix.getPriorPtr();
// Find the global drivers corresponding to the
vector<int> tumorGlobDriverIndices1, tumorGlobDriverIndices2;
//map <string, string> globalDriversMap;
if (!getDEGGlobDriverIndices(gtMatrix, geMatrix, mapGlobDrivers, tumorGeIndices, tumorGlobDriverIndices1, tumorGlobDriverIndices2))
{
cout << "Error occurred when retrieving global drivers";
}
// Allocate memory for nGT x nGE matrix
unsigned int nGT = tumorGtIndices.size();
unsigned int nGE = tumorGeIndices.size();
int nTumors = gtMatrix.getNTumors();
if (nTumors != geMatrix.getNTumors()) // number of tumors should agree between gtMatrix and geMatrix
{
cerr << "Bug: gtMatrix and geMatrix contain different number of tumors ";
}
cout << "Processing tumor " << curTumorName << " with " << nGT << " GAs, and " << nGE << " GEs" << "\n";
/*Get names of mutated GTs and GEs for this tumor
*/
vector<string> gtNames;
vector<string> geNames;
gtMatrix.getGeneNamesByIndices(tumorGtIndices, gtNames);
geMatrix.getGeneNamesByIndices(tumorGeIndices, geNames);
float* tumorPosteriorMatrix = new float[nGT * nGE]();
// loop through each GE
#pragma omp parallel for
for(unsigned int ge = 0; ge < nGE; ge++)
{
float normalizer = 0;
unsigned int curGeIndx = tumorGeIndices[ge];
unsigned int rowStartForGE = curGeIndx * nTumors;
// find the globDriver for this give ge
unsigned int curGDriverIndx = tumorGlobDriverIndices1[ge]; //curGDriverIndx is found by ge indx
unsigned int rowStartForGlobDriver = curGDriverIndx * nTumors;
// loop through each GT in the tumor
for (unsigned int gt = 0; gt < nGT; gt++)
{
// we use a binary tree to keep the statistics
float T[2] = {0.0};
float TE[4] = {0.0};
float TD[4] = {0.0};
float TDE[8] = {0.0};
int curGTIndx = tumorGtIndices[gt];
int gtRowStart = curGTIndx * nTumors;
//Check if current gt is the same as GD, if yes, switch GD
if (curGTIndx == curGDriverIndx){
unsigned int GD2Indx = tumorGlobDriverIndices2[ge];
rowStartForGlobDriver = GD2Indx * nTumors;
}
float gtPrior;
if (priorMatrix[gtRowStart + tumorID] == 0)
{
gtPrior = -FLT_MAX;
}
else
{
gtPrior = log(priorMatrix[gtRowStart + tumorID]);
}
for(int t = 0; t < nTumors; t++)
{
int tVal = gtDataMatrix[gtRowStart + t];
int eVal = geDataMatrix[rowStartForGE + t];
int dVal = gtDataMatrix[rowStartForGlobDriver + t];
//TDE[0xTDE] T is the gt value, D is the global driver value, E is the ge value
//e.g. TDE[7] means TDE[0x110] save the count when T=1 and D=1 and E=1
TDE[tVal*4+dVal*2+eVal]++;
}
//TD[0xTD] T is the gt value, D is the global driver value
//e.g. TD[2] means TD[ox10] save the count when T=1 D=0
TD[0] = TDE[0] + TDE[1]; //T0D0 = T0D0E0 + T0D0E1
TD[1] = TDE[2] + TDE[3]; //T0D1 = T0D1E0 + T0D1E1
TD[2] = TDE[4] + TDE[5]; //T1D0 = T1D0E0 + T1D0E1
TD[3] = TDE[6] + TDE[7]; //T0D1 = T1D1E0 + T1D1E1
//TE[0xTE]] T is the gt value, E is the ge value
//e.g. TE[3] means TE[0x11] save the count when T=1 and E=1
TE[0] = TDE[0] + TDE[2]; //T0E0 = T0D0E0 + T0D1E0
TE[1] = TDE[1] + TDE[3]; //T0E1 = T0D0E1 + T0D1E1
TE[2] = TDE[4] + TDE[6]; //T1E0 = T1D0E0 + T1D1E0
TE[3] = TDE[5] + TDE[7]; //T1E1 = T1D0E1 + T1D1E1
//T[0xT] T is the gt value
//e.g. T[1] save the count when gt value T = 1
T[0] = TE[0] + TE[1]; //T0 = T0E0 + T0E1
T[1] = TE[2] + TE[3]; //T1 = T1E0 + T1E1
//Therr is no count for T0ge0, T0ge1 and T0
TE[0]=TE[1] = 0.0;
T[0] = 0.0;
float TFscore;
if(curGTIndx == 0)
{
//TFscore = calcA0Fscore(T1, T1ge1, T1ge0, T0, T0ge1, T0ge0);
TFscore = calcA0Fscore(T[1], TE[3], TE[2], T[0], TE[1], TE[0]);
}
else
{
//TFscore = calcFscore( T1, T1ge1, T1ge0, T0, T0ge1, T0ge0 );
TFscore = calcFscore( T[1], TE[3], TE[2], T[0], TE[1], TE[0] );
}
//float DFscore = calcFscore( D1, D1ge1, D1ge0, D0, D0ge1, D0ge0 );
float DFscore = calcFscore( TD[1], TDE[3], TDE[2], TD[0], TDE[1], TDE[0] );
float lnData = TFscore + DFscore + gtPrior;
tumorPosteriorMatrix[gt * nGE + ge] = lnData;
float pGT1GE1, pGT0GE1;
if(gt == 0)
{
pGT1GE1 = (ALPHANULL + TE[3]) / (ALPHANULL + ALPHANULL + T[1]);
pGT0GE1 = (ALPHANULL + TDE[1] + TDE[3]) / (ALPHANULL + ALPHANULL + nTumors - T[1]);
}
else
{
pGT1GE1 = (ALPHAIJK11 + TE[3]) / (ALPHAIJK11 + ALPHAIJK10 + T[1]);
pGT0GE1 = (ALPHAIJK01 + TDE[1] + TDE[3]) / (ALPHAIJK01 + ALPHAIJK00 + nTumors - T[1]);
}
/*
// the following lines remove the SNPs that has lower panetration rate than population baseline prevalence.
// Comment it out to compare results on 08/27/2021
if(pGT1GE1 <= pGT0GE1)
{
tumorPosteriorMatrix[gt* nGE + ge] = -FLT_MAX;
}
*/ // restore GD after processing current gt == GD
if (curGTIndx == curGDriverIndx)
rowStartForGlobDriver = curGDriverIndx * nTumors;
}
for(unsigned int gt = 0; gt < nGT; gt++)
{
if(gt == 0)
{
normalizer = tumorPosteriorMatrix[gt * nGE + ge];
}
else
{
normalizer = logSum(normalizer, tumorPosteriorMatrix[gt * nGE + ge]);
}
}
// finished populating a column of GTs with respect to a given GE, normalize so that the column sum to 1
for (unsigned int gt = 0; gt < nGT; gt++)
tumorPosteriorMatrix[gt * nGE + ge] = exp(tumorPosteriorMatrix[gt * nGE + ge] - normalizer);
}
// save results to file
string outFileName;
if (*outPath.end() != '/')
{
outFileName = outPath + "/" + curTumorName + ".csv";
}
else
{
outFileName = outPath + curTumorName + ".csv";
}
//ofstream file;
ofstream outFile;
try
{
outFile.open(outFileName.c_str());
}
catch(ofstream::failure e)
{
cout << "Exception opening output file. Please ensure you have an existing directory for file.\n";
}
//start writing CSV representation of TDIMatrix
//write column headers
for(int i = 0; i < nGE; i++)
{
outFile << "," << geNames[i];
}
outFile << "\n";
for(int i = 0; i < nGT; i++)
{
outFile << gtNames[i];
for(int j = 0; j < nGE; j++)
{
outFile << "," << tumorPosteriorMatrix[i * nGE + j];
}
outFile << "\n";
}
outFile.close();
delete [] tumorPosteriorMatrix;
}
/**
* This function calculate marginal likelihood using TDI algorithm. It calculate the causal score for all
* GT-vs-GE pairs observed in a given tumor, populate a GT-by-GE score matrix and output to file.
* @param gtMatrix An TDIMatrix reference, in which SGA data of a collection of tumors are stored
* in a tumor-by-gene matrix
* @param geMatrix An TDIMatrix reference, in which DEG data of a collection of tumors are stored
* in a tumor-by-gene matrix
* @param mapGlobDrivers A reference to a dictionary of global drivers of DEGs in the "geMatrix",
Each entry is keyed by the DEG gene name, and the value is a reference of a
vector<string> containing the two 2 global driver.
*/
void TDIC_marginal(GTMatrix& gtMatrix, TDIMatrix& geMatrix, map<string,
vector<string> >& mapGlobDrivers, const string outPath, const float v0)
{
// initializations
bool* gtDataMatrix = gtMatrix.getMatPtr();
bool* geDataMatrix = geMatrix.getMatPtr();
// Allocate memory for nGT x nGE matrix
unsigned int nGT = gtMatrix.getNGenes();
unsigned int nGE = geMatrix.getNGenes();
int nTumors = gtMatrix.getNTumors();
if (nTumors != geMatrix.getNTumors()) // number of tumors should agree between gtMatrix and geMatrix
{
cerr << "Bug: gtMatrix and geMatrix contain different number of tumors ";
}
float* priorMatrix = gtMatrix.getPriorPtr();
/*Get names of all GE and GTs */
vector<string> geNames = geMatrix.getGeneNames();
vector<string> gtNames = gtMatrix.getGeneNames();
// Populate the global drivers corresponding to the GEs
vector<int> tumorGeIndices;
for (int i = 0; i < nGE; i++)
{
tumorGeIndices.push_back(i);
}
// Declare 2 vectors to hold the 1st and 2nd global drivers for DEGs
vector<int> tumorGlobDriverIndices1, tumorGlobDriverIndices2;
//map <string, string> globalDriversMap;
if (!getDEGGlobDriverIndices(gtMatrix, geMatrix, mapGlobDrivers, tumorGeIndices, tumorGlobDriverIndices1, tumorGlobDriverIndices2))
{
cout << "Error occurred when retrieving global drivers";
}
// allocate memory to hold the matrix
float* tumorPosteriorMatrix = new float[nGT * nGE]();
// loop through each GE
#pragma omp parallel for
for(unsigned int ge = 0; ge < nGE; ge++)
{
float normalizer = 0;
unsigned int curGeIndx = ge;
unsigned int rowStartForGE = curGeIndx * nTumors;
// find the globDriver for this give ge
unsigned int curGDriverIndx = tumorGlobDriverIndices1[ge]; //curGDriverIndx is found by ge indx
unsigned int rowStartForGlobDriver = curGDriverIndx * nTumors;
// loop through each GT in the tumor
for (unsigned int gt = 0; gt < nGT; gt++)
{
//Check if current gt is the same as GD, if yes, switch GD
unsigned int oldRowStartForGlobDriver = rowStartForGlobDriver;
if (gt == curGDriverIndx){
unsigned int GD2Indx = tumorGlobDriverIndices2[ge];
rowStartForGlobDriver = GD2Indx * nTumors;
}
// we use a binary tree to keep the statistics
float T[2] = {0.0};
float TE[4] = {0.0};
float TD[4] = {0.0};
float TDE[8] = {0.0};
int curGTIndx = gt; //This is special case because we are going through all GTs
int gtRowStart = curGTIndx * nTumors;
for(int t = 0; t < nTumors; t++)
{
int tVal = gtDataMatrix[gtRowStart + t];
int eVal = geDataMatrix[rowStartForGE + t];
int dVal = gtDataMatrix[rowStartForGlobDriver + t];
//TDE[0xTDE] T is the gt value, D is the global driver value, E is the ge value
//e.g. TDE[7] means TDE[0x110] save the count when T=1 and D=1 and E=1
TDE[tVal*4+dVal*2+eVal]++;
}
//TD[0xTD] T is the gt value, D is the global driver value
//e.g. TD[2] means TD[ox10] save the count when T=1 D=0
TD[0] = TDE[0] + TDE[1]; //T0D0 = T0D0E0 + T0D0E1
TD[1] = TDE[2] + TDE[3]; //T0D1 = T0D1E0 + T0D1E1
TD[2] = TDE[4] + TDE[5]; //T1D0 = T1D0E0 + T1D0E1
TD[3] = TDE[6] + TDE[7]; //T0D1 = T1D1E0 + T1D1E1
//TE[0xTE]] T is the gt value, E is the ge value
//e.g. TE[3] means TE[0x11] save the count when T=1 and E=1
TE[0] = TDE[0] + TDE[2]; //T0E0 = T0D0E0 + T0D1E0
TE[1] = TDE[1] + TDE[3]; //T0E1 = T0D0E1 + T0D1E1
TE[2] = TDE[4] + TDE[6]; //T1E0 = T1D0E0 + T1D1E0
TE[3] = TDE[5] + TDE[7]; //T1E1 = T1D0E1 + T1D1E1
//T[0xT] T is the gt value
//e.g. T[1] save the count when gt value T = 1
T[0] = TE[0] + TE[1]; //T0 = T0E0 + T0E1
T[1] = TE[2] + TE[3]; //T1 = T1E0 + T1E1
//Therr is no count for T0ge0, T0ge1 and T0
TE[0]=TE[1] = 0.0;
T[0] = 0.0;
float TFscore;
if(curGTIndx == 0)
{
//TFscore = calcA0Fscore(T1, T1ge1, T1ge0, T0, T0ge1, T0ge0);
TFscore = calcA0Fscore(T[1], TE[3], TE[2], T[0], TE[1], TE[0]);
}
else
{
//TFscore = calcFscore( T1, T1ge1, T1ge0, T0, T0ge1, T0ge0 );
TFscore = calcFscore( T[1], TE[3], TE[2], T[0], TE[1], TE[0] );
}
//float DFscore = calcFscore( D1, D1ge1, D1ge0, D0, D0ge1, D0ge0 );
float DFscore = calcFscore( TD[1], TDE[3], TDE[2], TD[0], TDE[1], TDE[0] );
float lnData = TFscore + DFscore;
tumorPosteriorMatrix[gt * nGE + ge] = lnData;
float pGT1GE1, pGT0GE1;
if(gt == 0)
{
pGT1GE1 = (ALPHANULL + TE[3]) / (ALPHANULL + ALPHANULL + T[1]);
pGT0GE1 = (ALPHANULL + TDE[1] + TDE[3]) / (ALPHANULL + ALPHANULL + nTumors - T[1]);
}
else
{
pGT1GE1 = (ALPHAIJK11 + TE[3]) / (ALPHAIJK11 + ALPHAIJK10 + T[1]);
pGT0GE1 = (ALPHAIJK01 + TDE[1] + TDE[3]) / (ALPHAIJK01 + ALPHAIJK00 + nTumors - T[1]);
}
/*
// the following lines remove the SNPs that has lower panetration rate than population baseline prevalence.
// Comment it out to compare results on 08/27/2021
if(pGT1GE1 <= pGT0GE1)
{
tumorPosteriorMatrix[gt* nGE + ge] = -FLT_MAX;
}
*/ // restore GD after processing current gt == GD
if (gt == curGDriverIndx)
rowStartForGlobDriver = oldRowStartForGlobDriver;
}
}
// save results to file
string outFileName;
if (*outPath.end() != '/')
{
outFileName = outPath + "/" + "ICI_discrete_all_marginal" + ".csv";
}
else
{
outFileName = outPath + "ICI_discrete_all_marginal" + ".csv";
}
//ofstream file;
ofstream outFile;
try
{
outFile.open(outFileName.c_str());
}
catch(ofstream::failure e)
{
cout << "Exception opening output file. Please ensure you have an existing directory for file.\n";
}
//start writing CSV representation of TDIMatrix
//write column headers
for(int i = 0; i < nGE; i++)
{
outFile << "," << geNames[i];
}
outFile << "\n";
for(int i = 0; i < nGT; i++)
{
outFile << gtNames[i];
for(int j = 0; j < nGE; j++)
{
outFile << "," << tumorPosteriorMatrix[i * nGE + j];
}
outFile << "\n";
}
outFile.close();
delete [] tumorPosteriorMatrix;
}
/**
* This function parse the text file that list top 2 global drivers for each of
* DEGs observed in a DEG matrix.
* @param A string fileName
* @return A boolean value indicating the success
*/
bool parseGlobDriverDict(string fileName, map<string, vector<string> > & globDriverMap){
ifstream inFileStream;
string line;
vector<string> fields;
vector<string> drivers;
try {
inFileStream.open(fileName.c_str());
while(getline(inFileStream, line))
{
line.erase(std::remove(line.begin(), line.end(), '\n'), line.end());
line.erase(std::remove(line.begin(), line.end(), '\r'), line.end());
fields = split(line, ',');
drivers.push_back(fields.at(1));
drivers.push_back(fields.at(2));
globDriverMap.insert(std::pair<string, vector<string> > (fields.at(0), drivers));
}
inFileStream.close();
}
catch (ifstream::failure e) {
cout << "Fail to open file " << fileName;
return false;
}
return true;
}
/**
* Split a string by a given delimiter.
* @param s String to be split.
* @param delim Single character delimiter by which to split the string.
* @param elems List containing each split substring of 's' split by 'delim'.
* @return
*/
std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) {
std::stringstream ss(s);
std::string item;
while (std::getline(ss, item, delim)) {
elems.push_back(item);
}
return elems;
}
/**
* This split function calls '&split'. User calls this function.
* @param s String to be split by 'delim'.
* @param delim Character delimiter to split the string 's'.
* @return List of substrings resulting from the split.
*/
std::vector<std::string> split(const std::string &s, char delim) {
std::vector<std::string> elems;
split(s, delim, elems);
return elems;
}
/**
*
* @param gtMat GT matr
* @param geMat
* @param mapGlobDrivers
* @param inDEGIndices
* @param OutGlobDriverVec
* @return
*/
bool getDEGGlobDriverIndices(GTMatrix& gtMat, TDIMatrix& geMat, map<string, vector<string> >& mapGlobDrivers,
vector<int>& inDEGIndices, vector<int>& OutGlobDriverVec1, vector<int>& OutGlobDriverVec2)
{
/*
* First we must get the names of the DEGs corresponding to the indices in "inDEGIndices".
* Then, using these DEG names, we can access their global driver through our map "mapGlobDrivers"
* and push them onto 'OutGlobDriverVec'.
*/
//cout << "Inside getDEGGlobDriver.\n";
vector<string> inDEGNames;
geMat.getGeneNamesByIndices(inDEGIndices, inDEGNames);
vector<string> globalDriverNames1, globalDriverNames2;
for(int i = 0; i < inDEGNames.size(); i++)
{
string geneName = inDEGNames[i];
vector<string> topDrivers = mapGlobDrivers[geneName];
globalDriverNames1.push_back(topDrivers[0]);
globalDriverNames2.push_back(topDrivers[1]);
}
gtMat.getGeneIndicesByNames(globalDriverNames1, OutGlobDriverVec1);
gtMat.getGeneIndicesByNames(globalDriverNames2, OutGlobDriverVec2);
return true;
}
/********** logSum *********************************************************/
/**
* Evaluate Ln(x + y)
* @param lnx ln(x)
* @param lny ln(y)
* @return ln(x + y)
*/
float logSum(float lnx, float lny){
float maxExp = -4950.0;
if(lny > lnx){
float tmp = lnx;
lnx = lny;
lny = tmp;
}
float lnyMinusLnX = lny - lnx;
float lnXplusLnY;
if(lnyMinusLnX < maxExp)
lnXplusLnY = lnx;
else
lnXplusLnY = log(1 + exp(lnyMinusLnX)) + lnx;
return (lnXplusLnY);
}
/***************** calcSingleGtFscore **************************************/
/**
*
* @param gt1
* @param gt1ge1
* @param gt1ge0
* @param gt0
* @param gt0ge1
* @param gt0ge0
* @return
*/
float calcFscore(float gt1, float gt1ge1, float gt1ge0,
float gt0, float gt0ge1, float gt0ge0 )
{
// Calculation of Equation 7
float glnNi0 = lgamma(ALPHAIJK00 + ALPHAIJK01) - lgamma(gt0 + ALPHAIJK00 + ALPHAIJK01);
float glnNi1 = lgamma(ALPHAIJK10 + ALPHAIJK11) - lgamma(gt1 + ALPHAIJK10 + ALPHAIJK11);
float fscore = glnNi0 + glnNi1;
fscore += lgamma(gt0ge0 + ALPHAIJK00) - lgamma(ALPHAIJK00);
fscore += lgamma(gt0ge1 + ALPHAIJK01) - lgamma(ALPHAIJK01);
fscore += lgamma(gt1ge0 + ALPHAIJK10) - lgamma(ALPHAIJK10);
fscore += lgamma(gt1ge1 + ALPHAIJK11) - lgamma(ALPHAIJK11);
return (fscore);
}
/***************** calcSingleGtFscore **************************************/
/**
*
* @param gt1
* @param gt1ge1
* @param gt1ge0
* @param gt0
* @param gt0ge1
* @param gt0ge0
* @return
*/
float calcA0Fscore(float gt1, float gt1ge1, float gt1ge0,
float gt0, float gt0ge1, float gt0ge0 )
{
// Calculation of Equation 7
float glnNi0 = lgamma( ALPHANULL + ALPHANULL) - lgamma(gt0 + ALPHANULL + ALPHANULL);
float glnNi1 = lgamma(ALPHAIJK10 + ALPHANULL) - lgamma(gt1 + ALPHANULL + ALPHANULL);
float fscore = glnNi0 + glnNi1;
fscore += lgamma(gt0ge0 + ALPHANULL) - lgamma(ALPHANULL);
fscore += lgamma(gt0ge1 + ALPHANULL) - lgamma(ALPHANULL);
fscore += lgamma(gt1ge0 + ALPHANULL) - lgamma(ALPHANULL);
fscore += lgamma(gt1ge1 + ALPHANULL) - lgamma(ALPHANULL);
return (fscore);
}
| true |
4d06088eea5cfda964083c0a20354bc4818c6a5b | C++ | caixiaomo/leetcode-ans1 | /leetcode C++/DP/2D/Interleaving_String/Interleaving_String.cpp | UTF-8 | 1,489 | 2.953125 | 3 | [] | no_license | class Solution {
public:
bool isInterleave(string s1, string s2, string s3) {
// Note: The Solution object is instantiated only once and is reused by each test case.
int size1 = s1.size();
int size2 = s2.size();
int size3 = s3.size();
vector<vector<bool>> matrix(size1 + 1, vector<bool>(size2 + 1,false));//= new matrix();
matrix[0][0] = true;
if(size1 + size2 != size3){
return false;
}
//init
for(int i = 0; i < size1; i++){
if(s1[i] == s3[i]){
matrix[i + 1][0] = matrix[i][0];
}else
break;
}
for(int i = 0; i < size2; i++){
if(s2[i] == s3[i]){
matrix[0][i + 1] = matrix[0][i];
}else
break;
}
//dp
for(int i = 0; i < size1; i++){
for(int j = 0; j < size2; j++){
if(s1[i] == s3[i + j + 1]){ //since when i = j =0, s3[i + j] has been checked, so we need to check from i + j + 1;
if(matrix[i][j+1] == true){ //matrix[i][j+1] means s3[i+j+1-1]
matrix[i+1][j+1] = true;
}
}
if(s2[j] == s3[i + j + 1]){
if(matrix[i+1][j] == true){
matrix[i+1][j+1] = true;
}
}
}
}
return matrix[size1][size2];
}
}; | true |
d042dfc4d938e207bf0f21a8871751bf6897383c | C++ | StanPlatinum/idash-sgx-bench | /mojo-cnn_demo/examples/parser/imagenet_parser.cpp | UTF-8 | 2,646 | 2.78125 | 3 | [
"MIT"
] | permissive | #include <vector>
#include <iostream>
#include "imagenet_parser.h"
using namespace std;
using namespace imagenet;
std::string data_path="./testdata/";
int main(int argc, char *argv[])
{
//int width, height;
vector<vector<float>> train_records;
vector<int> train_labels;
vector<vector<float>> test_records;
vector<int> test_labels;
if (!parse_train_data(data_path, train_records, train_labels)) {
std::cerr << "error: could not parse the sample data.\n";
return 1;
}
if (!parse_test_data(data_path, test_records, test_labels)) {
std::cerr << "error: could not parse the sample data.\n";
return 1;
}
cout << "=================" << endl;
ofstream out("output.txt");
/* deal with train_labels */
cout << "reading labels...";
for (int i = 0; i < train_labels.size(); ++i)
{
cout << i << endl;
}
/* deal with train_records */
vector<float> tmp_vector;
if (out.is_open())
{
out << "This is the first line.\n";
}
cout << "reading records..." << endl;
cout << "writting records..." << endl;
//for (vector<vector<float>>::iterator ite = train_records.begin(); ite != train_records.end(); ++ite)
for (int i = 0; i < train_records.size(); ++i)
{
tmp_vector = train_records[i];
int ln = 0;
out << "row 0: ";
for (vector<float>::iterator itee = tmp_vector.begin(); itee != tmp_vector.end(); itee++){
//cout every 113 elements
ln++;
out << *itee << " ";
if (ln % 113 == 0){
out << "\n";
// the last line should be: "row 113:"
out << "row " << ln/113 << ": ";
}
}
out << endl;
}
/* deal with test_labels */
cout << "reading labels...";
for (int i = 0; i < test_labels.size(); ++i)
{
cout << i << endl;
}
/* deal with test_records */
//vector<float> tmp_vector;
cout << "reading records..." << endl;
cout << "writting records..." << endl;
//for (vector<vector<float>>::iterator ite = train_records.begin(); ite != train_records.end(); ++ite)
for (int i = 0; i < test_records.size(); ++i)
{
tmp_vector = test_records[i];
int ln = 0;
out << "row 0: ";
for (vector<float>::iterator itee = tmp_vector.begin(); itee != tmp_vector.end(); itee++){
//cout every 113 elements
ln++;
out << *itee << " ";
if (ln % 113 == 0){
out << "\n";
// the last line should be: "row 113:"
out << "row " << ln/113 << ": ";
}
}
out << endl;
}
/* finished */
out.close();
return 0;
}
| true |
41ce426fe0fba0e52d04445e37d72ff4211e93cd | C++ | Mozenn/SDLGame | /SDLGame/Source/UI/Button.cpp | UTF-8 | 2,297 | 3.015625 | 3 | [] | no_license | #include "Button.h"
Button::Button()
{
}
Button::~Button()
{
free();
}
void Button::free()
{
mTexture->free();
mText->free();
}
void Button::render(int x, int y, SDL_Rect* clip , double angle , SDL_Point* center , SDL_RendererFlip flip )
{
mTexture->render(x,y,clip,angle,center,flip);
if (mText != nullptr)
{
mText->render(x, y, clip, angle, center, flip);
}
}
void Button::renderAtPosition(SDL_Rect* clip , double angle , SDL_Point* center , SDL_RendererFlip flip )
{
mTexture->renderAtPosition( clip, angle, center, flip);
if (mText != nullptr)
{
mText->renderAtPosition(clip, angle, center, flip);
}
}
bool Button::isPushed(SDL_Event* e)
{
bool result = false;
if (e->type == SDL_MOUSEBUTTONUP)
{
//Get mouse position
int x, y;
SDL_GetMouseState(&x, &y);
if (x >= mTexture->getXPosition() && x <= mTexture->getYPosition() + mTexture->getWidth() && y >= mTexture->getYPosition() && y <= mTexture->getYPosition() + mTexture->getHeight())
{
result = true;
}
}
return result;
}
bool Button::isHovered()
{
bool result = false;
//Get mouse position
int x, y;
SDL_GetMouseState(&x, &y);
if (x >= mTexture->getXPosition() && x <= mTexture->getXPosition() + mTexture->getWidth() && y >= mTexture->getYPosition() && y <= mTexture->getYPosition() + mTexture->getHeight())
{
result = true;
}
return result;
}
bool Button::loadSprite(std::string path)
{
return mTexture->load(path);
}
bool Button::loadText(std::string textureText, SDL_Color textColor, TTF_Font *font)
{
return mText->load(textureText, textColor, font);
}
Sprite* Button::getSprite() const
{
return mTexture;
}
TextSprite* Button::getText() const
{
return mText;
}
void Button::setSprite(Sprite* texture)
{
mTexture = texture;
}
void Button::setTextSprite(TextSprite* text)
{
mText = text;
}
void Button::setTextureColor(Uint8 red, Uint8 green, Uint8 blue)
{
mTexture->setColor(red, green, blue);
}
void Button::setTextureAlpha(Uint8 alpha)
{
mTexture->setAlpha(alpha);
}
void Button::setText(std::string text)
{
mText->setText(text);
}
void Button::setTextColor(Uint8 red, Uint8 green, Uint8 blue)
{
if (mText)
{
mText->setColor(red, green, blue);
}
}
void Button::setTextAlpha(Uint8 alpha)
{
if (mText)
{
mText->setAlpha(alpha);
}
} | true |
c0aa3d6410ccec79227c42fb3d1b2321707cc50d | C++ | JournKim/BOJ | /1813_마지막_한마디.cpp | UTF-8 | 288 | 2.75 | 3 | [] | no_license | #include<iostream>
using namespace std;
int table[100002] = { 0, };
int main()
{
int n,a;
cin >> n;
for (int i = 0; i < n; i++)
{
scanf("%d", &a);
table[a]++;
}
int max = -1;
for (int i = 0; i <= n; i++)
{
if (i == table[i])
{
max = i;
}
}
cout << max << endl;
} | true |
253843b284580af6d5510dcd9c2ef02659bc3e39 | C++ | mcaiox/BankAccounts | /Account.cpp | WINDOWS-1252 | 534 | 3.34375 | 3 | [] | no_license | #include "Account.h"
using namespace std;
Account::Account(double balance){
deposit(balance);
}
void Account::setInterest(double interestRate) {
interest = interestRate;
}
double Account::getInterest(){
return interest;
}
void Account::deposit(double amount)
{
if (amount >= 1.0)
balance += amount;
else
throw invalid_argument("Account cannot be opened without a minimum deposit of 1.00");
}
void Account::withdraw(double amount)
{
balance -= amount;
}
double Account::getBalance() { return balance; }
| true |
16952c509001504f7b4cd32dd8e95fa306d15a76 | C++ | Arunpar/C-Program | /Pattern_Of_Alphabets.cpp | UTF-8 | 274 | 2.796875 | 3 | [] | no_license | #include<iostream>
using namespace std;
main()
{
int row,col,num;
char c='A';
cout<<"Enter the Number : ";
cin>>num;
for(row=1;row<=num;row++)
{
for(col=1;col<=row;col++)
{
cout<<" "<<c;
c=c+1;
}
cout<<"\n";
c='A';
}
return 0;
}
| true |
278f3b05366c991981c7f2cdd070e9b87940d6ff | C++ | TheRemote/BattleCity-Classic | /Client/CExplode.h | UTF-8 | 816 | 2.9375 | 3 | [] | no_license | #ifndef __CEXPLODE__
#define __CEXPLODE__
#include "CGame.h"
class CGame;
class CExplosion
{
public:
CGame *p;
int X, Y;
int Type;
int Animation;
__int64 tick;
CExplosion *next;
CExplosion *prev;
CExplosion(int X, int Y, int Type, CGame *Game)
{
p = Game;
this->X = X;
this->Y = Y;
this->Type = Type;
this->Animation = 0;
this->tick = 0;
prev = 0;
next = 0;
}
~CExplosion()
{
if (next)
next->prev = prev;
if (prev)
prev->next = next;
}
};
class CExplosionList
{
public:
CExplosion *explosions;
CExplosion *newExplosion(int X, int Y, int Type);
CExplosion *delExplosion(CExplosion *del);
CExplosionList(CGame *game)
{
p = game;
explosions = 0;
}
~CExplosionList()
{
while (explosions)
delExplosion(explosions);
}
void Cycle();
CGame *p;
};
#endif | true |
83b34de00eec469b1ba3d406bb3fa74c99680463 | C++ | Grarak/Pong-Cpp | /point.cpp | UTF-8 | 1,469 | 2.78125 | 3 | [
"Apache-2.0"
] | permissive | /*
* Copyright (C) 2015 Willi Ye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <SFML/Graphics.hpp>
#include "point.h"
Point* Point::getInstance(Player player)
{
Point* point = new Point();
point->player = player;
return point;
}
void Point::draw(sf::RenderWindow* window, int screenWidth, int screenHeight)
{
sf::Font font;
if (!font.loadFromFile("/etc/alternatives/fonts-japanese-gothic.ttf")) return;
double w = 0;
switch (player)
{
case ONE:
w = screenWidth / 4;
break;
case TWO:
w = screenWidth - screenWidth / 4;
break;
}
char buf[100];
sprintf(buf, "%d", point);
sf::Text text;
text.setFont(font);
text.setString(strdup(buf));
text.setCharacterSize(30);
text.setPosition(w, 40);
text.setColor(sf::Color::White);
window->draw(text);
}
| true |
9143acf335f1980c5354ff4a849f0c01786a3261 | C++ | sarahkittyy/ScriptableTCP | /include/State/State.hpp | UTF-8 | 1,176 | 3.328125 | 3 | [
"MIT"
] | permissive | #pragma once
#include <SFML/Graphics.hpp>
#include <memory>
/**
* @brief A program state.
* Contains methods to draw what it needs to, as well as
* update it per frame.
*
*/
class State
{
public:
/**
* @brief Construct a new State object
*
* @param window The SFML window to draw to.
*/
State(sf::RenderWindow& window, std::unique_ptr<State>& main_state);
/**
* @brief Destroy the State object
*
*/
virtual ~State();
/**
* @brief Update the state.
*
*/
virtual void updateFrame() = 0;
/**
* @brief Draw SFML components.
*
*/
virtual void drawSFML() = 0;
/**
* @brief Draw ImGui components.
*
*/
virtual void drawImGui() = 0;
protected:
/**
* @brief Return the internal window. Used for child objects.
*
* @return sf::RenderWindow& A reference to mWindow.
*/
sf::RenderWindow& window();
/**
* @brief Returns a reference to the program state, to change it.
*
*/
std::unique_ptr<State>& state();
private:
/**
* @brief The internal window to draw to.
*
*/
sf::RenderWindow& mWindow;
/**
* @brief A reference to the main program state.
*
*/
std::unique_ptr<State>& mMainState;
}; | true |
c72940783fec1b6d0c0fc79173d98b06cfa49f2b | C++ | Seaftware/locked-up | /src/utils.cpp | UTF-8 | 1,165 | 3.390625 | 3 | [] | no_license | #include <cmath>
#include "utils.hpp"
float Utils::min(float a, float b)
{
return a < b ? a : b;
}
float Utils::max(float a, float b)
{
return a > b ? a : b;
}
float Utils::lerp(float a, float b, float f)
{
return a + f * (b - a);
}
float Utils::clamp(float v, float min, float max)
{
if(v < min)
return min;
else if(v > max)
return max;
return v;
}
float Utils::magnitude(sf::Vector2f vec)
{
return std::sqrt(vec.x * vec.x + vec.y * vec.y);
}
sf::Vector2f Utils::normalize(sf::Vector2f vec)
{
return vec / magnitude(vec);
}
bool Utils::is_number(const std::string& string)
{
for(auto& ch : string)
{
if(ch < '0' || ch > '9')
return false;
}
return true;
}
bool Utils::is_printable(const std::string& string)
{
for(auto& ch : string)
{
if(!isprint(ch))
return false;
}
return true;
}
std::string Utils::to_lower_case(const std::string& string)
{
std::string result(string.size(), ' ');
std::transform(
string.begin(), string.end(), result.begin(), [](char c) { return std::tolower(c); }
);
return result;
}
| true |
2cdfdb5578aa52610d5b5f54effa52ee7828347f | C++ | fabiuccio/University | /System Programming Project - Minifilter driver plus remote logger (Italian Language)/VLService/DisinstallazioneServizio/DisinstallazioneServizio.cpp | UTF-8 | 1,523 | 2.609375 | 3 | [] | no_license | #include "stdafx.h"
#include <Windows.h>
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
SC_HANDLE myService, scm;
BOOL success;
SERVICE_STATUS status;
cout << "Removing Service...\n";
// Open a Service Control Manager connection
scm = OpenSCManager(0, 0, SC_MANAGER_CREATE_SERVICE);
if (!scm)
{
cout<<"OpenSCManager Fails!";
cout<<GetLastError()<<endl;
}
cout << "Opened Service Control Manager...\n";
// Get the service's handle
myService = OpenService(scm, TEXT("VLService"), SERVICE_ALL_ACCESS | DELETE);
if (!myService)
{
cout<<"OpenService Fails!";
cout<<GetLastError()<<endl;
}
// Stop the service if necessary
success = QueryServiceStatus(myService, &status);
if (!success)
{
cout<<"QueryServiceStatus fails!";
cout<<GetLastError()<<endl;
}
if (status.dwCurrentState != SERVICE_STOPPED)
{
cout << "Service currently active. Stopping service...\n";
success = ControlService(myService, SERVICE_CONTROL_STOP, &status);
if (!success)
{
cout<<"ControlService fails to stop service!";
cout<<GetLastError()<<endl;
}
Sleep(500);
}
// Remove the service
success = DeleteService(myService);
if (success)
{
cout << "Service successfully removed.\n"<<endl;
}
else
{
cout<<"DeleteService Fails!";
cout<<GetLastError()<<endl;
}
CloseServiceHandle(myService);
CloseServiceHandle(scm);
int x;cin>>x;
return 0;
}
| true |
f2fb885ea25e8af864b3623f3c636112f0163eea | C++ | McSimp/ts3-auto-afk | /TS3AutoAFKPlugin/plugin.cpp | UTF-8 | 4,242 | 2.625 | 3 | [] | no_license | #include "plugin.hpp"
#include <iostream>
#include <thread>
#include <Windows.h>
static struct TS3Functions ts3;
static bool shouldExitMonitorThread;
static std::thread idleMonitorThread;
static DWORD secondsForIdle;
static bool isSetToAFK;
static bool shouldRestoreAFK;
static bool shouldRestoreMuteSound;
static bool shouldRestoreMuteMic;
const char* ts3plugin_name()
{
return "Auto AFK Status";
}
const char* ts3plugin_version()
{
return "1.1";
}
int ts3plugin_apiVersion()
{
return PLUGIN_API_VERSION;
}
const char* ts3plugin_author()
{
return "McSimp";
}
const char* ts3plugin_description()
{
return "This plugin will automatically set your status to AFK, mute your sound, and mute your microphone if you don't move your mouse or press any keys for 10 minutes.";
}
void ts3plugin_setFunctionPointers(const struct TS3Functions funcs)
{
ts3 = funcs;
}
void setToAFK(uint64 serverID)
{
// When we're setting the person as AFK, if they already have some kind of status
// set on their mic (muted for example), then don't unmute it when they come back.
int micMuted;
ts3.getClientSelfVariableAsInt(serverID, CLIENT_INPUT_MUTED, &micMuted);
if(micMuted != MUTEINPUT_NONE)
{
shouldRestoreMuteMic = false;
}
else
{
shouldRestoreMuteMic = true;
ts3.setClientSelfVariableAsInt(serverID, CLIENT_INPUT_MUTED, MUTEINPUT_MUTED);
}
// Same goes for speakers
int outMuted;
ts3.getClientSelfVariableAsInt(serverID, CLIENT_OUTPUT_MUTED, &outMuted);
if(outMuted != MUTEOUTPUT_NONE)
{
shouldRestoreMuteSound = false;
}
else
{
shouldRestoreMuteSound = true;
ts3.setClientSelfVariableAsInt(serverID, CLIENT_OUTPUT_MUTED, MUTEOUTPUT_MUTED);
}
// And AFK status
int afkStatus;
ts3.getClientSelfVariableAsInt(serverID, CLIENT_AWAY, &afkStatus);
if(afkStatus != AWAY_NONE)
{
shouldRestoreAFK = false;
}
else
{
shouldRestoreAFK = true;
ts3.setClientSelfVariableAsInt(serverID, CLIENT_AWAY, AWAY_ZZZ);
}
ts3.flushClientSelfUpdates(serverID, NULL);
//std::cout << "setTOAFK: " << shouldRestoreAFK << shouldRestoreMuteMic << shouldRestoreMuteSound << std::endl;
}
void setBack(uint64 serverID)
{
// Set AFK status
if(shouldRestoreAFK)
{
shouldRestoreAFK = false;
ts3.setClientSelfVariableAsInt(serverID, CLIENT_AWAY, AWAY_NONE);
}
// Microphone toggle
if(shouldRestoreMuteMic)
{
shouldRestoreMuteMic = false;
ts3.setClientSelfVariableAsInt(serverID, CLIENT_INPUT_MUTED, MUTEINPUT_NONE);
}
// Speaker toggle
if(shouldRestoreMuteSound)
{
shouldRestoreMuteSound = false;
ts3.setClientSelfVariableAsInt(serverID, CLIENT_OUTPUT_MUTED, MUTEOUTPUT_NONE);
}
ts3.flushClientSelfUpdates(serverID, NULL);
}
void toggleAFK(bool isAFK)
{
uint64* ids;
if(ts3.getServerConnectionHandlerList(&ids) != ERROR_ok)
{
ts3.logMessage("[AutoAFK] Error retrieving server list - cannot set AFK", LogLevel_ERROR, "Plugin", 0);
return;
}
// Foreach connection
for(int i = 0; ids[i]; i++)
{
uint64 serverID = ids[i];
anyID clid;
if(ts3.getClientID(serverID, &clid) == ERROR_ok)
{
if(isAFK)
{
setToAFK(serverID);
}
else
{
setBack(serverID);
}
}
}
ts3.freeMemory(ids);
isSetToAFK = isAFK;
}
void idleWatcher()
{
LASTINPUTINFO lastInput;
lastInput.cbSize = sizeof(LASTINPUTINFO);
std::chrono::milliseconds measureInterval(1000);
std::chrono::milliseconds loopTime(500);
auto start = std::chrono::steady_clock::now();
while(!shouldExitMonitorThread)
{
if((std::chrono::steady_clock::now() - start) > measureInterval)
{
if(GetLastInputInfo(&lastInput))
{
DWORD awayTimeSecs = ((GetTickCount() - lastInput.dwTime)/1000);
if(awayTimeSecs > secondsForIdle)
{
if(!isSetToAFK)
toggleAFK(true);
}
else if(isSetToAFK)
{
toggleAFK(false);
}
}
start = std::chrono::steady_clock::now();
}
std::this_thread::sleep_for(loopTime);
}
}
int ts3plugin_requestAutoload()
{
return 1;
}
int ts3plugin_init()
{
shouldExitMonitorThread = false;
secondsForIdle = 10 * 60;
idleMonitorThread = std::thread(idleWatcher);
return 0;
}
void ts3plugin_shutdown()
{
shouldExitMonitorThread = true;
idleMonitorThread.join();
}
| true |
dd2eb83b4005c89eb51c8dd2daf24171a3ed3314 | C++ | martinnobis/Head-First-Design-Patterns-Cpp | /Command/Remote_Control/main.cc | UTF-8 | 1,286 | 2.859375 | 3 | [] | no_license | #include <iostream>
#include <memory>
#include "remote_control.h"
#include "Light/light_on_command.h"
#include "Light/light_off_command.h"
#include "Light/light.h"
#include "Stereo/stereo_on_command.h"
#include "Stereo/stereo_off_command.h"
#include "Stereo/stereo.h"
int main(void)
{
RemoteControl remote_control;
// Things to command
Light living_room_light("Living Room");
Stereo living_room_stereo("Living Room");
// Commands
auto living_room_light_on = std::make_shared<LightOnCommand>(living_room_light);
auto living_room_light_off = std::make_shared<LightOffCommand>(living_room_light);
auto living_room_stereo_on = std::make_shared<StereoOnCommand>(living_room_stereo);
auto living_room_stereo_off = std::make_shared<StereoOffCommand>(living_room_stereo);
// Assign commands to buttons on the remote.
remote_control.SetCommand(0, living_room_light_on, living_room_light_off);
remote_control.SetCommand(1, living_room_stereo_on, living_room_stereo_off);
std::cout << remote_control << std::endl
<< std::endl;
// Push some buttons.
remote_control.OnButtonWasPushed(0);
remote_control.OffButtonWasPushed(0);
remote_control.OnButtonWasPushed(1);
remote_control.OffButtonWasPushed(1);
}
| true |
8e42a2a825969172050ced55466fd7dd636eb4e0 | C++ | jourdanj/JoynerJourdan_CSC5_46091_SUM2015- | /Assignments/Assignment 4/Gaddis 7th ed ch 5 #1/main.cpp | UTF-8 | 746 | 3.171875 | 3 | [] | no_license | /*
* File: main.cpp
* Author: Jourdan Joyner
* Created on July 13, 2015, 6:53 PM
* Purpose: Gaddis 7th Ed ch 5 # 1
*/
#include <iostream>//i/o libraries
using namespace std;
//User functions
// Global Constants
//Function proto1types
//execution begins
int main(int argc, char** argv) {
int num,//input number
sum,//sum of numbers
i;//counter
cout<<"Enter a positive integer.\n";
cin>>num;
if(num<0){//reject inputs <0
cout<<"You cannot follow directions.\n";
}
else{
for(i==0;i<=num;i++){//loop to count
sum+=i;
}
cout<<"Sum of integers to "<<num<<" is "<<sum<<endl;//output solution
}
return 0;
}
| true |
38195f7bfcbc8e326f530f0184c8d78bd961e769 | C++ | ashleygay/DCP | /day6/solve.cpp | UTF-8 | 1,245 | 4.03125 | 4 | [] | no_license | #include <iostream>
class list_head {
/* Contents of the diff fields:
*
* A B C D E
* B <-> A^C <-> B^D <-> C^E <-> D
*/
public:
list_head(void* elt) : _elt(elt){}
// Add an elt to the list
void add(void* elt) {
list_head* list = this;
list_head* prev = nullptr;
while (list->diff != (size_t)prev) {
auto tmp = list;
list = (list_head*)(((size_t)prev) ^ list->diff);
prev = tmp;
}
list_head* new_list = new list_head(elt);
new_list->diff = (size_t)list;
list->diff = ((size_t)prev) ^ ((size_t)new_list);
}
// Get the ith element of the list
void* get(int i) const {
const list_head* list = this;
const list_head* prev = nullptr;
while (i != 0 && list->diff != (size_t)prev) {
auto tmp = list;
list = (list_head*)(((size_t)prev) ^ list->diff);
prev = tmp;
--i;
}
return list->_elt;
}
private:
size_t diff = 0;
void* _elt = nullptr;
};
void print_index(list_head *h, int i)
{
std::cout <<" index " << i << " -> " << *((int*)h->get(i)) << std::endl;
}
int main() {
int start = -1;
int x = 0;
int y = 1;
int z = 2;
list_head h(&start);
h.add(&z);
h.add(&x);
std::cout << " List: " << std::endl;
print_index(&h, 0);
print_index(&h, 1);
print_index(&h, 2);
}
| true |
1399fc14860c88e7bd4c2da57bb32faada7125dc | C++ | WenqiJiang/Fast-Vector-Similarity-Search-on-FPGA | /FPGA-ANNS-local/generalized_K_10_12_bank_4_PE/src/LUT_construction.hpp | UTF-8 | 30,811 | 2.625 | 3 | [] | no_license | #pragma once
#include "constants.hpp"
#include "types.hpp"
//////////////////// Function to call in top-level ////////////////////
template<const int query_num>
void lookup_table_construction_wrapper(
const int nprobe,
const int nprobe_per_table_construction_pe_larger,
const int nprobe_per_table_construction_pe_smaller,
hls::stream<float> &s_PQ_quantizer_init,
hls::stream<float> &s_center_vectors_lookup_PE,
hls::stream<float> &s_query_vectors_lookup_PE,
hls::stream<distance_LUT_PQ16_t> &s_distance_LUT);
//////////////////// Function to call in top-level ////////////////////
//////////////////// Padding Logic ////////////////////
// PE_NUM_TABLE_CONSTRUCTION = PE_NUM_TABLE_CONSTRUCTION_LARGER + 1
// the first PE_NUM_TABLE_CONSTRUCTION_LARGER PEs construct nprobe_per_table_construction_pe_larger
// LUTs per query, while the last PE constructs nprobe_per_table_construction_pe_smaller
// it could happen that PE_NUM_TABLE_CONSTRUCTION_LARGER * nprobe_per_table_construction_pe_larger > nprobe
// such that nprobe_per_table_construction_pe_smaller is negative, and in this case we need pad it to 1
// the padding happens on the host side, and here we need to send some dummy data to finish the pad (if any)
// the order of table construction, given 4 PEs, nprobe=14 (pad to 15 = 3 * 5 + 1):
// PE0 (head): 1 5 8 11 14
// PE1: 2 6 9 12 15
// PE2: 3 7 10 13 16
// PE3 (tail): 4
// this order is preserved when forwarding the LUTs, and finally there's a consume unit to remove the dummy LUTs
//////////////////// Padding Logic ////////////////////
template<const int query_num>
void center_vectors_padding(
const int nprobe,
const int nprobe_per_table_construction_pe_larger,
const int nprobe_per_table_construction_pe_smaller,
hls::stream<float>& s_center_vectors_lookup_PE,
hls::stream<float>& s_center_vectors_lookup_PE_with_dummy) {
int padded_nprobe =
nprobe_per_table_construction_pe_larger * PE_NUM_TABLE_CONSTRUCTION_LARGER +
nprobe_per_table_construction_pe_smaller;
for (int query_id = 0; query_id < query_num; query_id++) {
for (int i = 0; i < padded_nprobe; i++) {
for (int d = 0; d < D; d++) {
#pragma HLS pipeline II=1
if (i < nprobe) {
s_center_vectors_lookup_PE_with_dummy.write(
s_center_vectors_lookup_PE.read());
}
else {
s_center_vectors_lookup_PE_with_dummy.write(0.0);
}
}
}
}
}
template<const int query_num>
void center_vectors_dispatcher(
const int nprobe_per_table_construction_pe_larger,
const int nprobe_per_table_construction_pe_smaller,
hls::stream<float>& s_center_vectors_lookup_PE_with_dummy,
hls::stream<float> (&s_center_vectors_table_construction_PE)[PE_NUM_TABLE_CONSTRUCTION]) {
// Given an input stream of center vectors, interleave it to all
// distance table construction PEs in a round-robin manner
// e.g., 4 PEs, vector 0,4,8 -> PE0, 1,5,9 -> PE1, etc.
for (int query_id = 0; query_id < query_num; query_id++) {
// first, interleave the common part of all PEs (decided by the PE of smaller scanned cells)
for (int interleave_iter = 0; interleave_iter < nprobe_per_table_construction_pe_larger; interleave_iter++) {
for (int s = 0; s < PE_NUM_TABLE_CONSTRUCTION_LARGER; s++) {
for (int n = 0; n < D; n++) {
#pragma HLS pipeline II=1
s_center_vectors_table_construction_PE[s].write(s_center_vectors_lookup_PE_with_dummy.read());
}
}
if (interleave_iter < nprobe_per_table_construction_pe_smaller) {
for (int n = 0; n < D; n++) {
#pragma HLS pipeline II=1
s_center_vectors_table_construction_PE[PE_NUM_TABLE_CONSTRUCTION_LARGER].write(s_center_vectors_lookup_PE_with_dummy.read());
}
}
}
}
}
template<const int query_num>
void gather_float_to_distance_LUT_PQ16(
const int nprobe_per_PE,
hls::stream<float>& s_partial_result_table_construction_individual,
hls::stream<distance_LUT_PQ16_t>& s_partial_result_table_construction_PE) {
for (int query_id = 0; query_id < query_num; query_id++) {
for (int nprobe_id = 0; nprobe_id < nprobe_per_PE; nprobe_id++) {
distance_LUT_PQ16_t out;
for (int k = 0; k < K; k++) {
#pragma HLS pipeline II=16
out.dist_0 = s_partial_result_table_construction_individual.read();
out.dist_1 = s_partial_result_table_construction_individual.read();
out.dist_2 = s_partial_result_table_construction_individual.read();
out.dist_3 = s_partial_result_table_construction_individual.read();
out.dist_4 = s_partial_result_table_construction_individual.read();
out.dist_5 = s_partial_result_table_construction_individual.read();
out.dist_6 = s_partial_result_table_construction_individual.read();
out.dist_7 = s_partial_result_table_construction_individual.read();
out.dist_8 = s_partial_result_table_construction_individual.read();
out.dist_9 = s_partial_result_table_construction_individual.read();
out.dist_10 = s_partial_result_table_construction_individual.read();
out.dist_11 = s_partial_result_table_construction_individual.read();
out.dist_12 = s_partial_result_table_construction_individual.read();
out.dist_13 = s_partial_result_table_construction_individual.read();
out.dist_14 = s_partial_result_table_construction_individual.read();
out.dist_15 = s_partial_result_table_construction_individual.read();
s_partial_result_table_construction_PE.write(out);
}
}
}
}
template<const int query_num>
void lookup_table_construction_compute_head(
const int nprobe_per_PE,
hls::stream<float>& s_PQ_quantizer_init_in,
hls::stream<float>& s_PQ_quantizer_init_out,
hls::stream<float>& s_center_vectors_table_construction_PE_in,
hls::stream<float>& s_query_vectors_table_construction_PE_in,
hls::stream<float>& s_query_vectors_table_construction_PE_out,
hls::stream<float>& s_partial_result_table_construction_individual) {
/* output format:
* lookup table dim: (K x M)
* sending first row, then second row, and so on...
* store in distance_LUT_PQ16_t, each represent an entire row (M=16)
* 256 distance_LUT_PQ16_t is an entire lookup table
*/
// local alignment: 16-sub quantizers
// each quantizer: 256 row, (128 / 16) col
// [M][K][D/M] -> [16][256][8]
float sub_quantizer[M * K * (D / M)];
#pragma HLS resource variable=sub_quantizer core=RAM_2P_URAM
#pragma HLS array_partition variable=sub_quantizer cyclic factor=8 dim=1
// DRAM PQ quantizer format: 16 (M) x 256 (K) x 8 (D/M)
for (int i = 0; i < M * K * D / M; i++) {
float reg = s_PQ_quantizer_init_in.read();
sub_quantizer[i] = reg;
s_PQ_quantizer_init_out.write(reg);
}
float query_vector_local[D];
float center_vector_local[D];
float residual_center_vector[D]; // query_vector - center_vector
#pragma HLS array_partition variable=residual_center_vector cyclic factor=16
for (int query_id = 0; query_id < query_num; query_id++) {
// load query vector
for (int d = 0; d < D; d++) {
#pragma HLS pipeline II=1
float reg = s_query_vectors_table_construction_PE_in.read();
query_vector_local[d] = reg;
s_query_vectors_table_construction_PE_out.write(reg);
}
for (int nprobe_id = 0; nprobe_id < nprobe_per_PE; nprobe_id++) {
// load center vector
residual_center_vectors:
for (int d = 0; d < D; d++) {
#pragma HLS pipeline II=1
center_vector_local[d] = s_center_vectors_table_construction_PE_in.read();
residual_center_vector[d] = query_vector_local[d] - center_vector_local[d];
}
// construct distance lookup table
single_row_lookup_table_construction:
for (int k = 0; k < K; k++) {
for (int m = 0; m < M; m++) {
#pragma HLS pipeline II=1
// no need to init to 0, the following logic will overwrite them
float L1_dist[D / M];
#pragma HLS array_partition variable=L1_dist complete
for (int simd_i = 0; simd_i < D / M; simd_i++) {
#pragma HLS UNROLL
L1_dist[simd_i] =
residual_center_vector[m * (D / M) + simd_i] -
sub_quantizer[m * K * (D / M) + k * (D / M) + simd_i];
}
float LUT_val =
(L1_dist[0] * L1_dist[0]) + (L1_dist[1] * L1_dist[1]) +
(L1_dist[2] * L1_dist[2]) + (L1_dist[3] * L1_dist[3]) +
(L1_dist[4] * L1_dist[4]) + (L1_dist[5] * L1_dist[5]) +
(L1_dist[6] * L1_dist[6]) + (L1_dist[7] * L1_dist[7]);
s_partial_result_table_construction_individual.write(LUT_val);
}
}
}
}
}
template<const int query_num>
void extra_FIFO_head_PE(
const int nprobe_per_PE,
hls::stream<distance_LUT_PQ16_t>& s_partial_result_table_construction_PE_in,
hls::stream<distance_LUT_PQ16_t>& s_partial_result_table_construction_PE_out) {
// Prevent compute stall:
// make sure that the results of head PE can accumulate if later forward FIFO stalls
for (int query_id = 0; query_id < query_num; query_id++) {
for (int nprobe_id = 0; nprobe_id < nprobe_per_PE; nprobe_id++) {
for (int k = 0; k < K; k++) {
#pragma HLS pipeline II=1
s_partial_result_table_construction_PE_out.write(
s_partial_result_table_construction_PE_in.read());
}
}
}
}
template<const int query_num>
void lookup_table_construction_head_PE(
const int nprobe_per_PE,
hls::stream<float>& s_PQ_quantizer_init_in,
hls::stream<float>& s_PQ_quantizer_init_out,
hls::stream<float>& s_center_vectors_table_construction_PE_in,
hls::stream<float>& s_query_vectors_table_construction_PE_in,
hls::stream<float>& s_query_vectors_table_construction_PE_out,
hls::stream<distance_LUT_PQ16_t>& s_partial_result_table_construction_PE) {
#pragma HLS dataflow
hls::stream<float> s_partial_result_table_construction_individual;
#pragma HLS stream variable=s_partial_result_table_construction_individual depth=512
const int s_partial_result_table_construction_PE_extra_FIFO_depth = K * PE_NUM_TABLE_CONSTRUCTION_LARGER;
hls::stream<distance_LUT_PQ16_t> s_partial_result_table_construction_PE_extra_FIFO;
#pragma HLS stream variable=s_partial_result_table_construction_PE depth=s_partial_result_table_construction_PE_extra_FIFO_depth
lookup_table_construction_compute_head<query_num>(
nprobe_per_PE,
s_PQ_quantizer_init_in,
s_PQ_quantizer_init_out,
s_center_vectors_table_construction_PE_in,
s_query_vectors_table_construction_PE_in,
s_query_vectors_table_construction_PE_out,
s_partial_result_table_construction_individual);
gather_float_to_distance_LUT_PQ16<query_num>(
nprobe_per_PE,
s_partial_result_table_construction_individual,
s_partial_result_table_construction_PE_extra_FIFO);
extra_FIFO_head_PE<query_num>(
nprobe_per_PE,
s_partial_result_table_construction_PE_extra_FIFO,
s_partial_result_table_construction_PE);
}
template<const int query_num>
void lookup_table_construction_compute_midlle(
const int nprobe_per_PE,
hls::stream<float>& s_PQ_quantizer_init_in,
hls::stream<float>& s_PQ_quantizer_init_out,
hls::stream<float>& s_center_vectors_table_construction_PE_in,
hls::stream<float>& s_query_vectors_table_construction_PE_in,
hls::stream<float>& s_query_vectors_table_construction_PE_out,
hls::stream<float>& s_partial_result_table_construction_individual) {
/* output format:
* lookup table dim: (K x M)
* sending first row, then second row, and so on...
* store in distance_LUT_PQ16_t, each represent an entire row (M=16)
* 256 distance_LUT_PQ16_t is an entire lookup table
*/
// local alignment: 16-sub quantizers
// each quantizer: 256 row, (128 / 16) col
// [M][K][D/M] -> [16][256][8]
float sub_quantizer[M * K * (D / M)];
#pragma HLS resource variable=sub_quantizer core=RAM_2P_URAM
#pragma HLS array_partition variable=sub_quantizer cyclic factor=8 dim=1
// DRAM PQ quantizer format: 16 (M) x 256 (K) x 8 (D/M)
for (int i = 0; i < M * K * D / M; i++) {
float reg = s_PQ_quantizer_init_in.read();
sub_quantizer[i] = reg;
s_PQ_quantizer_init_out.write(reg);
}
float query_vector_local[D];
float center_vector_local[D];
float residual_center_vector[D]; // query_vector - center_vector
#pragma HLS array_partition variable=residual_center_vector cyclic factor=16
for (int query_id = 0; query_id < query_num; query_id++) {
// load query vector
for (int d = 0; d < D; d++) {
#pragma HLS pipeline II=1
float reg = s_query_vectors_table_construction_PE_in.read();
query_vector_local[d] = reg;
s_query_vectors_table_construction_PE_out.write(reg);
}
for (int nprobe_id = 0; nprobe_id < nprobe_per_PE; nprobe_id++) {
// load center vector
residual_center_vectors:
for (int d = 0; d < D; d++) {
#pragma HLS pipeline II=1
center_vector_local[d] = s_center_vectors_table_construction_PE_in.read();
residual_center_vector[d] = query_vector_local[d] - center_vector_local[d];
}
// construct distance lookup table
single_row_lookup_table_construction:
for (int k = 0; k < K; k++) {
for (int m = 0; m < M; m++) {
#pragma HLS pipeline II=1
// no need to init to 0, the following logic will overwrite them
float L1_dist[D / M];
#pragma HLS array_partition variable=L1_dist complete
for (int simd_i = 0; simd_i < D / M; simd_i++) {
#pragma HLS UNROLL
L1_dist[simd_i] =
residual_center_vector[m * (D / M) + simd_i] -
sub_quantizer[m * K * (D / M) + k * (D / M) + simd_i];
}
float LUT_val =
(L1_dist[0] * L1_dist[0]) + (L1_dist[1] * L1_dist[1]) +
(L1_dist[2] * L1_dist[2]) + (L1_dist[3] * L1_dist[3]) +
(L1_dist[4] * L1_dist[4]) + (L1_dist[5] * L1_dist[5]) +
(L1_dist[6] * L1_dist[6]) + (L1_dist[7] * L1_dist[7]);
s_partial_result_table_construction_individual.write(LUT_val);
}
}
}
}
}
template<const int query_num>
void lookup_table_construction_forward_middle(
const int systolic_array_id,
const int nprobe_per_table_construction_pe_larger,
hls::stream<distance_LUT_PQ16_t> &s_partial_result_table_construction_PE,
hls::stream<distance_LUT_PQ16_t> &s_partial_result_table_construction_forward_in,
hls::stream<distance_LUT_PQ16_t> &s_partial_result_table_construction_forward_out) {
////////// NOTE: the order of output LUT must be consistent of the center vector input /////////
// e.g., say nprobe=17, PE_num=4, then the first 3 PEs compute 5 tables while the last compute 2
// first 2 rounds 4 PEs, last 3 rounds 3 PEs
// PE 0: 0, 4, 8, 11, 14
// PE 1: 1, 5, 9, 12, 15
// PE 2: 2, 6, 10, 13, 16
// PE 3: 3, 7
for (int query_id = 0; query_id < query_num; query_id++) {
for (int interleave_iter = 0; interleave_iter < nprobe_per_table_construction_pe_larger; interleave_iter++) {
// forward head / midlle PEs
for (int s = 0; s < systolic_array_id; s++) {
// each lookup table: K rows
for (int t = 0; t < K; t++) {
#pragma HLS pipeline II=1
s_partial_result_table_construction_forward_out.write(s_partial_result_table_construction_forward_in.read());
}
}
// result from the current PE
for (int t = 0; t < K; t++) {
#pragma HLS pipeline II=1
s_partial_result_table_construction_forward_out.write(s_partial_result_table_construction_PE.read());
}
}
}
}
template<const int query_num>
void lookup_table_construction_middle_PE(
const int systolic_array_id,
const int nprobe_per_table_construction_pe_larger,
hls::stream<float>& s_PQ_quantizer_init_in,
hls::stream<float>& s_PQ_quantizer_init_out,
hls::stream<float>& s_center_vectors_table_construction_PE_in,
hls::stream<float>& s_query_vectors_table_construction_PE_in,
hls::stream<float>& s_query_vectors_table_construction_PE_out,
hls::stream<distance_LUT_PQ16_t> &s_partial_result_table_construction_forward_in,
hls::stream<distance_LUT_PQ16_t> &s_partial_result_table_construction_forward_out) {
#pragma HLS dataflow
hls::stream<float> s_partial_result_table_construction_individual;
#pragma HLS stream variable=s_partial_result_table_construction_individual depth=512
const int s_partial_result_table_construction_PE_depth = K * PE_NUM_TABLE_CONSTRUCTION_LARGER;
hls::stream<distance_LUT_PQ16_t> s_partial_result_table_construction_PE;
#pragma HLS stream variable=s_partial_result_table_construction_PE depth=s_partial_result_table_construction_PE_depth
lookup_table_construction_compute_midlle<query_num>(
nprobe_per_table_construction_pe_larger,
s_PQ_quantizer_init_in,
s_PQ_quantizer_init_out,
s_center_vectors_table_construction_PE_in,
s_query_vectors_table_construction_PE_in,
s_query_vectors_table_construction_PE_out,
s_partial_result_table_construction_individual);
gather_float_to_distance_LUT_PQ16<query_num>(
nprobe_per_table_construction_pe_larger,
s_partial_result_table_construction_individual,
s_partial_result_table_construction_PE);
lookup_table_construction_forward_middle<query_num>(
systolic_array_id,
nprobe_per_table_construction_pe_larger,
s_partial_result_table_construction_PE,
s_partial_result_table_construction_forward_in,
s_partial_result_table_construction_forward_out);
}
template<const int query_num>
void lookup_table_construction_compute_tail(
const int nprobe_per_PE,
hls::stream<float>& s_PQ_quantizer_init_in,
hls::stream<float>& s_center_vectors_table_construction_PE_in,
hls::stream<float>& s_query_vectors_table_construction_PE_in,
hls::stream<float>& s_partial_result_table_construction_individual) {
/* output format:
* lookup table dim: (K x M)
* sending first row, then second row, and so on...
* store in distance_LUT_PQ16_t, each represent an entire row (M=16)
* 256 distance_LUT_PQ16_t is an entire lookup table
*/
// local alignment: 16-sub quantizers
// each quantizer: 256 row, (128 / 16) col
// [M][K][D/M] -> [16][256][8]
float sub_quantizer[M * K * (D / M)];
#pragma HLS resource variable=sub_quantizer core=RAM_2P_URAM
#pragma HLS array_partition variable=sub_quantizer cyclic factor=8 dim=1
// DRAM PQ quantizer format: 16 (M) x 256 (K) x 8 (D/M)
for (int i = 0; i < M * K * D / M; i++) {
float reg = s_PQ_quantizer_init_in.read();
sub_quantizer[i] = reg;
}
float query_vector_local[D];
float center_vector_local[D];
float residual_center_vector[D]; // query_vector - center_vector
#pragma HLS array_partition variable=residual_center_vector cyclic factor=16
for (int query_id = 0; query_id < query_num; query_id++) {
// load query vector
for (int d = 0; d < D; d++) {
#pragma HLS pipeline II=1
float reg = s_query_vectors_table_construction_PE_in.read();
query_vector_local[d] = reg;
}
for (int nprobe_id = 0; nprobe_id < nprobe_per_PE; nprobe_id++) {
// load center vector
residual_center_vectors:
for (int d = 0; d < D; d++) {
#pragma HLS pipeline II=1
center_vector_local[d] = s_center_vectors_table_construction_PE_in.read();
residual_center_vector[d] = query_vector_local[d] - center_vector_local[d];
}
// construct distance lookup table
single_row_lookup_table_construction:
for (int k = 0; k < K; k++) {
for (int m = 0; m < M; m++) {
#pragma HLS pipeline II=1
// no need to init to 0, the following logic will overwrite them
float L1_dist[D / M];
#pragma HLS array_partition variable=L1_dist complete
for (int simd_i = 0; simd_i < D / M; simd_i++) {
#pragma HLS UNROLL
L1_dist[simd_i] =
residual_center_vector[m * (D / M) + simd_i] -
sub_quantizer[m * K * (D / M) + k * (D / M) + simd_i];
}
float LUT_val =
(L1_dist[0] * L1_dist[0]) + (L1_dist[1] * L1_dist[1]) +
(L1_dist[2] * L1_dist[2]) + (L1_dist[3] * L1_dist[3]) +
(L1_dist[4] * L1_dist[4]) + (L1_dist[5] * L1_dist[5]) +
(L1_dist[6] * L1_dist[6]) + (L1_dist[7] * L1_dist[7]);
s_partial_result_table_construction_individual.write(LUT_val);
}
}
}
}
}
template<const int query_num>
void lookup_table_construction_forward_tail(
const int nprobe_per_table_construction_pe_larger,
const int nprobe_per_table_construction_pe_smaller,
hls::stream<distance_LUT_PQ16_t> &s_partial_result_table_construction_PE,
hls::stream<distance_LUT_PQ16_t> &s_partial_result_table_construction_forward_in,
hls::stream<distance_LUT_PQ16_t> &s_result_all_distance_lookup_table) {
////////// NOTE: the order of output LUT must be consistent of the center vector input /////////
// e.g., say nprobe=17, PE_num=4, then the first 3 PEs compute 5 tables while the last compute 2
// first 2 rounds 4 PEs, last 3 rounds 3 PEs
// PE 0: 0, 4, 8, 11, 14
// PE 1: 1, 5, 9, 12, 15
// PE 2: 2, 6, 10, 13, 16
// PE 3: 3, 7
for (int query_id = 0; query_id < query_num; query_id++) {
for (int interleave_iter = 0; interleave_iter < nprobe_per_table_construction_pe_larger; interleave_iter++) {
// forward head / midlle PEs
for (int s = 0; s < PE_NUM_TABLE_CONSTRUCTION_LARGER; s++) {
// each lookup table: K rows
for (int t = 0; t < K; t++) {
#pragma HLS pipeline II=1
s_result_all_distance_lookup_table.write(s_partial_result_table_construction_forward_in.read());
}
}
if (interleave_iter < nprobe_per_table_construction_pe_smaller) {
// result from the current PE
for (int t = 0; t < K; t++) {
#pragma HLS pipeline II=1
s_result_all_distance_lookup_table.write(s_partial_result_table_construction_PE.read());
}
}
}
}
}
template<const int query_num>
void lookup_table_construction_tail_PE(
const int nprobe_per_table_construction_pe_larger,
const int nprobe_per_table_construction_pe_smaller,
hls::stream<float>& s_PQ_quantizer_init_in,
hls::stream<float>& s_center_vectors_table_construction_PE_in,
hls::stream<float>& s_query_vectors_table_construction_PE_in,
hls::stream<distance_LUT_PQ16_t> &s_partial_result_table_construction_forward_in,
hls::stream<distance_LUT_PQ16_t> &s_result_all_distance_lookup_table) {
#pragma HLS dataflow
hls::stream<float> s_partial_result_table_construction_individual;
#pragma HLS stream variable=s_partial_result_table_construction_individual depth=512
const int s_partial_result_table_construction_PE_depth = K * PE_NUM_TABLE_CONSTRUCTION_SMALLER;
hls::stream<distance_LUT_PQ16_t> s_partial_result_table_construction_PE;
#pragma HLS stream variable=s_partial_result_table_construction_PE depth=s_partial_result_table_construction_PE_depth
lookup_table_construction_compute_tail<query_num>(
nprobe_per_table_construction_pe_smaller,
s_PQ_quantizer_init_in,
s_center_vectors_table_construction_PE_in,
s_query_vectors_table_construction_PE_in,
s_partial_result_table_construction_individual);
gather_float_to_distance_LUT_PQ16<query_num>(
nprobe_per_table_construction_pe_smaller,
s_partial_result_table_construction_individual,
s_partial_result_table_construction_PE);
lookup_table_construction_forward_tail<query_num>(
nprobe_per_table_construction_pe_larger,
nprobe_per_table_construction_pe_smaller,
s_partial_result_table_construction_PE,
s_partial_result_table_construction_forward_in,
s_result_all_distance_lookup_table);
}
template<const int query_num>
void remove_dummy_LUTs(
const int nprobe,
const int nprobe_per_table_construction_pe_larger,
const int nprobe_per_table_construction_pe_smaller,
hls::stream<distance_LUT_PQ16_t>& s_distance_LUT_with_dummy,
hls::stream<distance_LUT_PQ16_t>& s_distance_LUT) {
int padded_nprobe =
nprobe_per_table_construction_pe_larger * PE_NUM_TABLE_CONSTRUCTION_LARGER +
nprobe_per_table_construction_pe_smaller;
for (int query_id = 0; query_id < query_num; query_id++) {
for (int i = 0; i < padded_nprobe; i++) {
for (int t = 0; t < K; t++) {
#pragma HLS pipeline II=1
distance_LUT_PQ16_t reg = s_distance_LUT_with_dummy.read();
if (i < nprobe) {
s_distance_LUT.write(reg);
}
}
}
}
}
template<const int query_num>
void lookup_table_construction_wrapper(
const int nprobe,
const int nprobe_per_table_construction_pe_larger,
const int nprobe_per_table_construction_pe_smaller,
hls::stream<float> &s_PQ_quantizer_init,
hls::stream<float> &s_center_vectors_lookup_PE,
hls::stream<float> &s_query_vectors_lookup_PE,
hls::stream<distance_LUT_PQ16_t> &s_distance_LUT) {
#pragma HLS inline
hls::stream<float> s_center_vectors_lookup_PE_with_dummy;
#pragma HLS stream variable=s_center_vectors_lookup_PE_with_dummy depth=512
center_vectors_padding<query_num>(
nprobe,
nprobe_per_table_construction_pe_larger,
nprobe_per_table_construction_pe_smaller,
s_center_vectors_lookup_PE,
s_center_vectors_lookup_PE_with_dummy);
hls::stream<float> s_center_vectors_table_construction_PE[PE_NUM_TABLE_CONSTRUCTION];
#pragma HLS stream variable=s_center_vectors_table_construction_PE depth=512
// #pragma HLS resource variable=s_center_vectors_table_construction_PE core=FIFO_BRAM
#pragma HLS array_partition variable=s_center_vectors_table_construction_PE complete
center_vectors_dispatcher<query_num>(
nprobe_per_table_construction_pe_larger,
nprobe_per_table_construction_pe_smaller,
s_center_vectors_lookup_PE_with_dummy,
s_center_vectors_table_construction_PE);
hls::stream<float> s_PQ_quantizer_init_forward[PE_NUM_TABLE_CONSTRUCTION_LARGER];
#pragma HLS stream variable=s_PQ_quantizer_init_forward depth=8
#pragma HLS array_partition variable=s_PQ_quantizer_init_forward complete
hls::stream<float> s_query_vectors_table_construction_PE_forward[PE_NUM_TABLE_CONSTRUCTION_LARGER];
#pragma HLS stream variable=s_query_vectors_table_construction_PE_forward depth=512
#pragma HLS array_partition variable=s_query_vectors_table_construction_PE_forward complete
hls::stream<distance_LUT_PQ16_t> s_partial_result_table_construction_PE_forward[PE_NUM_TABLE_CONSTRUCTION_LARGER];
#pragma HLS stream variable=s_partial_result_table_construction_PE_forward depth=8
#pragma HLS array_partition variable=s_partial_result_table_construction_PE_forward complete
lookup_table_construction_head_PE<query_num>(
nprobe_per_table_construction_pe_larger,
s_PQ_quantizer_init,
s_PQ_quantizer_init_forward[0],
s_center_vectors_table_construction_PE[0],
s_query_vectors_lookup_PE,
s_query_vectors_table_construction_PE_forward[0],
s_partial_result_table_construction_PE_forward[0]);
// systolic array ID: e.g., 5 PEs, head = 0, middle = 1, 2, 3, tail = 4
for (int s = 1; s < PE_NUM_TABLE_CONSTRUCTION_LARGER; s++) {
#pragma HLS UNROLL
lookup_table_construction_middle_PE<query_num>(
s,
nprobe_per_table_construction_pe_larger,
s_PQ_quantizer_init_forward[s - 1],
s_PQ_quantizer_init_forward[s],
s_center_vectors_table_construction_PE[s],
s_query_vectors_table_construction_PE_forward[s - 1],
s_query_vectors_table_construction_PE_forward[s],
s_partial_result_table_construction_PE_forward[s - 1],
s_partial_result_table_construction_PE_forward[s]);
}
hls::stream<distance_LUT_PQ16_t> s_distance_LUT_with_dummy;
#pragma HLS stream variable=s_distance_LUT_with_dummy depth=8
// NOTE! PE_NUM_TABLE_CONSTRUCTION_SMALLER must === 1
lookup_table_construction_tail_PE<query_num>(
nprobe_per_table_construction_pe_larger,
nprobe_per_table_construction_pe_smaller,
s_PQ_quantizer_init_forward[PE_NUM_TABLE_CONSTRUCTION_LARGER - 1],
s_center_vectors_table_construction_PE[PE_NUM_TABLE_CONSTRUCTION_LARGER],
s_query_vectors_table_construction_PE_forward[PE_NUM_TABLE_CONSTRUCTION_LARGER - 1],
s_partial_result_table_construction_PE_forward[PE_NUM_TABLE_CONSTRUCTION_LARGER - 1],
s_distance_LUT_with_dummy);
remove_dummy_LUTs<query_num>(
nprobe,
nprobe_per_table_construction_pe_larger,
nprobe_per_table_construction_pe_smaller,
s_distance_LUT_with_dummy,
s_distance_LUT);
}
| true |
6120a67ef68b3746f608d220f66c3c3a71f5dfc1 | C++ | huoxiaodan-kaihong/C-Plus-Plus | /Practice_primer/pta_6-3.cpp | UTF-8 | 520 | 3.625 | 4 | [] | no_license | #include <iostream>
using namespace std;
const double PI=3.1415926;
class Circle
{
protected:
double radius;
Circle(double r)
{
radius = r;
}
double getArea()
{
return PI * radius * radius;
}
};
class Cylinder : public Circle
{
private:
double h;
public:
Cylinder(double r, double h);
double getArea();
};
Cylinder::Cylinder(double r, double h) : Circle(r)
{
this->h = h;
}
double Cylinder::getArea()
{
return ((2 * PI * radius * radius) + (2 * PI * radius) * h);
} | true |
67d6649c59974d761ee9cb19fd19de72e4a3f91c | C++ | ItzelXu/EE569-ImageProcessing | /569_HW4/p1/p1_code/Morphology.cpp | UTF-8 | 16,814 | 2.671875 | 3 | [] | no_license | /* EE569 Homework Assignment #4
* Date: Noverber 29, 2015
* Name: Meiyi Yang
* ID: 6761054585
* email: meiyiyan@usc.edu
* Problem1. OCR
*
* Main function:
* p1_main.cpp
*
* Class OCR:
* OCR.h
* OCR.cpp
*
* Class Image:
* image.h
* image.cpp
*
* Class Morphology:
* Morphology.h
* Morphology.cpp
*/
#include "Morphology.h"
///////////////////////////////////////
///////////// Constructor /////////////
///////////////////////////////////////
Morphology::Morphology() { };
Morphology::Morphology(Image *new_image) {
// Set value to image
image.col = new_image->col;
image.row = new_image->row;
image.byte = 1;
image.data = new ImgPixel[image.col * image.row * image.byte];
if (!image.data) {
cerr << "Wrong allocate memory" << endl;
exit(1);
}
for (int i = 0; i < image.col * image.row; i++) {
image.data[i] = new_image->data[i];
}
// Set to binary image
Convert_to_Binary_Image();
}
Morphology::Morphology(int new_row, int new_col, int new_byte, ImgPixel *pt_img) {
// Check parameter
if (new_col <= 0 || new_col > 1024) {
cerr << "wrong column" << endl;
exit(1);
}
if (new_row <= 0 || new_row > 1024) {
cerr << "wrong column" << endl;
exit(1);
}
if (new_byte != 1) {
cerr << "Image must be grayscale" << endl;
exit(1);
}
// Set value to image
image.col = new_col;
image.row = new_row;
image.byte = new_byte;
image.data = new ImgPixel [image.col * image.row * image.byte];
if (!image.data) {
cerr << "Wrong allocate memory" << endl;
exit(1);
}
if (pt_img == NULL) {
for (int i = 0; i < image.col * image.row * image.byte; i++) {
image.data[i] = 0;
}
} else {
for (int i = 0; i < image.col * image.row * image.byte; i++) {
image.data[i] = *pt_img++;
}
}
// Set to binary image
//Convert_to_Binary_Image();
is_binary = 1;
}
Morphology::~Morphology() {
if (filter)
delete [] filter;
if (filter2)
delete [] filter2;
}
////////////////////////////////////////////
///////////// S/T/K Morphology /////////////
////////////////////////////////////////////
int Morphology::Apply_Hit_Miss(int size_filter1, int size_filter2) {
int PRINT = 0;
// Convert to binary image
int row = image.row;
int col = image.col;
if (!is_binary)
Convert_to_Binary_Image();
// Hit-or-Miss
int index[2][9] = {{-1, -1, -1, 0, 0, 0, 1, 1, 1}, {-1, 0, 1, -1, 0, 1, -1, 0, 1}};
int is_change = 1;
int count = 0;
while(count < 100 && is_change == 1) {
// For statistics and debug
is_change = 0;
int count_M = 0;
int count_F = 0;
// Generate M image by Hit-or-Miss filter1
Image image_M = Image(row, col, 1, NULL);
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
if (image.Get_Value(i, j, 0) == 1) {
// Find neighbor dataset
Dataset pixel_neighbor = {};
for (int k = 0; k < 9; k++)
pixel_neighbor[k] = (int)image.Get_Value(i + index[0][k], j + index[1][k], 0);
// Compare the conditional pattern
int res = 0;
int k = 0;
for (k = 0; k < size_filter1; k++) {
res = Compare_Dataset_Conditional(pixel_neighbor, filter[k]);
if (res == 1)
break;
}
// Set M image
if (res == 1) { // Hit
*image_M.Get_Pixel(i, j, 0) = (ImgPixel)1;
count_F++;
}
}
}
}
if (PRINT == 1)
image_M.Print_Pattern_Data("M");
// Hit-or Miss filter2
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
if (image_M.Get_Value(i, j, 0) == 1) {
// Find neighbor dataset
Dataset pixel_neighbor = {};
for (int k = 0; k < 9; k++)
pixel_neighbor[k] = (int)image_M.Get_Value(i + index[0][k], j + index[1][k], 0);
// Compare the conditional pattern and set M image
int res = 0;
int k = 0;
for (k = 0; k < size_filter2; k++) {
res = Compare_Dataset_Unconditional(pixel_neighbor, filter2[k]);
if (res == 1)
break;
}
// Set value to Image F
if (res == 0) { // Miss
count_M++;
is_change = 1;
*image.Get_Pixel(i, j, 0) = (ImgPixel)0;
}
}
}
}
count++;
if (PRINT == 1)
image.Print_Pattern_Data("F");
}
// Calculate Pixel number for debug
int count_pixel = 0;
for (int i = 0; i < row * col; i++) {
if (image.data[i] > 0)
count_pixel++;
}
//cout << " COUNT: " << count_pixel << " ROUND: " << count << endl;
return 0;
};
int Morphology::Operator_Hit_Miss(string filename1, string filename2, int size1, int size2) {
/*if (size1 == PATTERN_S1)
cout << "Operator_Hit_Miss (Shrinking)" << endl;
else if (size1 == PATTERN_S2)
cout << "Operator_Hit_Miss (Thinning)" << endl;
else
cout << "operator_Hit_Miss (Sketonizing)" << endl;*/
Initialize_Pattern_Conditional(filename1, size1);
Initialize_Pattern_Unconditional(filename2, size2);
Apply_Hit_Miss(size1, size2);
return 1;
}
///////////////////////////////////////////////////
///////////// Dilate/Erode Morphology /////////////
///////////////////////////////////////////////////
int Morphology::Operator_Dilate(Dataset filter) {
//cout << "Operator_Dilate: ";
int size = 9;
for (int i = 0; i < size; i++)
//cout << filter[i] << " ";
//cout << endl;
if (!is_binary)
Convert_to_Binary_Image();
// Find pixels to be added by filter
int neighbor_index[2][9] = {{-1, -1, -1, 0, 0, 0, 1, 1, 1}, {-1, 0, 1, -1, 0, 1, -1, 0, 1}};
vector<int> dilate_index_list;
for (int i = 0; i < image.row; i++) {
for (int j = 0; j < image.col; j++) {
if (image.Get_Value(i, j, 0) == 1) {
for (int k = 0; k < size; k++) {
if (filter[k] == 1) {
int temp_x = i + neighbor_index[0][k];
int temp_y = j + neighbor_index[1][k];
if (temp_x >= 0 && temp_x < image.row && temp_y >= 0 && temp_y < image.col)
dilate_index_list.push_back(temp_x * image.col + temp_y);
}
}
}
}
}
// Set dilated pixels
for (int i = 0; i < dilate_index_list.size(); i++) {
image.data[dilate_index_list[i]] = (ImgPixel)1;
}
return 1;
}
int Morphology::Operator_Erode(Dataset filter) {
//cout << "Operator_Erode: ";
int size = 9;
for (int i = 0; i < size; i++)
//cout << filter[i] << " ";
//cout << endl;
if (!is_binary)
Convert_to_Binary_Image();
// Find pixels to be added by filter
int neighbor_index[2][9] = {{-1, -1, -1, 0, 0, 0, 1, 1, 1}, {-1, 0, 1, -1, 0, 1, -1, 0, 1}};
vector<int> erode_index_list;
for (int i = 0; i < image.row; i++) {
for (int j = 0; j < image.col; j++) {
if (image.Get_Value(i, j, 0) == 1) {
// Find neighbor dataset
Dataset pixel_neighbor = {};
for (int k = 0; k < size; k++) {
pixel_neighbor[k] = (int)image.Get_Value(i + neighbor_index[0][k], j + neighbor_index[1][k], 0);
}
// Compare the filter and pixels
int res = 1;
for (int k = 0; k < size; k++) {
if (filter[k] == 1) {
if (filter[k] != pixel_neighbor[k]) {
res = 0;
break;
}
}
}
// Add pixel
if (res == 1) {
erode_index_list.push_back(i * image.col + j);
}
}
}
}
// Set erode pixels
for (int i = 0; i < image.row * image.col; i++) {
image.data[i] = (ImgPixel)0;
}
for (int i = 0; i < erode_index_list.size(); i++) {
image.data[erode_index_list[i]] = (ImgPixel)1;
}
return 1;
}
int Morphology::Operator_Open(Dataset filter1, Dataset filter2) {
Operator_Erode(filter1);
Operator_Dilate(filter2);
return 1;
}
int Morphology::Operator_Close(Dataset filter1, Dataset filter2) {
Operator_Dilate(filter1);
Operator_Erode(filter2);
return 1;
}
int Morphology::Operator_Filter(Dataset filter) {
//cout << "Operator_Filter: ";
int size = 9;
for (int i = 0; i < size; i++)
cout << filter[i] << " ";
cout << endl;
if (!is_binary)
Convert_to_Binary_Image();
// Find pixels to be added by filter
int neighbor_index[2][9] = {{-1, -1, -1, 0, 0, 0, 1, 1, 1}, {-1, 0, 1, -1, 0, 1, -1, 0, 1}};
vector<int> erode_index_list;
for (int i = 0; i < image.row; i++) {
for (int j = 0; j < image.col; j++) {
if (image.Get_Value(i, j, 0) == 1) {
// Find neighbor dataset
Dataset pixel_neighbor = {};
for (int k = 0; k < size; k++) {
pixel_neighbor[k] = (int)image.Get_Value(i + neighbor_index[0][k], j + neighbor_index[1][k], 0);
}
// Compare the filter and pixels
int res = 1;
for (int k = 0; k < size; k++) {
if (filter[k] != pixel_neighbor[k]) {
res = 0;
break;
}
}
// Add pixel
if (res == 1) {
erode_index_list.push_back(i * image.col + j);
}
}
}
}
// Set erode pixels
for (int i = 0; i < image.row * image.col; i++) {
image.data[i] = (ImgPixel)0;
}
for (int i = 0; i < erode_index_list.size(); i++) {
image.data[erode_index_list[i]] = (ImgPixel)1;
}
return 1;
}
///////////////////////////////////////////////
///////////// Counting and Display/////////////
///////////////////////////////////////////////
int Morphology::Convert_Black_Image() {
if (!is_binary)
Convert_to_Binary_Image();
for (int i = 0; i < image.row * image.col; i++) {
if (image.data[i] == 0)
image.data[i] = 1;
else
image.data[i] = 0;
}
return 1;
}
int Morphology::Write(string filename) {
if (is_binary)
Convert_to_Grayscale_Image();
image.Write(filename);
Convert_to_Binary_Image();
return 1;
}
int Morphology::Count_Pixel() {
int count = 0;
for (int i = 0; i < image.row * image.col; i++){
if (image.data[i] > 0)
count++;
}
cout << endl << "The image has " << count << " points" << endl;
return count;
}
int Morphology::Count_Pathway(Image *image_label) {
vector<int> label_table;
// First Pass
int neighbor_index[2][9] = {{-1, -1, -1, 0, 0, 0, 1, 1, 1}, {-1, 0, 1, -1, 0, 1, -1, 0, 1}};
for (int i = 0; i < image.row; i++) {
for (int j = 0; j < image.col; j++) {
if (image.Get_Value(i, j, 0) == 1) {
// Find neighbor
Dataset pixel_neighbor = {};
int temp_min = INT_MAX;
int temp_max = 0;
for (int k = 0; k < 4; k++) {
pixel_neighbor[k] = (int)image_label->Get_Value(i + neighbor_index[0][k], j + neighbor_index[1][k], 0);
if (pixel_neighbor[k] > temp_max)
temp_max = pixel_neighbor[k];
if (pixel_neighbor[k] != 0 && pixel_neighbor[k] < temp_min)
temp_min = pixel_neighbor[k];
}
if (temp_max == 0) {
// Neighbor is empty
int label_number = label_table.size() + 1;
*image_label->Get_Pixel(i, j, 0) = (ImgPixel)label_number;
label_table.push_back(label_number);
} else {
*image_label->Get_Pixel(i, j, 0) = (ImgPixel)temp_min;
int min = label_table[temp_min - 1];
for (int k = 0; k < 4; k++) {
if (pixel_neighbor[k] != 0) {
label_table[pixel_neighbor[k] - 1] = min;
}
}
}
}
}
}
//Process table
for (int i = 0; i < label_table.size(); i++) {
if ((i + 1) > label_table[i]) {
for (int j = i; j < label_table.size(); j++) {
if (label_table[j] == (i + 1)) {
label_table[j] = label_table[i];
}
}
}
}
// Print count result
int count = 2;
vector <int> temp_number;
temp_number.push_back(label_table[0]);
for (int i = 1; i < label_table.size(); i++) {
int temp_value = label_table[i];
int res = 0;
for (int j = 0; j < temp_number.size(); j++) {
if (temp_value == temp_number[j]) {
res = 1;
break;
}
}
if (res == 0) {
temp_number.push_back(temp_value);
}
}
// Normalize the label
for (int i = 0; i < label_table.size(); i++) {
for (int j = 0; j < temp_number.size(); j++) {
if (label_table[i] == temp_number[j]) {
label_table[i] = (j + 1);
}
}
}
// Second Pass
for (int i = 0; i < image.row; i++) {
for (int j = 0; j < image.col; j++) {
if (image.Get_Value(i, j, 0) != 0) {
int label_number = image_label->Get_Value(i, j, 0);
*image_label->Get_Pixel(i, j, 0) = (ImgPixel)label_table[label_number - 1];
}
}
}
return temp_number.size();
}
///////////////////////////////////////////////////
///////////// S/T/K Morphology Private/////////////
///////////////////////////////////////////////////
int Morphology::Initialize_Pattern_Conditional(string filename, int size) {
ifstream fout(filename);
if (!fout.is_open()) {
cerr << "Cannot open the file " << filename << endl;
return 0;
}
filter = new Dataset[size];
char temp;
for (int i = 0; i < size; i++) {
for (int j = 0; j < 10; j++) {
fout.get(temp);
if (temp == '1' || temp == '0')
filter[i][j] = (int)temp - 48;
}
}
fout.close();
return 1;
}
int Morphology::Initialize_Pattern_Unconditional(string filename, int size) {
ifstream fout(filename);
if (!fout.is_open()) {
cerr << "Cannot open the file " << filename << endl;
return 0;
}
filter2 = new Dataset[size];
char temp;
for (int i = 0; i < size; i++) {
for (int j = 0; j < 10; j++) {
fout.get(temp);
if (temp == '1' || temp == '0' || temp == '2')
filter2[i][j] = (int)temp - 48;
}
}
fout.close();
return 1;
}
int Morphology::Compare_Dataset_Conditional(Dataset data1, Dataset data2) {
for (int i = 0; i < 9; i++) {
if (data1[i] != data2[i])
return 0;
}
return 1;
}
int Morphology::Compare_Dataset_Unconditional(Dataset data1, Dataset data2) {
for (int i = 0; i < 9; i++) {
int temp1 = data1[i];
int temp2 = data2[i];
if (temp2 == 2)
temp2 = 1;
if (temp1 != temp2)
return 0;
}
return 1;
}
///////////////////////////////////////////
///////////// Helper Function /////////////
///////////////////////////////////////////
int Morphology::Convert_to_Binary_Image() {
for (int i = 0; i < image.row * image.col; i++) {
if (image.data[i] > 250)
image.data[i] /= 255;
}
is_binary = 1;
return 1;
}
int Morphology::Convert_to_Grayscale_Image() {
for (int i = 0; i < image.row * image.col; i++)
image.data[i] *= 255;
is_binary = 0;
return 1;
}
| true |
881d91abb8eab2ec433e5b1368beb5a3eb44edbb | C++ | Anguei/OI-Codes | /LuoguCodes/P1100.cpp | UTF-8 | 195 | 2.609375 | 3 | [
"MIT"
] | permissive | //【P1100】高低位交换 - 洛谷 - 0
#include <iostream>
int main() {
unsigned long long n;
std::cin >> n;
std::cout << ((n & 0x0000ffff) << 16 | (n & 0xffff0000) >> 16) << std::endl;
} | true |
49a6001fbca611f51c6130c1767d39ce3cada98a | C++ | 10n1/RiotPrototype | /src/scene/ObjectManager.h | UTF-8 | 5,237 | 2.625 | 3 | [] | no_license | /*********************************************************\
File: ObjectManager.h
Purpose: Handles allocation of objects
Author: Kyle Weicht
Created: 3/31/2011
Modified: 5/20/2011 4:16:57 PM
Modified by: Kyle Weicht
\*********************************************************/
#ifndef _OBJECTMANAGER_H_
#define _OBJECTMANAGER_H_
#include "common.h"
#include "IListener.h"
#include "Thread.h"
#include "Object.h"
namespace Riot
{
class CObjectManager : public IListener
{
friend class Engine;
public:
// CObjectManager constructor
CObjectManager();
// CObjectManager destructor
~CObjectManager();
/***************************************\
| class methods |
\***************************************/
//-----------------------------------------------------------------------------
// Initialize
//-----------------------------------------------------------------------------
void Initialize( void );
//-----------------------------------------------------------------------------
// Shutdown
//-----------------------------------------------------------------------------
void Shutdown( void );
//-----------------------------------------------------------------------------
// CreateObject
// Creates a new object and returns its index
//-----------------------------------------------------------------------------
uint CreateObject( const char* szName, const char* szType );
uint CreateObject( uint32 nNameHash, uint32 nTypeHash );
uint CreateObjectFromFile( const char* szFilename );
//-----------------------------------------------------------------------------
// DeleteObject
// Deletes an object
//-----------------------------------------------------------------------------
void DeleteObject( uint nIndex );
//-----------------------------------------------------------------------------
// LoadObjectDeclaration
// Loads an object declaration from a file
//-----------------------------------------------------------------------------
void LoadObjectDeclaration( const char* szFilename );
//-----------------------------------------------------------------------------
// GetObject
// Returns an object
//-----------------------------------------------------------------------------
inline CObject& GetObject( uint nIndex );
//-----------------------------------------------------------------------------
// ProcessMessage
// Processes the input message
//-----------------------------------------------------------------------------
void ProcessMessage( const TMessage& msg );
//-----------------------------------------------------------------------------
// UpdateObjects
// Updates the objects
//-----------------------------------------------------------------------------
void UpdateObjects( float fDt );
//-----------------------------------------------------------------------------
// GetSizeOfType
// Returns the size of the type
//-----------------------------------------------------------------------------
uint GetSizeOfType( uint32 nTypeHash );
private:
//-----------------------------------------------------------------------------
// Parallel functions
// The task functions
//-----------------------------------------------------------------------------
static void ParallelProcessComponents( void* pData, uint nThreadId, uint nStart, uint nCount );
static void ParallelProcessComponentMessages( void* pData, uint nThreadId, uint nStart, uint nCount );
static void PipelineObjectUpdate( void* pData, uint nThreadId, uint nStart, uint nCount );
void AddPropertyToDefinition( TObjectDefinition& def, uint32 nTypeHash, uint32 nNameHash );
private:
/***************************************\
| class members |
\***************************************/
static const MessageType MessagesReceived[];
static const uint NumMessagesReceived;
CObject m_Objects[MAX_OBJECTS];
uint32 m_nFreeSlots[ MAX_OBJECTS ];
uint32 m_nActiveObjects[ MAX_OBJECTS ];
TObjectDefinition m_pObjectTypes[ 128 ];
uint32 m_nNumObjectTypes;
atomic_t m_nNumObjects;
sint32 m_nNumFreeSlots;
};
//-----------------------------------------------------------------------------
// GetObject
// Returns an object
//-----------------------------------------------------------------------------
CObject& CObjectManager::GetObject( uint nIndex )
{
return m_Objects[ nIndex ];
}
} // namespace Riot
#endif // #ifndef _OBJECTMANAGER_H_
| true |
97f24eb4f268036b61672767b45e47e0f615296d | C++ | Emily-ejag/PlayingwithCPP | /FunctionFun1/FunctionFun1/main.cpp | UTF-8 | 255 | 2.96875 | 3 | [] | no_license | #include <iostream>
using namespace std;
void printSomething(); //function prototipe, otherwise all funtions must be set before main
int main() {
return 0;
}
//funtion itself
void printSomething() {
cout << "Hello beautiful human being" << endl;
} | true |
cb718e9d117cf027981cef5ded18a03329f0c1c5 | C++ | Small-Embedded-Systems/assignment-2-asteroids-W15016306 | /asteroids/src/model.cpp | UTF-8 | 10,117 | 2.59375 | 3 | [] | no_license |
//Joshua Higgins - W15016306
//Connor Moore - W15012760
/* Asteroids model */
#include <stdbool.h>
#include <stdint.h>
#include <stdlib.h>
#include <math.h>
#include "model.h"
#include "utils.h"
#include "asteroids.h"
#include "view.h"
//variable Decleration
static const int heapsize = 25;
static node_t heap[heapsize];
static node_t *freenodes;
static int n = 0;
static float shot0[4] = {3000,3000,0,0},
shot1[4] = {3000,3000,0,0},
shot2[4] = {3000,3000,0,0},
shot3[4] = {3000,3000,0,0},
shot4[4] = {3000,3000,0,0};
static bool collision = false;
static int hits = 15;
static int newPosX, newPosY;
static int asteroidCount, totalAsteroids, destroyedAsteroids;
static int fired, firedCount;
static bool asteroidSplitMode = false;
double x1, y1, x2, y2, x3, y3;
static double acceleration = 0.0;
float bulletAcceleration = 4;
float newHeading, currentHeading;
//Heap Creation for linked list
void initialise_heap(void)
{
for( n=0 ; n<(heapsize-0) ; n++) {
heap[n].next = &heap[n+1];
}
heap[n].next = NULL;
freenodes = &heap[0];
}
node_t *allocnode(void)
{
node_t *node = NULL;
if( freenodes ) {
node = freenodes;
freenodes = freenodes->next;
}
return node;
}
void freenode(node_t *n)
{
n->next = freenodes;
freenodes = n;
}
//Games physics
void physics(void)
{
//shio movement
if(acceleration > 0.0)
{
player.p.x += acceleration*cos(radians(newHeading));
player.p.y += acceleration*sin(radians(newHeading));
if(acceleration > 0.5)
{
acceleration = acceleration-0.006;
}
else
{
acceleration = acceleration-0.002;
}
}
x1=-7*cos(radians(player.heading)) - 7*sin(radians(player.heading));
y1=-6*sin(radians(player.heading)) + 6*cos(radians(player.heading));
x2= -6* cos(radians(player.heading)) - -6*sin(radians(player.heading));
y2= -6* sin(radians(player.heading)) + -6*cos(radians(player.heading));
x3= 12*cos(radians(player.heading)) - sin(radians(player.heading));
y3= 12*sin(radians(player.heading)) + cos(radians(player.heading));
//Ship Wrapping
if(player.heading >= 360)
{
player.heading = 0;
}
if(player.heading <= -360)
{
player.heading = 0;
}
if(player.p.y < -10)
{
player.p.y = 272;
}
if(player.p.y > 282)
{
player.p.y = 0;
}
if(player.p.x > 490)
{
player.p.x = 40;
}
if(player.p.x < 40)
{
player.p.x = 480;
}
//destroy check
if(destroyedAsteroids == 11)
{
asteroidCount = 1;
totalAsteroids = 1;
destroyedAsteroids = 0;
}
}
///////////////////////////////////////////////////////////////
// Asteroid Control //
///////////////////////////////////////////////////////////////
//creates elements for list
void strike(struct particle *l)
{
if(asteroidCount < 5){
if(!asteroidSplitMode){
l->x = randrange(0,480);
l->y = randrange(0,270);
l->size = 2;
l->heading = randrange(-259,360);
l->ttl = 10;
l->active = true;
l->type = 0;
}
else
{
l->x = randrange(newPosX,newPosX+15);
l->y = randrange(newPosY,newPosY+15);
l->size = 1;
l->heading = randrange(-259,360);
l->ttl = 10;
l->active = true;
l->type = 0;
asteroidSplitMode = false;
}
asteroidCount++;
totalAsteroids++;
}
if((fired == 1)&&(firedCount <=5))
{
fired = 0;
l->x = player.p.x+x3;
l->y = player.p.y+y3;
l->active = true;
l->distanceCount = 0;
l->count = randrange(0,90000);
l->heading = player.heading;
l->type = 1;
if(shot0[3]==0)
{
shot0[2]=l->count;
shot0[3]=1;
}
else if(shot1[3]==0)
{
shot1[2]=l->count;
shot1[3]=1;
}
else if(shot2[3]==0)
{
shot2[2]=l->count;
shot2[3]=1;
}
else if(shot3[3]==0)
{
shot3[2]=l->count;
shot3[3]=1;
}
if(shot4[3]==0)
{
shot4[2]=l->count;
shot4[3]=1;
}
firedCount++;
}
else{
fired = 0;
}
}
///////////////////////////////////////////////////////////////
// List Managment //
///////////////////////////////////////////////////////////////
//updates elements in list
void update(struct particle *l)
{
for( ; l ; l = l->next ) {
if(firedCount < 0)
{
firedCount = 0;
}
if((!l->next->active)) {
if(l->type == 0)
{
destroyedAsteroids++;
struct particle *expired = l->next;
l->next = l->next->next;
freenode(expired);
}
if(l->type == 1)
{
firedCount--;
fired = 0;
struct particle *expired = l->next;
l->next = l->next->next;
freenode(expired);
}
}
if(l->type == 0){
//Bullets and Asteroids
int size;
if(l->size == 2)
{
size = 30;
}
else if(l->size == 1)
{
size = 15;
}
if ((((shot0[0] >= l->x-size)&&(shot0[0] <= l->x+size)) && ((shot0[1] >= l->y-size)&&(shot0[1] <= l->y+size))&&(shot0[3]==1)))
{
collision = true;
shot0[3]=0;
}
if ((((shot1[0] >= l->x-size)&&(shot1[0] <= l->x+size)) && ((shot1[1] >= l->y-size)&&(shot1[1] <= l->y+size))&&(shot1[3]==1)))
{
collision = true;
shot1[3]=0;
}
if ((((shot2[0] >= l->x-size)&&(shot2[0] <= l->x+size)) && ((shot2[1] >= l->y-size)&&(shot2[1] <= l->y+size))&&(shot2[3]==1)))
{
collision = true;
shot2[3]=0;
}
if ((((shot3[0] >= l->x-size)&&(shot3[0] <= l->x+size)) && ((shot3[1] >= l->y-size)&&(shot3[1] <= l->y+size))&&(shot3[3]==1)))
{
collision = true;
shot3[3]=0;
}
if ((((shot4[0] >= l->x-size)&&(shot4[0] <= l->x+size)) && ((shot4[1] >= l->y-size)&&(shot4[1] <= l->y+size))&&(shot4[3]==1)))
{
collision = true;
shot4[3]=0;
}
if(collision)
{
if(l->size == 2){
l->size=1;
asteroidSplitMode = true;
asteroidCount --;
newPosX = l->x;
newPosY = l->y;
if(firedCount >0){
firedCount-=1;
}
}
else if(l->size == 1)
{
l->active = false;
asteroidSplitMode = false;
if(firedCount > 0){
firedCount-=1;
}
}
collision = false;
}
//shield collision detection
if(!shield && ((player.p.x >= l->x-30)&&(player.p.x <= l->x+30)) && ((player.p.y >= l->y-30)&&(player.p.y <= l->y+30)))
{
lives--;
shield = true;
player.p.x = 240;
player.p.y = 136;
}
if(shield && ((player.p.x >= l->x-30)&&(player.p.x <= l->x+30)) && ((player.p.y >= l->y-30)&&(player.p.y <= l->y+30)))
{
shieldCollision = true;
damage--;
}
else
{
shieldCollision = false;
}
//astroid speed
if(l->size == 2)
{
l->x += 1*cos(radians(l->heading));
l->y += 1*sin(radians(l->heading));
}
if(l->size == 1){
l->x += 1.5*cos(radians(l->heading));
l->y += 1.5*sin(radians(l->heading));
}
//content wrapping
if(l->y > 300)
{
l->y = -30;
}
if(l->y < -30)
{
l->y = 300;
}
if(l -> x < 0)
{
l->x = 500;
}
if(l -> x > 500)
{
l->x = 0;
}
}
//Bullets
if(l->type ==1){
if(l->count == shot0[2])
{
if(shot0[3]==0)
{
l->active = false;
}
}
if(l->count == shot1[2])
{
if(shot1[3]==0)
{
l->active = false;
}
}
if(l->count == shot2[2])
{
if(shot2[3]==0)
{
l->active = false;
}
}
if(l->count == shot3[2])
{
if(shot3[3]==0)
{
l->active = false;
}
}
if(l->count == shot4[2])
{
if(shot4[3]==0)
{
l->active = false;
}
}
//Bullet Movement
l->x += 2*cos(radians(l->heading));
l->y += 2*sin(radians(l->heading));
l->distanceCount++;
if(l->distanceCount == 300)
{
l->active = false;
l->x = 3000;
l->y = 3000;
}
//Bullet Wrapping
if(l->x < 40)
{
l->x = 480;
}
else if(l->x > 480)
{
l->x = 40;
}
if(l->y < 0)
{
l->y = 270;
}
else if(l->y > 270)
{
l->y = 0;
}
//Bullet Position Tracking
if(l->count == shot0[2])
{
shot0[0]=l->x;
shot0[1]=l->y;
}
if(l->count == shot1[2])
{
shot1[0]=l->x;
shot1[1]=l->y;
}
if(l->count == shot2[2])
{
shot2[0]=l->x;
shot2[1]=l->y;
}
if(l->count == shot3[2])
{
shot3[0]=l->x;
shot3[1]=l->y;
}
if(l->count == shot4[2])
{
shot4[0]=l->x;
shot4[1]=l->y;
}
//Bullet/Ship Interaction
if(shield && l->active){
if(((player.p.x >= l->x-5)&&(player.p.x <= l->x+5)) && ((player.p.y >= l->y-5)&&(player.p.y <= l->y+5)))
{
damage-=10;
l->x = 3000;
l->y = 3000;
}
}
else if(((player.p.x >= l->x-5)&&(player.p.x <= l->x+5)) && ((player.p.y >= l->y-5)&&(player.p.y <= l->y+5))&&l->active)
{
lives--;
l->x = 3000;
l->y = 3000;
player.p.x = 240;
player.p.y = 136;
}
}
//shield reset
if(damage < 1)
{
lives --;
player.p.x = 240;
player.p.y = 136;
damage = 100;
shield = true;
}
}
}
struct particle *active = NULL;
void particle_system(void)
{
if((asteroidCount < 5)&&(totalAsteroids<10))
{
struct particle *spark = allocnode();
if(spark) {
spark->next = active;
active = spark;
strike(spark);
}
}
if((fired == 1) && (firedCount < 5))
{
struct particle *spark = allocnode();
if(spark) {
spark->next = active;
active = spark;
strike(spark);
}
}
update(active);
}
///////////////////////////////////////////////////////////////
// SHIP CONTROLS //
///////////////////////////////////////////////////////////////
void shipRight(void)
{
player.heading -=3;
}
void shipLeft(void)
{
player.heading +=3;
}
void shipUp(void)
{
newHeading = player.heading;
player.p.x += acceleration*cos(radians(player.heading));
player.p.y += acceleration*sin(radians(player.heading));
if(acceleration <= 1.5)
{
acceleration = acceleration+0.04;
}
}
void shipDown(void)
{
if(acceleration > 0.0)
{
acceleration = acceleration-0.004;
}
}
void setFire()
{
fired = 1;
}
| true |
50d334e7bcc2b822a00eb6315014f94e8791fec4 | C++ | tidus-open/ClickHouse | /src/Parsers/ClickGraph/ParserCypherEntity.cpp | UTF-8 | 1,762 | 2.625 | 3 | [
"Apache-2.0"
] | permissive | #include <Parsers/ClickGraph/ParserCypherEntity.h>
#include <Parsers/ClickGraph/ParserCypherMapList.h>
#include <Parsers/ClickGraph/ParserCypherAliasAndLabel.h>
#include <Parsers/ClickGraph/ASTCypherMapList.h>
#include <Parsers/ClickGraph/ASTCypherAliasAndLabel.h>
#include <Parsers/ClickGraph/ASTCypherNode.h>
namespace DB
{
bool ParserCypherEntity::parseImpl(Pos & pos, ASTPtr & node, Expected & expected)
{
ParserCypherMapList map_list_parser;
ParserCypherAliasAndLabel alias_and_label_parser;
ASTPtr map_list;
ASTPtr alias_and_label;
auto parseMapList = [&]() -> bool {
if(pos->type != TokenType::OpeningCurlyBrace)
{
expected.add(pos, " { ");
return false;
}
if(!map_list_parser.parse(pos, map_list, expected))
return false;
cypher_entity->addMapList(map_list);
return true;
};
if(pos->type != opening_type)
return false;
++pos;
if(pos->type == TokenType::BareWord || pos->type == TokenType::Colon)
{
if(!alias_and_label_parser.parse(pos, alias_and_label, expected))
return false;
cypher_entity->addAliasAndLabel(alias_and_label);
if(pos->type == TokenType::OpeningCurlyBrace){
if(!parseMapList())
return false;
}
} else if(pos->type == TokenType::OpeningCurlyBrace)
{
cypher_entity->addAnonAliasAndAllLabel();
if(!parseMapList())
return false;
} else if (pos->type == TokenType::ClosingRoundBracket)
{
cypher_entity->addAnonAliasAndAllLabel();
}else
{
expected.add(pos, " alias:label or list of { key:value }");
return false;
}
if(pos->type != closing_type)
{
String err = (getTokenName(closing_type) + String("or list of {key:value}"));
expected.add(pos, err.c_str());
return false;
}
++pos;
node = cypher_entity;
return true;
}
};
| true |
4186fc62c383a1101ac69ef16e1751e40f680ffe | C++ | efleming111/2DEngine | /2DEngine_Win32/2DEngine_Win32/src/engine/components/lilRigidbody.h | UTF-8 | 2,095 | 2.578125 | 3 | [] | no_license | //
// 2DEngine
// lilRigidbody.h
// Eric Fleming
// 5/18/2018
//
#pragma once
#include <list>
#include <string>
#include <Box2D\Box2D.h>
#include "lilComponent.h"
#define lilVector2D b2Vec2
#define lilMax b2Max
#define lilMin b2Min
class lilRigidbody : public lilComponent
{
public:
lilRigidbody(lilGameObject* gameObject) { mGameObject = gameObject; }
~lilRigidbody() {}
// Creates a rigidbody
// @ element - data for setting up the rigidbody
void Create(TiXmlElement* element);
// Update the game object of the rigidbodies position
void Update();
// Does nothing
void Destroy();
// Set weather rigidbody is active
void SetActive(bool isActive);
// Call back funciton for collision begin events
// Gameobject sub classes should override this function
void BeginContact(lilRigidbody* thisRigidbody, lilRigidbody* otherRigidbody);
// Call back funciton for collision end events
// Gameobject sub classes should override this function
void EndContact(lilRigidbody* thisRigidbody, lilRigidbody* otherRigidbody);
// Returns the gameobject this rigidbody is attached to
lilGameObject* GetGameObject() { return mGameObject; }
// Returns the velocity of the rigidbody
lilVector2D GetVelocity() { return mBody->GetLinearVelocity(); }
// Returns the position of the rigidbody
lilVector2D GetPosition() { return mBody->GetPosition(); }
// Sets the velocity of the rigidbody
// @ vector - a 2d vector reprresenting the current velocity of the rigidbody
void SetVelocity(lilVector2D vector) { mBody->SetLinearVelocity(vector); }
void SetPosition(lilVector2D position) { mBody->SetTransform(position, 0.0f); }
void SetOwnGravityScale(float scale) { mBody->SetGravityScale(scale); }
// Pointer to the name of the currently collided collider
std::string* colliderName;
protected:
b2Body* mBody;
std::list<std::string> mColliderNames;
private:
// No copying
lilRigidbody(const lilRigidbody& component) {}
void operator=(const lilRigidbody& component) {}
void AddBoxCollider(TiXmlElement* element);
void AddCircleCollider(TiXmlElement* element);
};
| true |
231df06af382d3d89c3ead6ca7dc624c65893423 | C++ | ldcduc/CS202 | /Week_5/ex01/function.cpp | UTF-8 | 1,867 | 3.40625 | 3 | [] | no_license | #include "function.h"
int Staff:: base_salary = 10;
int Staff:: paper_support = 40;
int Staff:: project_salary = 100;
void Staff:: set_static(int salary, int paper, int project) {
base_salary = salary;
paper_support = paper;
project_salary = project;
}
double Staff:: get_salary() {
return salary;
}
istream& operator>> (istream& is, TA& src) {
cout << "Name: ";
is >> src.name;
cout << "Number of work hours: ";
is >> src.work_hour;
return is;
}
istream& operator>> (istream& is, Lecturer& src) {
cout << "Name: ";
is >> src.name;
cout << "Number of lecturing hours: ";
is >> src.lecturing_hour;
cout << "Number of papers: ";
is >> src.paper_num;
return is;
}
istream& operator>> (istream& is, Researcher& src) {
cout << "Name: ";
is >> src.name;
cout << "Number of research projects: ";
is >> src.research_project;
cout << "Number of papers: ";
is >> src.paper_num;
return is;
}
void TA:: print() {
cout << name << " - Teaching Assistant\n";
cout << "Salary: " << salary << '$' << endl;
}
void TA:: calc_salary() {
salary = 0.8 * work_hour * base_salary;
}
void TA:: input(istream& is) {
is >> *this;
calc_salary();
}
void Lecturer:: print() {
cout << name << " - Lecturer\n";
cout << "Salary: " << salary << '$' << endl;
}
void Lecturer:: calc_salary() {
salary = 1.2 * lecturing_hour * base_salary + paper_support * paper_num;
}
void Lecturer:: input(istream& is) {
is >> *this;
calc_salary();
}
void Researcher:: print() {
cout << name << " - Researcher\n";
cout << "Salary: " << salary << '$' << endl;
}
void Researcher:: calc_salary() {
salary = 1.0 * research_project * project_salary * 1.1 * paper_support * paper_num;
}
void Researcher:: input(istream& is) {
is >> *this;
calc_salary();
}
| true |
ec7a1e2f27c464fa2a363cd651434a569da2b418 | C++ | sanasarjanjughazyan/Data_structures | /List.cpp | UTF-8 | 4,797 | 3.53125 | 4 | [] | no_license | #include <iostream>
#include <cassert>
#include <initializer_list>
template <typename T>
class List
{
template <typename T>
struct Node
{
T data;
Node* next;
Node(const T& data) : data(data), next(nullptr) {}
};
mutable size_t size;
Node<T>* head;
public:
template <typename T>
class iterator
{
Node<T>* ptr;
public:
iterator(Node<T>* head) : ptr(head) {}
T& operator* () const { assert(ptr != nullptr); return ptr->data; }
T& operator-> () const { assert(ptr != nullptr); return ptr->data; }
iterator& operator++ () { assert(ptr != nullptr); ptr = ptr->next; return *this; }
iterator operator++ (int) { assert(ptr != nullptr); iterator temp = *this; ptr = ptr->next; return temp; }
bool operator!= (const iterator& it) const { return ptr != it.ptr; }
bool operator== (const iterator& it) const { return ptr == it.ptr; }
void swap(iterator& it) { std::swap(ptr, it->ptr); }
};
List();
List(const size_t sz, const T& elem = T());
List(const List<T>& l);
List(const std::initializer_list<T>& l);
List<T>& operator= (const List<T>& l);
~List();
iterator<T> begin();
iterator<T> end();
size_t Size() const { return size; }
void pop_front();
iterator<T> erase(size_t ind) const;
void push_front(const T& elem);
iterator<T> insert(size_t ind, const T& elem) const;
void clear();
bool empty() const;
bool operator== (const List<T>& l) const;
};
//..............CONSTRUCTORS......................................................
template<typename T>
List<T>::List() : size(0), head(nullptr) {}
template<typename T>
List<T>::List(const size_t sz, const T& elem) : size(sz)
{
head = new Node<T>(elem);
Node<T>* start = head;
for (size_t i = 1; i < size; ++i)
{
start->next = new Node<T>(elem);
start = start->next;
}
}
template<typename T>
List<T>::List(const List<T>& l)
{
size = l.size;
head = new Node<T>(l.head->data);
Node<T>* to = head;
Node<T>* from = l.head;
for (size_t i = 1; i < size; ++i)
{
to->next = new Node<T>(from->next->data);
to = to->next;
from = from->next;
}
}
template<typename T>
List<T>::List(const std::initializer_list<T>& l) : size(l.size())
{
auto it = l.begin();
head = new Node<T>(*it);
Node<T>* start = head;
++it;
for (; it != l.end(); ++it)
{
start->next = new Node<T>(*it);
start = start->next;
}
}
template<typename T>
List<T>& List<T>::operator=(const List<T>& l)
{
if (this == &l)
return *this;
clear();
size = l.size;
head = new Node<T>(l.head->data);
Node<T>* to = head;
Node<T>* from = l.head;
for (size_t i = 1; i < size; ++i)
{
to->next = new Node<T>(from->next->data);
to = to->next;
from = from->next;
}
return *this;
}
template<typename T>
List<T>::~List()
{
clear();
}
//.......................functions..............................................
template<typename T>
List<T>::iterator<T> List<T>::begin()
{
iterator<T> it(head);
return it;
}
template<typename T>
List<T>::iterator<T> List<T>::end()
{
Node<T>* end = head;
while (end != nullptr)
end = end->next;
iterator<T> it(end);
return it;
}
template<typename T>
void List<T>::pop_front()
{
assert(size > 0);
Node<T>* temp = head;
head = head->next;
delete temp;
--size;
}
template<typename T>
List<T>::iterator<T> List<T>::erase(size_t ind) const
{
assert(ind < size);
Node<T>* start = head;
--ind; // for deleteing exactly ind elem (start->next)
while (ind--)
start = start->next;
Node<T>* temp = start->next;
start->next = temp->next;
delete temp;
--size;
iterator<T> it(start->next); // after deleteing elem
return it;
}
template<typename T>
void List<T>::push_front(const T & elem)
{
Node<T>* temp = new Node<T>(elem);
temp->next = head;
head = temp;
++size;
}
template<typename T>
List<T>::iterator<T> List<T>::insert(size_t ind, const T& elem) const
{
assert(ind < size);
Node<T>* start = head;
while (ind--)
start = start->next;
Node<T>* temp = new Node<T>(elem);
temp->next = start->next;
start->next = temp;
++size;
iterator<T> it(temp);
return it;
}
template<typename T>
void List<T>::clear()
{
while (size)
pop_front();
}
template<typename T>
bool List<T>::empty() const
{
return size == 0;
}
template<typename T>
bool List<T>::operator==(const List<T>& l) const
{
if (size != l.size)
return false;
Node<T>* start = head;
Node<T>* l_start = l.head;
for (size_t i = 0; i < size; ++i)
{
if (start->data != l_start->data)
return false;
start = start->next;
l_start = l_start->next;
}
return true;
}
//....................main........................................................
int main()
{
List<int> k = {4, 6, 3, 22, 5, 6};
List<int> l(k);
std::cout << (l == k) << std::endl;
for (auto it = l.begin(); it != l.end(); ++it)
std::cout << *(it) << " ";
std::cout << std::endl;
system("pause");
}
| true |
a502eb9166f31d481f439435562c3ffeb8335ccc | C++ | butchhoward/cmake_exmample | /tests/testlib.cpp | UTF-8 | 258 | 2.703125 | 3 | [
"MIT"
] | permissive | #include "gtest/gtest.h"
#include <modern/lib.hpp>
TEST( example, first_two_returned ) {
std::vector<double> values {1, 2., 3.};
auto [the_first, the_second] = first_two(values);
EXPECT_EQ( the_first, 1.0 );
EXPECT_EQ( the_second, 2.0 );
}
| true |
657e4c6702a7328e71531a31ca4c1243f1884d3d | C++ | vikash7325/AlgorithmDesign | /CharMaxLen.cpp | UTF-8 | 639 | 3.109375 | 3 | [] | no_license | /*Author Vikash Kumar Goldman Sachs*/
#include<iostream>
using namespace std;
char getMaxLen(string inp){
int len;
int max = 1;
char val;
char temp;
char Output = '\0';
int count = 1;
len = inp.length();
temp = inp[0];
val = temp;
for (int index=1; index < len; index++){
if (temp == inp[index]){
count++;
temp = inp[index];
val = temp;
}
else{
count=1;
temp = inp[index];
}
if (max < count){
max = count;
Output = inp[index];
}
}
return Output;
}
int main(){
string inp = "geeekk";
char out;
out = getMaxLen(inp);
cout<<"Result is "<<out<<"\n";
return 0;
}
| true |
2bb314a12c9d230138ec74b8f1647dd1b1f413d2 | C++ | WasiqMemon/level-based-mario | /hammer_bros.hpp | UTF-8 | 354 | 2.578125 | 3 | [] | no_license | #pragma once
#include "enemy.hpp"
class Hammer: public Enemy{ //Does not do damage, but pushes you away
SDL_Rect onimage[3]; // to make animation
int frame; // frame to be currently displayed for animation
public:
Hammer(SDL_Renderer*, SDL_Texture*, SDL_Rect);
void draw(); //Draws and moves hammer
~Hammer();
}; | true |
551e17b07cc20b14cff18869ce6efd0c0d3f05b4 | C++ | UCC-Programacion3-historico/segundo-parcial-el-equipo | /src/TPFinal/arbolmail.cpp | UTF-8 | 1,965 | 2.84375 | 3 | [] | no_license | #include "arbolmail.h"
arbolMail::arbolMail() {
raiz = NULL;
}
arbolMail::~arbolMail() {
}
nodoMail* arbolMail::put(email n,int modo) {
if (raiz == NULL) {
raiz = new nodoMail(n);
return raiz;
}
return raiz->put(n,modo);
}
void arbolMail::put(nodoMail* n,int modo) {
if (raiz == NULL) {
raiz = n;
return;
}
raiz->put(n,modo);
}
void arbolMail::remove() {
}
bool arbolMail::esVacio() {
if(raiz == NULL) return 1;
return 0;
}
void arbolMail::print() {
//Implementar para mostrar el mail en la interfaz grafica
}
nodoMail* nodoMail::put(email n,int modo) {
if(modo == 0) {
if(n.getDateScore() < mail.getDateScore()) {
if(izq != NULL) {
return izq->put(n,modo);
}
izq = new nodoMail(n);
return izq;
}
if(der != NULL) {
return der->put(n,modo);
}
der = new nodoMail(n);
return der;
}
if(n.compareMailsFrom(&mail) < 1) {
if(izq != NULL) {
return izq->put(n,modo);
}
izq = new nodoMail(n);
return izq;
}
if(der != NULL) {
return der->put(n,modo);
}
der = new nodoMail(n);
return der;
}
void nodoMail::put(nodoMail* n,int modo) {
if(modo == 0) {
if(n->getMail().getDateScore() < mail.getDateScore()) {
if(izq != NULL) {
izq->put(n,modo);
return;
}
izq = n;
return;
}
if(der != NULL) {
der->put(n,modo);
return;
}
der = n;
return;
}
if(n->getMail().compareMailsFrom(&mail) < 1) {
if(izq != NULL) {
izq->put(n,modo);
return;
}
izq = n;
return;
}
if(der != NULL) {
der->put(n,modo);
return;
}
der = n;
}
void nodoMail::print() {
}
| true |
9e927d6df7657ee0128fc88f400e37651e26dfca | C++ | wildstar84/fauxdacious | /src/libfauxdcore/inifile.cc | UTF-8 | 3,053 | 2.515625 | 3 | [
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | /*
* inifile.c
* Copyright 2013 John Lindgren
*
* 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
* provided with the distribution.
*
* This software is provided "as is" and without any warranty, express or
* implied. In no event shall the authors be liable for any damages arising from
* the use of this software.
*/
#include "inifile.h"
#include <string.h>
#include <glib.h> /* for g_ascii_isspace */
#include "audstrings.h"
#include "vfs.h"
static char * strskip (char * str, char * end)
{
while (str < end && g_ascii_isspace (* str))
str ++;
return str;
}
static char * strtrim (char * str, char * end)
{
while (end > str && g_ascii_isspace (end[-1]))
end --;
* end = 0;
return str;
}
EXPORT void IniParser::parse (VFSFile & file)
{
int size = 512;
StringBuf buf (size);
char * pos = buf;
int len = 0;
bool eof = false;
while (1)
{
char * newline = (char *) memchr (pos, '\n', len);
while (! newline && ! eof)
{
memmove (buf, pos, len);
pos = buf;
if (len >= size - 1)
{
size <<= 1;
buf.resize (size);
pos = buf;
}
len += file.fread (buf + len, 1, size - 1 - len);
if (len < size - 1)
eof = true;
newline = (char *) memchr (pos, '\n', len);
}
char * end = newline ? newline : pos + len;
char * start = strskip (pos, end);
char * sep;
if (start < end)
{
switch (* start)
{
case '#':
case ';':
break;
case '[':
if ((end = (char *) memchr (start, ']', end - start)))
handle_heading (strtrim (strskip (start + 1, end), end));
break;
default:
if ((sep = (char *) memchr (start, '=', end - start)))
handle_entry (strtrim (start, sep), strtrim (strskip (sep + 1, end), end));
break;
}
}
if (! newline)
break;
len -= newline + 1 - pos;
pos = newline + 1;
}
}
EXPORT bool inifile_write_heading (VFSFile & file, const char * heading)
{
StringBuf line = str_concat ({"\n[", heading, "]\n"});
return (file.fwrite (line, 1, line.len ()) == line.len ());
}
EXPORT bool inifile_write_entry (VFSFile & file, const char * key, const char * value)
{
StringBuf line = str_concat ({key, "=", value, "\n"});
return (file.fwrite (line, 1, line.len ()) == line.len ());
}
| true |
5eccdf78f3da9e15d4ed8c0c606fd68b05d945de | C++ | slashformotion/prc | /EXERCICES/3/rollingMean.cpp | UTF-8 | 789 | 3.046875 | 3 | [] | no_license | #include "rollingMean.hpp"
namespace moy
{
double RollingMean::total() const
{
double result=0;
for (auto &elem: tableau_)
{
result+=elem;
}
return result;
}
double RollingMean::mean() const
{
return (total() / double(count()));
}
void RollingMean::sample(const double e)
{
tableau_[position_] = e;
position_ = (position_+1)%count();
}
void RollingMean::fill(const double e)
{
for (auto &elem: tableau_)
{
elem = e;
}
}
std::ostream& operator<<(std::ostream &output, RollingMean const &r)
{
output << "{ "<< r.count() << "with mean" << r.mean() << "}";
return output;
}
} // namespace moy
| true |
d41afd5eeffda7c8071b3ab2c4e3acd1efead465 | C++ | mitkooo12345/excel-table-project | /OOP Project/Main.cpp | UTF-8 | 1,517 | 3.046875 | 3 | [] | no_license | #include <fstream>
#include "Cell.h"
#include"UserController.h"
const int BUFF_SIZE = 5000;
void printFileName(char* arr, int pos, int size) {
for (int i = pos; i < size; i++) {
std::cout << arr[i];
}
}
int getFileNameStart(char* arr, int size) {
for (int i = size; i > 0; i--) {
if (arr[i] == '\\') {
return i+1;
}
}
}
int main() {
char buffer[BUFF_SIZE];
UserController controller;
for (;;) {
controller.displayPromtp();
std::cin.getline(buffer, BUFF_SIZE);
int size = strlen(buffer)+1;
char* arr = new char[size];
for (int i = 0; i < size; i++) {
arr[i] = buffer[i];
}
memset(buffer, 0, BUFF_SIZE);
//exit
if (strcmp("exit", arr) == 0) {
std::cout << "Exiting the program...\n";
break;
//close
} else if (strcmp("close", arr) == 0) {
controller.close();
//open
} else if (strcmp("open", arr) == 0) {
//TODO:
std::cin.getline(buffer,BUFF_SIZE);
delete[] arr;
size = strlen(buffer) + 1;
arr = new char[size];
for (int i = 0; i < size; i++) {
arr[i] = buffer[i];
}
//open file
if (controller.open(arr)) {
std::cout << "Successfully opened \"";
printFileName(arr, getFileNameStart(arr, size),size-1);
std::cout << "\"\n";
} else {
std::cout << "File failed opening\n";
}
delete[] arr;
//save
} else if (strcmp("saveas", arr) == 0) {
//TODO:
controller.saveAs("");
//save as
} else if (strcmp("save", arr) == 0) {
//TODO:
controller.save();
}
}
return 0;
} | true |
7c8c09f7ca0e6c3ad154dfe208c7b63d4c3a232c | C++ | graphics-rpi/oasis_dependencies | /dynamic_projection/source/applications/magnification/cursor.cpp | UTF-8 | 5,733 | 2.796875 | 3 | [] | no_license | #include "cursor.h"
#include <random>
#include <ctime>
#include "canvas.h"
#include "argparser.h"
// Static variable since all cursors have same base model
bool Cursor::initialized_ = false;
GLuint Cursor::cursor_pos_vbo_ = 0;
GLuint Cursor::cursor_color_vbo_ = 0;
GLuint Cursor::cursor_vao_ = 0;
ArgParser* Cursor::args_;
glm::mat4 Cursor::model_ = glm::mat4(1.0);
void Cursor::Print( std::ostream & stream ) const {
stream << "ID: " << id_ << " POS: " << glm::to_string(pos_);
return;
}
Cursor::Cursor(ArgParser* args, int id, int x, int y) : id_(id) , pos_(x, y){
// Hack to do static vbo and vao setup.
if( !initialized_ ){
args_ = args;
GLfloat dummy_pos[(args_->num_cursors_ - 1) * 2];
GLfloat dummy_color[(args_->num_cursors_ - 1) * 3];
for( int i = 0; i < args_->num_cursors_ - 1; i++ ){
dummy_pos[i*2] = 0.0f;
dummy_pos[i*2+1] = 0.0f;
if( i % 4 == 0 ){
dummy_color[i*3] = 1.0f;
dummy_color[i*3+1] = 0.0f;
dummy_color[i*3+2] = 0.0f;
}
else if( i % 4 == 1 ){
dummy_color[i*3] = 0.0f;
dummy_color[i*3+1] = 1.0f;
dummy_color[i*3+2] = 0.0f;
}
else if( i % 4 == 2 ){
dummy_color[i*3] = 0.0f;
dummy_color[i*3+1] = 0.0f;
dummy_color[i*3+2] = 1.0f;
}
else{
dummy_color[i*3] = 1.0f;
dummy_color[i*3+1] = 1.0f;
dummy_color[i*3+2] = 1.0f;
}
}
glGenVertexArrays(1, &cursor_vao_);
glBindVertexArray(cursor_vao_);
glGenBuffers(1, &cursor_pos_vbo_);
glBindBuffer(GL_ARRAY_BUFFER, cursor_pos_vbo_);
glBufferData( GL_ARRAY_BUFFER, sizeof(dummy_pos), dummy_pos, GL_DYNAMIC_DRAW);
glGenBuffers(1, &cursor_color_vbo_);
glBindBuffer(GL_ARRAY_BUFFER, cursor_color_vbo_);
glBufferData( GL_ARRAY_BUFFER, sizeof(dummy_color), dummy_color, GL_DYNAMIC_DRAW);
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, cursor_pos_vbo_);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(2);
glBindBuffer(GL_ARRAY_BUFFER, cursor_color_vbo_);
glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 0, 0);
glBindVertexArray(0);
initialized_ = true;
}
rng_.seed( std::time(0));
rng_.discard( id * 3 );
double r = std::generate_canonical<double, 10>(rng_);
double g = std::generate_canonical<double, 10>(rng_);
double b = std::generate_canonical<double, 10>(rng_);
color_ = glm::vec3( (float)r, (float)g, (float)b );
glm::vec2 model_space = ConvertToModelCoordinates( pos_ );
Canvas::HandleGLError("AFTER CONVERT TO MODEL");
glBindBuffer(GL_ARRAY_BUFFER, cursor_pos_vbo_);
Canvas::HandleGLError("AFTER BIND BUFFER");
if( id != 0 ){
glBufferSubData( GL_ARRAY_BUFFER, (id-1) * sizeof(float) * 2, sizeof(float) * 2, glm::value_ptr(model_space));
Canvas::HandleGLError("AFTER BUFFER SUB DATA");
}
//glBindBuffer(GL_ARRAY_BUFFER, cursor_color_vbo_);
//glBufferSubData( GL_ARRAY_BUFFER, id * sizeof(float) * 3, sizeof(float) * 3, glm::value_ptr(color_));
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
void Cursor::Draw(){
glPointSize(10);
Canvas::HandleGLError("AFTER POINT SIZE");
glDepthMask( GL_FALSE );
glDisable( GL_DEPTH_TEST);
glBindVertexArray(cursor_vao_);
Canvas::HandleGLError("AFTER BINDING VAO");
glDrawArrays(GL_POINTS, 0, args_->num_cursors_ - 1 );
Canvas::HandleGLError("AFTER DRAWING ARRAY");
glBindVertexArray(0);
glEnable(GL_DEPTH_TEST);
glDepthMask( GL_TRUE );
Canvas::HandleGLError("AFTER UNBINDING VAO");
return;
}
glm::vec2 Cursor::ConvertToModelCoordinates(const glm::vec2 & input ){
float x = (float)input[0] / ((float)(args_->width_) / 2.0f) - 1.0f;
float y = (float)input[1] / ((float)(args_->height_) / 2.0f) - 1.0f;
y = y * -1.0f;
return glm::vec2(x, y);
}
AICursor::AICursor(ArgParser* args, int id, int x, int y) : Cursor( args, id, x, y ){
// initialize distributions
std::mt19937 rng;
rng.seed( std::time(0));
rng.discard( id * 2 );
x_dis_ = std::uniform_int_distribution<int>(0, args_->width_);
y_dis_ = std::uniform_int_distribution<int>(0, args_->height_);
GenerateNewDest();
}
void AICursor::Print(std::ostream & stream) const {
stream << "ID: " << id_ << " POS: " << glm::to_string(pos_) << "\n"
<< "VEL: " << glm::to_string(vel_) << "\n"
<< "DEST: " << glm::to_string(dest_);
return;
}
void AICursor::Update(){
glm::vec2 new_pos = pos_ + vel_;
glm::vec2 model_coordinates = ConvertToModelCoordinates( new_pos );
glBindBuffer( GL_ARRAY_BUFFER, cursor_pos_vbo_ );
glBufferSubData( GL_ARRAY_BUFFER, (id_ - 1) * sizeof(float) * 2, sizeof(float) * 2, glm::value_ptr(model_coordinates));
pos_ = new_pos;
//std::cout << "UL ORIGIN " << id_ << " : " << glm::to_string(pos_) << std::endl;
// compare distance for dest
if( glm::distance(pos_ , dest_) < glm::length(vel_)){
GenerateNewDest();
}
return;
}
void AICursor::GenerateNewDest(){
int x_dest = x_dis_(rng_);
int y_dest = y_dis_(rng_);
dest_ = glm::vec2(x_dest, y_dest);
vel_ = dest_ - pos_;
vel_ = glm::normalize(vel_);
return;
}
void ControlledCursor::Update(){
pos_ = next_pos_;
}
void ControlledCursor::Print( std::ostream & stream ) const{
stream << "ID: " << id_ << " POS: " << glm::to_string(pos_);
}
| true |
94d4f3cb21c3916296bf5ffa7f1c30cb014b37db | C++ | KaranPupneja/cpp-programming | /Level 4 - Advanced Programming Concepts/uca 110 - improved.cpp | UTF-8 | 738 | 3.53125 | 4 | [] | no_license | #include<iostream>
using namespace std;
int main()
{
int i, n, largest, sec_largest;
cout << "Enter number of values: ";
cin >> n;
int arr[n];
cout << "Enter values:\n";
for(i = 0; i < n; i++)
{
cin >> arr[i];
}
largest = arr[0];
for(i = 1; i < n; i++)
{
if(arr[i] != largest)
{
sec_largest = arr[i];
break;
}
}
while(i < n)
{
if (arr[i] > largest)
{
sec_largest = largest;
largest = arr[i];
}
else if (arr[i] > sec_largest)
{
sec_largest = arr[i];
}
i++;
}
cout << "Second largest: " << sec_largest;
return 0;
}
| true |
91e2af8e5425b5adc18b4be113402743300251be | C++ | kokeiro001/YamabiYagiNoHoko | /山火-ヤギの咆哮-/SpriteNode.hpp | SHIFT_JIS | 8,058 | 2.890625 | 3 | [
"MIT"
] | permissive | #pragma once
// Złقlj
/// XvCg̕`W
enum DrawPosType
{
DRAWPOS_ABSOLUTE, ///< EBhE̐W
DRAWPOS_RELATIVE, ///< eXvCg̑W
};
/// eNX`̓@
enum TextureDivType
{
TEX_DIVTYPE_NONE, ///< Ȃ
TEX_DIVTYPE_SIMPLE, ///<
TEX_DIVTYPE_USER, ///< [U[w肵`Qŕ
};
/// XvCg@\
class Sprite
: public boost::enable_shared_from_this<Sprite>
{
protected:
static const int MAX_TEXT = 256;
typedef std::list<boost::shared_ptr<Sprite>>::iterator Itr;
/// \[h
enum Mode{
SPR_NONE, /// \
SPR_TEXTURE, /// eNX``
SPR_TEXT, /// eLXg`
};
Mode m_mode;
bool m_isDraw;
DrawPosType m_posType;
std::string m_name;
float m_alpha;
// position
float m_x;
float m_y;
float m_z;
// size
float m_width;
float m_height;
float m_drawWidth;
float m_drawHeight;
// draw params
float m_centerX;
float m_centerY;
float m_rot;
float m_rotOffcetX;
float m_rotOffcetY;
// simple div
int m_divDrawTexIdx;
int m_divX, m_divY;
int m_divW, m_divH;
// user div
int m_srcX, m_srcY;
int m_srcW, m_srcH;
// texture params
Engine::Graphics::Resource::ITexture* m_pTexBuf;
ColorF m_textureColor;
TextureDivType m_divType;
// text data
bool m_useTextRenderer;
Engine::Graphics::Simple::ITextRenderer* m_pTextRdr;
Graphics::Resource::Text::ITextData* m_pTextData;
wchar_t m_text[MAX_TEXT];
ColorF m_textColor;
std::string m_fontName;
int m_fontSize;
boost::weak_ptr<Sprite> m_pParent;
std::list<boost::shared_ptr<Sprite>> m_children;
/// ݒ肳ꂽeNX`pāAgێ傫̏XVB
void UpdateSize();
public:
Sprite();
virtual ~Sprite();
boost::shared_ptr<Sprite> GetPtr() {
return shared_from_this();
}
void SetPos(float x, float y) {
m_x = x;
m_y = y;
}
void SetPos(float x, float y, float z) {
m_x = x;
m_y = y;
m_z = z;
}
std::string const GetName() { return m_name; }
void SetName(std::string name) { m_name = name; }
float const GetX() { return m_x; }
void SetX(float x) { m_x = x; }
float const GetY() { return m_y; }
void SetY(float y) { m_y = y; }
float const GetZ() { return m_z; }
void SetZ(float z) { m_z = z; }
float const GetAlpha() { return m_alpha; }
void SetAlpha(float alpha);
ColorF const GetColor();
void SetColor(ColorF color);
float const GetWidth() { return m_width; }
void SetWidth(float width) { m_width = width; }
float const GetHeight() { return m_height; }
void SetHeight(float height) { m_height = height; }
Point2DI GetOriginTexSize();
float const GetDrawWidth() { return m_drawWidth; }
void SetDrawWidth(float width) { m_drawWidth = width; }
float const GetDrawHeight() { return m_drawHeight; }
void SetDrawHeight(float height) { m_drawHeight = height; }
void SetCenter(float x, float y)
{
m_centerX = x;
m_centerY = y;
}
float const GetCenterX() { return m_centerX; }
void SetCenterX(float x) { m_centerX = x; }
float const GetCenterY() { return m_centerY; }
void SetCenterY(float y) { m_centerY = y; }
float const GetRot() { return m_rot; }
void SetRot(float rot) { m_rot = rot; }
float const GetRotOffcetX() { return m_rotOffcetX; }
void SetRotOffcetX(float x) { m_rotOffcetX = x; }
float const GetRotOffcetY() { return m_rotOffcetY; }
void SetRotOffcetY(float y) { m_rotOffcetY = y; }
int const GetDivDrawTexIdx() { return m_divDrawTexIdx; }
void SetDivDrawTexIdx(int idx) { m_divDrawTexIdx = idx; }
bool IsDraw() const { return m_isDraw; } ///< \E\̏Ԃ擾
void Show() { m_isDraw = true; } ///< `悷Ԃɂ
void Hide() { m_isDraw = false; } ///< `悵ȂԂɂ
/// EBhE̐Wŕ`悷Ԃɂ
void SetDrawPosAbsolute() { m_posType = DRAWPOS_ABSOLUTE; }
/// eXvCg̑Wŕ`悷Ԃɂ
void SetDrawPosRelative() { m_posType = DRAWPOS_RELATIVE; }
/// w肵GCAX̃eNX`pāA`惂[heNX`ɐݒ肷
void SetTextureMode(const char* name);
/// eNX``悷郂[h̐ؑւ
/// @param name eNX`̃GCAX
/// @param xnum X̕
/// @param ynum Y̕
/// @param width ̃eNX`̕(Zɂ덷̉e}邽߂ɕKv)
/// @param height ̃eNX`̍(Zɂ덷̉e}邽߂ɕKv)
void SetDivTextureMode(const char* name, int xnum, int ynum, int width, int height);
/// eNX``悷ہA`Ɏgp͈͂w肷
void SetTextureSrc(int x, int y, int w, int h);
void SetTextureColorF(ColorF color); ///< eNX`̕`Fݒ肷
/// eLXg`惂[hɂ
void SetTextMode(const char* text);
/// tHgw肵ăeLXg`惂[hɂ
void SetTextMode2(const char* text, const char* font);
/// `悷eLXgݒ肷
void SetText(const char* text);
/// eLXg擾
std::string GetText();
void SetTextColorF(ColorF color); ///< eLXg̕`Fݒ肷
void SetTextColor1(float r, float g, float b); ///< eLXg̕`Fݒ肷(0.0-1.0)
void SetTextColor255(int r, int g, int b); ///< eLXg̕`Fݒ肷(0-255)
void SetFontSize(int size); ///< eLXg`̃tHgTCYݒ肷
void AddChild(boost::shared_ptr<Sprite> chr); ///< qXvCglj
void RemoveChild(boost::shared_ptr<Sprite> chr);///< qXvCg폜
void ClearChild(); ///< qXvCgSč폜
void SetParent(boost::shared_ptr<Sprite> parent) { m_pParent = parent; } ///< eXvCgݒ肷
void RemoveFromParent(); ///< eXvCg玩g藣
void RemoveFromParentForce(); ///< eXvCg玩gIɐ藣({IɌĂяoȂ)
int GetChildCnt() { return m_children.size(); } ///< qXvCg̐擾
boost::shared_ptr<Sprite> GetChild(int idx); ///< qXvCg擾
/// g`悷
void DrawThis(Engine::Graphics::Simple::ISpriteRenderer* pSpr, float baseX, float baseY);
/// qXvCg܂߂ĕ`悷
void Draw(Engine::Graphics::Simple::ISpriteRenderer* pSpr, float baseX, float baseY, int level);
/// qXvCgZWŃ\[g(ZWقǎOɕ`悳)
void SortZ();
/// `̈̑傫擾
RectI GetBounds() { return RectI((int)m_x, (int)m_y, (int)m_width, (int)m_height); }
/// LuaŎgp@\o^
static void RegistLua();
};
/// `VXe
class DrawSystem
{
boost::shared_ptr<Sprite> m_baseSprite;
std::vector<boost::shared_ptr<Sprite>> m_sprites;
public:
bool OnPowerInit();
static DrawSystem* GetInst()
{
static DrawSystem inst;
return &inst;
}
void Dispose();
boost::shared_ptr<Sprite> GetSprite();
void AddSprite(boost::shared_ptr<Sprite> spr);
void RemoveSprite(boost::shared_ptr<Sprite> spr);
void ClearSprite();
void Draw();
static void RegistLua();
};
| true |
5826d0c851390dd412f7628f505dd8319889ec7e | C++ | KimiroDev/NIM | /variables.h | UTF-8 | 4,108 | 2.703125 | 3 | [] | no_license | #ifndef VARIABLES_H_INCLUDED
#define VARIABLES_H_INCLUDED
//#define _WIN32_WINNT 0x0601 //not always necessary
// Unicode needs to be enabled so that
//WHITESPACE character can be used
#ifndef UNICODE
#define UNICODE
#define UNICODE_WAS_UNDEFINED
#endif
#include <Windows.h>
#ifdef UNICODE_WAS_UNDEFINED
#undef UNICODE
#endif
#define WHITE_SPACE 9608
#include <vector>
#include <time.h>
#include <chrono>
#include <fstream>
const int screen_width = 80, screen_height = 25;//screen dimensions in columns/rows
int cell_count = screen_height * screen_width;//number of total cells on screen
int cell_size_px_x = 8, cell_size_px_y = 12; //used to calculate over which cell the mouse hovers
int pile_turn = 1;//iterates from pile 1 to 5 and updates them in order
int pile_selected = 1, coin_selected = 1;//remembers which pile/coin are selected (by keyboard input)
int default_turn = 0;//retains the preference of who starts the rounds
int turn = 0;//indicated who's player turn is
int scene = 1;//indicates the current scene(game/options/how_to_play scene)
int nrCoins[] = {0, 1, 2, 3, 4, 5};//keeps count of the coins (on each pile)
int mi, mj;//the line and column over which the mouse hovers
int score1 = 0, score2 = 0;//keep track of score
int difficulty = 2;//for single player mode:
//1 = easy, 2 = medium, 3 = hard
using text = wchar_t[];
text player1 = L"Jonathan\0 ";//can be modified at runtime
text player2 = L"Alice\0 ";//can be modified at runtime
text winner = L"\0\0\0\0\0\0\0\0\0\0";//for displaying the winner player
//text over_score = {175, 175, 175, 175, 175, 175, 175, 175, 0};
//text horizontal_line = {9472, 9472, 9472, 9472, 9472, 9472, 9472, 9472, 9472, 9472, 9472, 0};
bool running = true;//the boolean used for the game loop
bool updated = false;//indicates if the turn has changed
bool score_updated = false;//checks if the score has been updated
bool pile_updated = false;//only 1 pile can be updated in a single frame
bool widgets_updated;//makes sure multiple widgets can't be open in the same frame
bool restart_game = false;//when true, the piles get filled and the game begins again
bool game_begin = true;//if true, the game has just begun; used to block players to
//manually change default turn in the middle of the game
bool game_end = false;//game has ended (one player has won)
bool game_just_ended = false;//the first frame of the end of the game
bool game_mode = true;//false = 1 player, true = 2 players
wchar_t *screen = new wchar_t[screen_width*screen_height];//console graphic buffer
std::vector<const wchar_t*> names;
void resetScore()
{ score1 = score2 = 0; }
/* there are 3 scenes: howToPlay=0, game=1, options=2 */
void howToPlayScene()
{ scene = 0; }
void gameScene()
{ scene = 1; }
//optionsScene declared in options.h
size_t wstrlen(wchar_t* n)
{
size_t i = 0;
while(n[i])++i;
return i;
}
size_t wstrlen(const wchar_t* n)
{
size_t i = 0;
while (n[i])++i;
return i;
}
void wstrcpy(wchar_t * destination, const wchar_t *origin)
{
size_t it = 0;
while (origin[it] != 0)
{ destination[it] = origin[it]; ++it; }
destination[it] = 0;
}
void wstrcpy(wchar_t* destination, const char* origin)
{
size_t it = 0;
while (origin[it] != 0)
{
destination[it] = origin[it]; ++it;
}
destination[it] = 0;
}
void setrunningtofalse()//end game loop
{ running = false; }
void quit()
{ exit(1); }
void players_1()
{
game_mode = false;
restart_game = true;
if (default_turn == 1)
wstrcpy(player1, "Computer");
else wstrcpy(player2, "Computer");
default_turn = turn = 0;
}
void players_2()
{
game_mode = true;
restart_game = true;
if (turn == 1)
{
if (names[0][0] != player1[0])
{
wstrcpy(player1, names[1]);
}
else
wstrcpy(player1, names[0]);
}
else
{
if (names[0][0] != player2[0])
{
wstrcpy(player2, names[1]);
}
else
wstrcpy(player2, names[0]);
}
default_turn = turn = 0;
}
#endif // VARIABLES_H_INCLUDED
| true |
13bc841345f874f0ddc2c4485d9d76533fa422c8 | C++ | Barkole/sudoku | /src/Condition.h | UTF-8 | 2,318 | 2.625 | 3 | [
"MIT"
] | permissive | // Condition.h: interface for the CCondition class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_CONDITION_H__1AE36C4B_CAA5_4210_B176_990D8447C9BA__INCLUDED_)
#define AFX_CONDITION_H__1AE36C4B_CAA5_4210_B176_990D8447C9BA__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include <vector>
struct sCellValPair
{
sCellValPair() : pCell(NULL), val(0) {}
CCell* pCell;
int val;
};
class CCondition;
struct sConditionPart
{
CCondition* pCond;
CCell* m_pCells[COLS_IN_FIELD];//Hardcoding COLS_IN_FIELD == ROWS_IN_FIELD. If COLS_IN_FIELD != ROWS_IN_FIELD we must distinguish more.
//But i am to lazy to impl a game i do not have... (we should have as m_pCells a list with variable length then)
bool m_bCol;
sConditionPart() : pCond(NULL), m_bCol(false) { ZeroMemory( m_pCells , COLS_IN_FIELD * sizeof(CCell*) ); }
bool IsFull();//is full with numbers.
bool IsFull( int v , bool bWithForbids );
};
class CPartConditions
{
public:
sConditionPart m_PartConditions[3];
int GetFreePartCondCnt();
sConditionPart* GetOnlyFreePartCond( int v , bool bWithForbids );
};
class CCondition
{
public:
CCondition();
virtual ~CCondition();
CCell* m_Cells[VAL_CNT];
CCell* OnlyOneCellLeft( int v );
inline bool IsFree( int v ) { return m_Cells[v-1]->m_Val == 0; }
inline CCell* GetCell( int v ) { return (m_Cells[v-1]->m_Val == 0) ? NULL : m_Cells[v-1]; }
void SetVal( CCell* pCell , int v );
int GetFreeCellCnt();
int GetFreePartCondCnt( bool& bCol );
CCell* GetFirstFreeCell();
void GetFreeValues( std::vector<sValCellPair>& FreeValues );
void GetFreeCells( std::vector<CCell*>& FreeCells , std::vector<sValCellPair>* pNotThisOnes );
void GetFreeCells( std::vector<CCell*>& FreeCells , int ForbiddenValue , int NotPartIdx , bool bCol );
int AddFreeCells( int v , CCell** ppFreeCells , int CellIdx , int CellCnt );//for group-building
sConditionPart* GetOnlyFreePartCond( int v , bool bWithForbids );
bool DoGroupForbid( int CurFreeCellCnt );//returns true is a forbid was made
CString m_Desc;
LPCTSTR GetDesc() { return (LPCTSTR)m_Desc; }
std::vector<CPartConditions*> m_arPartConditions;
};
#endif // !defined(AFX_CONDITION_H__1AE36C4B_CAA5_4210_B176_990D8447C9BA__INCLUDED_)
| true |
6b64736a83e2d885555dabb5ffe7de5bd5be72e0 | C++ | everbgs/OpenCV-Testes | /projetos/simple1/first.cpp | UTF-8 | 511 | 2.5625 | 3 | [] | no_license | #include <opencv/cv.h>
#include <opencv/highgui.h>
int main(int argc, char** argv)
{
//Carregar a imagem
IplImage *img = argc > 1 ? cvLoadImage(argv[1], -1) : cvLoadImage("lena.jpg", -1);
//Cria uma janela para exibir a imagem
cvNamedWindow("tela1", CV_WINDOW_AUTOSIZE);
//Exibir a imagem
cvShowImage("tela1", img);
// Espera até fechar a janela
cvWaitKey(0);
// Libera o objeto imagem
cvReleaseImage(&img);
// Destruir a janela
cvDestroyWindow("tela1");
return 0;
}
| true |
c5b58a8f167937f600ff12a5d453a3d42e82704b | C++ | furkan-enes-polatoglu/C-Basics | /C 5 (Döngüler - While,Do-While,For )/For.cpp | ISO-8859-9 | 771 | 2.84375 | 3 | [] | no_license | #include <stdio.h>
#include <locale.h>
#include <math.h>
int main()
{
setlocale(LC_ALL,"Turkish");
/*
for(int i=1; i<=10; i++)
{
printf("%d - Hello World\n",i);
}
*/
/*
for(int i=1; i<=10; i++)
{
printf("%d saysnn kp = %d\n",i,i*i*i);
}
*/
/*
int s1,i;
printf("Say giriniz : "); scanf("%d",&s1);
for(i=1; i<=s1; i++)
{
printf("%d saysnn karekk = %.1f\n",i,sqrt(i));
}
*/
/*
int sayi;
printf("Say giriniz : "); scanf("%d",&sayi);
for(int i=sayi; i>=0; i--)
{
printf("%d\n",i);
}
*/
/*
int toplam=0;
for(int i=1; i<=10; i++)
{
toplam+=i;
}
printf("%d\n",toplam);
*/
}
| true |
264f0e6d7ad73643e0aaa2fb79daf1e31361848a | C++ | tgni/alg | /kaoYan/tsinghua/buildTree.cc | UTF-8 | 886 | 3.703125 | 4 | [] | no_license | #include <iostream>
#include <string>
using namespace std;
struct Node {
char val;
struct Node *lchild, *rchild;
Node(char c) : val(c), lchild(nullptr), rchild(nullptr) {}
};
typedef struct Node Tree;
Tree * createTree(string &str, int &i)
{
char c;
Node *T;
if ((c = str[i++]) == '#')
return NULL;
T = new Node(c);
T->lchild = createTree(str, i);
T->rchild = createTree(str, i);
return T;
}
void destroyTree(Tree *T)
{
if (T) {
if (T->lchild) {
destroyTree(T->lchild);
T->lchild = nullptr;
}
if (T->rchild) {
destroyTree(T->rchild);
T->rchild = nullptr;
}
delete T;
}
}
void inOrder(Tree *T)
{
if (!T) return;
inOrder(T->lchild);
cout << T->val << " ";
inOrder(T->rchild);
}
int main()
{
string str;
while (cin >> str) {
int i = 0;
Tree *T = createTree(str, i);
inOrder(T);
cout << endl;
destroyTree(T);
}
return 0;
}
| true |
5d31d365754d6faff19512e06f2be2351a2a82ec | C++ | adyjunior/adyjrpucgo | /3_semestre/workspace/Triangulo/Principal.cpp | ISO-8859-1 | 590 | 3.125 | 3 | [] | no_license | /*
* Principal.cpp
*
* Created on: 21/09/2009
* Author: jUniN C.Z.N
*/
#include<iostream>
#include<cmath>
#include"Triangulo.h"
using namespace std;
int main()
{
float a,b,c;
Triangulo t(a,b,c);
cout<<"Digite o Valor do lado a \n";
cin>>a;
cout<<"Digite o Valor do lado b \n";
cin>>b;
cout<<"Digite o Valor do lado c \n";
cin>>c;
if((a+b>c)||(a+c>b)||(b+c>a))
{
cout<<"O Triangulo eh"<<t.getTipoLado()<<" e "<<t.getTipoAngulo()<<endl;
cout<<"A area do Triangulo eh "<<t.getArea()<<endl;
}
else
cout<<"No eh Triangulo\n";
}
| true |
e8444713935a4203ba138df8292ae9a6c53cd147 | C++ | wobushimotou/Daily | /ACM/其它/week4/3.cpp | UTF-8 | 726 | 3.53125 | 4 | [] | no_license | /*
* 修改钟表显示时间
* 若时间显示正常,则不做修改,若不正常,则显示修改最少的数字来达到的最小合理时间
*
*
* */
#include <iostream>
using namespace std;
int main()
{
string time;
cin >> time;
string Hour,Minute,Second;
Hour = time.substr(0,2);
Minute = time.substr(3,2);
Second = time.substr(6,2);
if(Hour[0] > '2') {
Hour[0] = '0';
}
else if(Hour[0] == '2') {
if(Hour[1] >= '4')
Hour[1] = '0';
}
if(Minute[0] >= '6') {
Minute[0] = '0';
}
if(Second[0] >= '6') {
Second[0] = '0';
}
cout << Hour << ":" << Minute << ":" << Second;
return 0;
}
| true |
b104e1c143d8cc4f0fc7faba478cfb3c774f8a2f | C++ | 7kia/OOD | /Lab6/shape_drawing_lib/Triangle.cpp | UTF-8 | 439 | 2.6875 | 3 | [] | no_license | #include "stdafx.h"
#include "Triangle.h"
namespace shape_drawing_lib
{
CTriangle::CTriangle(const Point & p1, const Point & p2, const Point & p3)
: m_point1(p1)
, m_point2(p2)
, m_point3(p3)
{
}
void CTriangle::Draw(graphics_lib::ICanvas & canvas) const
{
canvas.MoveTo(m_point1.x, m_point1.y);
canvas.LineTo(m_point2.x, m_point2.y);
canvas.LineTo(m_point3.x, m_point3.y);
canvas.LineTo(m_point1.x, m_point1.y);
}
} | true |
6c68ee807c236f31e651727f1cce1d406156f959 | C++ | Sam-Evans-Thomson/Platformer_Live | /Window/Texture.h | UTF-8 | 2,116 | 2.640625 | 3 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: Texture.h
* Author: sam
*
* Created on 31 January 2016, 1:05 PM
*/
#ifndef TEXTURE_H
#define TEXTURE_H
#include <SDL.h>
#include <SDL_image.h>
#include <stdio.h>
#include <string>
#include "Window.h"
class Texture {
public:
Texture();
Texture(const Texture& orig);
virtual ~Texture();
int getWidth();
int getHeight();
void setColor( Uint8 red, Uint8 green, Uint8 blue );
void setBlendMode( SDL_BlendMode blending );
void setAlpha( Uint8 alpha );
void wipe();
void setAsRenderTarget();
void resetRenderTarget();
// These function will initialize this texture.
bool createBlank(int w, int h);
bool loadFromFile( std::string path );
bool loadFromRendererText( std::string textureText, SDL_Color textColor );
void setRenderSettings(SDL_Rect* _clip, double _angle, double _scaleX,
double _scaleY, SDL_RendererFlip _flip);
void setClip(SDL_Rect* _clip);
void setAngle(double _angle);
void setScale(double _scaleX, double _scaleY);
void setFlip(SDL_RendererFlip _flip);
// This renders the texture to the window.
void render(int x, int y);
void render(int x, int y, int w, int h);
void renderToTexture(Texture* _texture, int x, int y);
void renderToTexture(Texture* _texture, int x, int y, int w, int h);
bool lockTexture();
bool unlockTexture();
void* getPixels();
void copyPixels( void* _pixels );
int getPitch();
Uint32 getPixel32( unsigned int x, unsigned int y);
void free();
private:
SDL_Texture* texture;
void* pixels;
int pitch;
int width;
int height;
SDL_Rect* clip = NULL;
SDL_RendererFlip flip = SDL_FLIP_NONE;
double angle = 0.0;
double scaleX = 1.0;
double scaleY = 1.0;
void freeTexture();
};
#endif /* TEXTURE_H */
| true |
e7d76c542b5413bdca4b9e16d95481232fb59257 | C++ | sumagowri/CGMiniProject | /ShortestPath.h | UTF-8 | 1,796 | 3.015625 | 3 | [] | no_license | #include <stdio.h>
#include <limits.h>
#include <vector>
int minDistance(int dist[],
bool sptSet[], int size){
int min = INT_MAX, min_index;
for (int v = 0; v < size; v++)
if (sptSet[v] == false &&
dist[v] <= min)
min = dist[v], min_index = v;
return min_index;
}
void printPath(int parent[], int j, std::vector<int> &ans){
if (parent[j] == -1)
return;
printPath(parent, parent[j], ans);
ans.push_back(j);
}
void printSolution(int dist[], int n,
int parent[], int start, int end, std::vector<int> &ans)
{
ans.push_back(start);
printPath(parent, end, ans);
}
void dijkstra(std::vector<std::vector<int>> graph, int start, int end, std::vector<int> &ans)
{
int size = graph.size();
int dist[40];
bool sptSet[40];
int parent[40];
parent[start] = -1;
for (int i = 0; i < size; i++)
{
dist[i] = INT_MAX;
sptSet[i] = false;
}
dist[start] = 0;
for (int count = 0; count < size - 1; count++){
int u = minDistance(dist, sptSet, size);
sptSet[u] = true;
for (int v = 0; v < size; v++)
if (!sptSet[v] && graph[u][v] &&
dist[u] + graph[u][v] < dist[v])
{
parent[v] = u;
dist[v] = dist[u] + graph[u][v];
}
}
printSolution(dist, size, parent, start, end, ans);
}
int dist(int x1, int y1, int x2, int y2){
return ((x1 - x2)*(x1 - x2) + (y1 - y2)*(y1 - y2));
}
void calcPath(int node[40][2], int conn[40][40], int len, int start, int end, std::vector<int> &ans){
std::vector<std::vector<int>> graph(len, std::vector<int>(len, 0));
for (int i = 0; i<len; i++){
for (int j = i; j<40; j++){
if (conn[i][j] == 0){
graph[i][j] = 0;
graph[j][i] = 0;
}
else{
int d = dist(node[i][0], node[i][1], node[j][0], node[j][1]);
graph[i][j] = d;
graph[j][i] = d;
}
}
}
dijkstra(graph, start, end, ans);
} | true |
6962ac23798a07688b340fad24b96a9d5ab7bc9a | C++ | michaelwangzhenan/gitskills | /codeJam/codeJam/src/machineStudy.cpp | UTF-8 | 1,389 | 2.734375 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <string.h>
#include <stdlib.h>
//#include "../inc/machineStudy.hpp"
using namespace std;
#define MAX 26
int study[MAX][2] = {0};
void readNameGender(char* p)
{
char seps[] = ",";
char *token=NULL;
token = strtok( p, seps );
int i=0,index=0;
while( token != NULL )
{
if (i==0)
{
index = token[0]-65;
if (index<0 || index>=MAX)
break;
}
else
{
if (strcmp(token,"male")==0)
{
study[index][0]++;
}else{
study[index][1]++;
}
}
i++;
token = strtok( NULL, seps );
}
}
void printT()
{
char s='A';
for (int i=0;i<MAX;i++)
{
cout << s++ << ": ";
for (int j=0;j<2;j++)
cout << study[i][j]<< " ";
cout << endl;
}
}
void readPre(char* p)
{
int index = p[0]-65;
if (index<0 || index>=MAX)
index = 0;
cout << p<< ",";
if (study[index][0]>study[index][1])
cout << "male"<<endl;
else
cout << "female"<<endl;
}
void readTrainning(char *path,int flag)
{
ifstream in(path);
string line="";
if(in)
{
while (getline(in, line))
{
char *p = (char *)line.c_str();
if (flag ==0)
readNameGender(p);
else
readPre(p);
}
}
else
{
cout <<"no such file" << endl;
}
}
void predict(char * path)
{
readTrainning(path,1);
}
void machine(char *path)
{
readTrainning(path,0);
printT();
predict("D:/sourceCode/mycode/codeJam/codeJam/src/test.csv");
}
| true |
1dcf67dbc476b224a6bef0586aeaab68f2fa5604 | C++ | Sahil12S/MarioReborn | /GameEngine/States/GameState.h | UTF-8 | 833 | 2.515625 | 3 | [] | no_license | #ifndef GAME_STATE_H
#define GAME_STATE_H
#include "State.h"
#include "../Game.h"
#include "../Entities/Player.h"
namespace SSEngine
{
class GameState : public State
{
public:
GameState( GameDataRef data );
~GameState();
void Init() override;
void HandleInput( float dt ) override;
void Update( float dt ) override;
void Draw() override;
private:
/* Variables */
GameDataRef m_Data;
std::map<std::string, int> m_KeyBinds;
Player* m_Player;
sf::Sprite m_BackgroundSprite;
/* Functions */
// Initializers
void InitKeyBinds();
void InitTextures();
void InitFonts();
void InitSounds();
void InitButtons();
void InitVariables();
};
}
#endif // GAME_STATE_H | true |
d4712d5b098f28c17aa23f2a47073322c8a1a056 | C++ | liuq901/code | /CF/cd_59_A.cpp | UTF-8 | 344 | 2.734375 | 3 | [] | no_license | #include <cstdio>
#include <cstring>
#include <cctype>
char s[10000];
int main()
{
scanf("%s",s);
int n=strlen(s),a=0,b=0;
for (int i=0;i<n;i++)
if (islower(s[i]))
a++;
else
b++;
for (int i=0;i<n;i++)
s[i]=a>=b?tolower(s[i]):toupper(s[i]);
printf("%s\n",s);
return(0);
}
| true |
756dc6076f5e225723d806d2000a27a1d665f5d0 | C++ | Neverous/xivlo08-11 | /OBOZY/2010 - Październik/kkostniezer.cpp | UTF-8 | 643 | 2.90625 | 3 | [] | no_license | /* 2010
* Maciej Szeptuch
* XIV LO Wrocław
*/
#include<cstdio>
//#define DEBUG(args...) fprintf(stderr, args)
#define DEBUG(args...)
unsigned int tests,
number,
magic[21] = { 1,
1, 2, 6, 4, 2,
2, 4, 2, 8, 4,
4, 8, 4, 6, 8,
8, 6, 8, 2, 6,
};
inline unsigned int factorial(unsigned int num);
int main(void)
{
scanf("%u", &tests);
for(unsigned int t = 0; t < tests; ++ t)
{
scanf("%u", &number);
printf("%u\n", factorial(number));
}
return 0;
}
inline unsigned int factorial(unsigned int num)
{
unsigned int result = 1;
while(num)
{
result = (result * magic[num % 20]) % 10;
num /= 5;
}
return result;
}
| true |
ae57fdcb8be65376beaef6bc89e2f6366abbea24 | C++ | tmf7/Engine-of-Evil | /EngineOfEvil/source/Box.cpp | UTF-8 | 2,272 | 2.640625 | 3 | [] | no_license | /*
===========================================================================
Engine of Evil GPL Source Code
Copyright (C) 2016-2017 Thomas Matthew Freehill
This file is part of the Engine of Evil GPL game engine source code.
The Engine of Evil (EOE) Source Code is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
EOE Source Code is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with EOE Source Code. If not, see <http://www.gnu.org/licenses/>.
If you have questions concerning this license, you may contact Thomas Freehill at tom.freehill26@gmail.com
===========================================================================
*/
#include "Box.h"
//*************
// eBox::eBox
// DEBUG: assumes all three points are corners of a rectangle
// with the 0th point common to two edges
// and the 1st and 2nd points being on opposite corners
//*************
eBox::eBox(const eVec2 points[3]) {
eVec2 xAxis = points[1] - points[0];
eVec2 yAxis = points[2] - points[0];
float xLength = xAxis.Length();
float yLength = yAxis.Length();
float invLengthX = xLength == 0.0f ? 0.0f : 1.0f / xLength;
float invLengthY = yLength == 0.0f ? 0.0f : 1.0f / yLength;
extents.x = xLength * 0.5f;
extents.y = yLength * 0.5f;
axes[0] = xAxis * invLengthX;
axes[1] = yAxis * invLengthY;
center = (points[1] + points[2]) * 0.5f;
}
//*************
// eBox::eBox
// DEBUG: edges must be perpendicular
// and corner must be their point of intersection
//*************
eBox::eBox(const eVec2 & corner, const eVec2 edges[2]) {
float xLength = edges[0].Length();
float yLength = edges[1].Length();
float invLengthX = xLength == 0.0f ? 0.0f : 1.0f / xLength;
float invLengthY = yLength == 0.0f ? 0.0f : 1.0f / yLength;
extents.x = xLength * 0.5f;
extents.y = yLength * 0.5f;
axes[0] = edges[0] * invLengthX;
axes[1] = edges[1] * invLengthY;
center = corner + (edges[0] + edges[1]) * 0.5f;
} | true |
f92cb572de04e43e6d6b071f32a13b05d3fef19f | C++ | ranjiewwen/Everyday_Practice | /C--C++/设计模式/SingletonPatternEx/SingletonPatternEx/SinglePattern/SingletonFactory.cpp | UTF-8 | 542 | 2.78125 | 3 | [] | no_license | #include "SingletonFactory.h"
#include "FactoryA.h"
#include "FactoryB.h"
SingletonFactory *SingletonFactory::m_Instance = NULL;
SingletonFactory::GC SingletonFactory::gc;
SingletonFactory *SingletonFactory::GetInstance(FactoryEnum factory)
{
if (m_Instance == NULL)
{
switch (factory)
{
case kFactory_A:
m_Instance = new FactoryA();
break;
case kFactory_B:
m_Instance = new FactoryB();
default:
// This is the default, you can change the implementation
m_Instance = new FactoryA();
}
}
return m_Instance;
} | true |
cbee3d37517672107161ec44659a8bbd29a72dc6 | C++ | wowns9270/code_up | /백준/그리디/2457_공주님의 정원.cpp | UHC | 1,013 | 3.09375 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int n, st, en, cnt;
vector<pair<int, int>> arr;
bool cmp(pair<int, int> x, pair<int, int> y) {
if (x.first < y.first) {
return true;
}
return false;
}
int main() {
// Ǵ³ Ѵ.
cin >> n;
for (int i = 0; i < n; i++) {
int a, b, c, d; cin >> a >> b >> c >> d;
arr.push_back(make_pair(a * 100 + b, c * 100 + d));
}
sort(arr.begin(), arr.end(), cmp);
int date = 301;
int i = 0;
int state = 0;
int en = 0;
//301 Ѵ ó
while (date <= 1130 && i < n) {
state = 0;
for (int j = i; j < n; j++) {
//ó 301 ū ǿ ؼ ,
if (date < arr[j].first) break;
// ǿ ³ Ѵ.
if (en < arr[j].second) {
en = arr[j].second;
state = 1;
i = j;
}
}
if (state == 0) {
cout << "0";
return 0;
}
else {
date = en;
cnt++;
}
}
cout << cnt;
return 0;
} | true |
11b8d63aae149eb15fb23637602c6c23967679f3 | C++ | Abhiramon/ioi-training | /CodeForces/479A - Expression.cpp | UTF-8 | 431 | 2.734375 | 3 | [] | no_license | //11064485 2015-05-10 19:50:12 Hiasat98 A - Expression GNU C++ Accepted 15 ms 0 KB
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main() {
int a1, a2 , a3;
cin >> a1 >> a2 >> a3;
int ans = a1 + a2 * a3;
ans = max(ans,a1 * a2 * a3);
ans = max(ans,a1 * (a2 + a3));
ans = max(ans,(a1 + a2) * a3);
ans = max(ans,a1 + a2 + a3);
cout << ans << endl;
return 0;
}
| true |
441dbb9b1e5316a8f6e44a8efda907c7da79881c | C++ | GorMkrtchyan/Test1 | /ConsoleApplication2.cpp | UTF-8 | 6,161 | 3.0625 | 3 | [] | no_license | // ConsoleApplication2.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <list>
#include <algorithm>
#include <numeric>
#include <map>
#include <set>
#include <string>
#include <iterator>
#include <mutex>
#include"windows.h"
using namespace std;
mutex mMutex;
void callBackF(int val)
{
cout << "val = " << val << endl;
}
typedef void(*pFunc)(int);
void myFunc(pFunc p)
{
p(111);
}
void func(vector<string> vec)
{
vector<string>::iterator iter = vec.begin();
while (iter != vec.end())
{
cout << *iter << endl;
++iter;
}
}
void printVal(int cnt, string str)
{
mMutex.lock();
for (int i = 0; i < cnt; ++i)
{
cout << str << ", ";
Sleep(1000);
}
cout << endl;
mMutex.unlock();
}
string callBackFuncStr(string str, string(*pFunc)(string))
{
return pFunc(str);
}
string NewString(string str)
{
size_t i{0};
while (i < str.length())
{
if (str[i] >= 'a'&&str[i] < 'z' || str[i] >= 'A'&&str[i] < 'Z')
++str[i];
++i;
}
return str;
}
class A
{
private:
int iVal;
int mArray[5];
public:
A()
{
for (int i = 0; i < 5; ++i)
mArray[i] = i + 5;
cout << "Def constructor." << endl;
}
A(int n) :iVal(n) {}
bool operator==(const A& obj)
{
return this->iVal == obj.iVal;
}
A(const A& obj) //copy constructor
{
this->iVal = obj.iVal;
}
A operator=(const A& obj) //operator assignment
{
if (*this == obj)
return obj;
this->iVal = obj.iVal;
return *this;
}
int operator[](int k)
{
return mArray[k];
}
int getVal()
{
return iVal;
}
};
template<typename T>
class C
{
private:
T m_Val;
public:
C(T a) :m_Val(a)
{
cout << "Template" << endl;
}
T getVal() { return m_Val; }
};
void FuncForEach(int a)
{
cout << "arr[i] = " << a << ", " << endl;
}
int main()
{
vector<int> iVec(5);
vector<int> iVec2;
iota(iVec.begin(), iVec.end(), 1);
for (auto& x : iVec)
{
cout << x << endl;
}
cout << "size of int vector is: " << iVec.size() << endl;
list<double> dList(5);
iota(dList.begin(), dList.end(), 1.1);
for (auto& x : dList)
{
cout << x << endl;
}
cout << endl;
using iter = list<double>::iterator;
iter ii = dList.begin();
++ii;
dList.insert(ii, 5.5);
for (auto& x : dList)
{
cout << x << endl;
}
map<int, const char> mMap;
mMap.insert(pair<int, const char>(10, 'a'));
mMap.insert(pair<int, const char>(15, 'b'));
mMap.insert(pair<int, const char>(35, 'c'));
mMap.insert(pair<int, const char>(5, 'd'));
map<int, const char>::iterator iMap = mMap.find(45);
if (iMap != mMap.end())
cout << (*iMap).second << endl;
else
cout << "the value not found" << endl;
iMap = mMap.begin();
for (auto& x : mMap)
cout << x.first << " " << x.second << endl;
iMap = mMap.begin();
while (iMap != mMap.end())
{
if ((*iMap).second == 'd')
cout << (*iMap).first << endl;
++iMap;
}
/*{
string strArr[]{ "abcd", "asd", "asdf", "erte" };
vector<string> v1(strArr, strArr + sizeof(strArr) / sizeof(string));
vector<string> v2;
v2.push_back("qwer");
v2.push_back("sgfdfg");
v2.push_back("tyutyu");
v2.push_back("xdfgnb");
v2.push_back("uykl");
vector<string> v3(v2.begin(), v2.end());
vector<vector<string>> v4;
v4.push_back(v2);
v4.push_back(v1);
v4.push_back(v3);
vector<vector<string>>::iterator iVec2 = v4.begin();
while (iVec2 != v4.end())
{
func(*iVec2);
cout << endl;
++iVec2;
}
}
{
set<int> iSet;
iSet.insert(15);
iSet.insert(2);
iSet.insert(10);
iSet.insert(4);
iSet.insert(10);
cout << "set size is: " << iSet.size() << endl;
copy(iSet.begin(), iSet.end(), ostream_iterator<int>(cout, " "));
}
{
cout << endl;
map<int, string> map1;
map1[1] = "one";
map1[2] = "two";
map1[2] = "three";
map1.insert(pair<int, string>(4, "four"));
map1.insert(pair<int, string>(4, "five"));
map<int, string>::iterator mapIter = map1.begin();
while (mapIter != map1.end())
{
cout << mapIter->first << " " << mapIter->second << endl;
++mapIter;
}
}
{
cout << "Multithreading example" << endl;
thread th1(printVal, 5, "TH1");
thread th2(printVal, 9, "TH2");
th1.join();
th2.join();
}
{
string str{ "New String is z" };
cout << "The original string is: " << str << endl;
str = callBackFuncStr(str, &NewString);
cout << "The modified string is: " << str << endl;
unique_ptr<int> ptrI(new int(25));
cout << *ptrI << endl;
}
{
cout << "A class with copy copy constructor" << endl;
A ob1(125);
cout << "A class value is: " << ob1.getVal() << endl;
A ob2 = ob1;
cout << "A class value for ob2 is: " << ob2.getVal() << endl;
A ob3(130);
cout << "befor assigment ob3 is: " << ob3.getVal() << endl;
ob3 = ob2;
cout << "after assigment ob3 is: " << ob3.getVal() << endl;
ob3 = ob3;
cout << "after assigment ob3 is: " << ob3.getVal() << endl;
}
{
C<int> ob1(25);
cout << ob1.getVal() << endl;
C<double> ob2(25.5);
cout << ob2.getVal() << endl;
C<string> ob3("String");
cout << ob3.getVal() << endl;
}
{
int arr[]{ 1,2,6,7,5,9,4,1,6 };
int i{ 0 };
for_each(arr, arr + sizeof(arr) / sizeof(int), [&](int x)
{
cout << "arr[" << i << "] = " << x << ", " << endl;
++i;
});
cout << endl;
for_each(arr, arr + sizeof(arr) / sizeof(int), (&FuncForEach));
}
{
vector<int> iVect(10);
iota(iVect.begin(), iVect.end(), 2);
//copy(iVect.begin(), iVect.end(), ostream_iterator<int>(cout, ", "));
//vector<int>::const_iterator iter = iVect.cbegin();
const vector<int>::iterator iter = iVect.begin();
cout << *iter << endl;
*iter = 12;
cout << *iter << endl;
cout << endl;
}*/
{
A ob;
int k = ob[2];
for (int i = 0; i < 5; ++i)
cout << ob[i] << ", ";
cout << endl;
}
cout << endl;
cout << "C++ 11" << endl;
cout << "C++ interview" << endl;
return 0;
}
| true |
daea85975d136e834ddbf5cce910ce83da882fbf | C++ | hamstache/CoffeeDecorator | /Whip.cpp | UTF-8 | 251 | 2.90625 | 3 | [] | no_license |
#include "Whip.h"
Whip::Whip(const Beverage& beverage) : CondimentDecorator("Whip", beverage) { }
std::string Whip::description() const {
return "Whip, " + beverage().description();
}
double Whip::cost() const {
return 0.10 + beverage().cost();
}
| true |
19abebeabe1cdf34652ca2ac9185956016c6b66d | C++ | dytron/obi | /batalha2.cpp | UTF-8 | 380 | 2.953125 | 3 | [] | no_license | // OBI 2018 PJ Fase 3
#include <iostream>
using namespace std;
int main(){
int a1, d1, a2, d2;
cin >> a1 >> d1 >> a2 >> d2;
int v1 = 0, v2 = 0;
if (d1 == a2) v1 = 1;
if (d2 == a1) v2 = 1;
if (v1 == v2){
cout << -1 << endl;
}else{
if (v1){
cout << 1 << endl;
}else{
cout << 2 << endl;
}
}
}
| true |
427b9e0db83c6bc572be9d9878c185b4b38a0bda | C++ | yfisyak/star-sw | /garfield/Source/ComponentComsol.cc | UTF-8 | 23,058 | 2.546875 | 3 | [] | no_license | // Copied and modified ComponentAnsys123.cc
#include <iostream>
#include <fstream>
#include <sstream>
#include <stdlib.h>
#include <math.h>
#include <map>
#include "ComponentComsol.hh"
namespace Garfield {
ComponentComsol::ComponentComsol() : ComponentFieldMap() {
m_className = "ComponentComsol";
}
ComponentComsol::ComponentComsol(std::string mesh, std::string mplist,
std::string field)
: ComponentFieldMap() {
m_className = "ComponentComsol";
Initialise(mesh, mplist, field);
}
bool ends_with(std::string s, std::string t) {
return s.size() >= t.size() && s.substr(s.size() - t.size(), t.size()) == t;
}
int readInt(std::string s) {
std::istringstream iss(s);
int ret;
iss >> ret;
return ret;
}
bool ComponentComsol::Initialise(std::string mesh, std::string mplist,
std::string field) {
m_ready = false;
m_warning = false;
m_nWarnings = 0;
double unit = 100.0; // m
std::string line;
// Open the materials file.
materials.clear();
std::ifstream fmplist;
fmplist.open(mplist.c_str(), std::ios::in);
if (fmplist.fail()) {
std::cerr << m_className << "::Initialise:\n";
std::cerr << " Could not open result file " << mplist
<< " for reading.\n";
return false;
}
fmplist >> m_nMaterials;
for (unsigned int i = 0; i < m_nMaterials; ++i) {
Material newMaterial;
newMaterial.driftmedium = true;
newMaterial.medium = nullptr;
newMaterial.ohm = -1;
fmplist >> newMaterial.eps;
materials.push_back(newMaterial);
}
{
// add default material
Material newMaterial;
newMaterial.driftmedium = false;
newMaterial.medium = nullptr;
newMaterial.eps = newMaterial.ohm = -1;
materials.push_back(newMaterial);
m_nMaterials++;
}
std::map<int, int> domain2material;
int d2msize;
fmplist >> d2msize;
for (int i = 0; i < d2msize; ++i) {
int domain;
fmplist >> domain;
fmplist >> domain2material[domain];
}
fmplist.close();
nodes.clear();
std::ifstream fmesh;
fmesh.open(mesh.c_str(), std::ios::in);
if (fmesh.fail()) {
std::cerr << m_className << "::Initialise:\n";
std::cerr << " Could not open nodes file " << mesh << " for reading.\n";
return false;
}
do {
std::getline(fmesh, line);
} while (!ends_with(line, "# number of mesh points"));
nNodes = readInt(line);
std::cout << m_className << "::Initialise:\n";
std::cout << " Read " << nNodes << " nodes from file " << mesh << ".\n";
do {
std::getline(fmesh, line);
} while (line != "# Mesh point coordinates");
double minx = 1e100, miny = 1e100, minz = 1e100, maxx = -1e100, maxy = -1e100,
maxz = -1e100;
for (int i = 0; i < nNodes; ++i) {
Node newNode;
fmesh >> newNode.x >> newNode.y >> newNode.z;
newNode.x *= unit;
newNode.y *= unit;
newNode.z *= unit;
nodes.push_back(newNode);
minx = std::min(minx, newNode.x);
maxx = std::max(maxx, newNode.x);
miny = std::min(miny, newNode.y);
maxy = std::max(maxy, newNode.y);
minz = std::min(minz, newNode.z);
maxz = std::max(maxz, newNode.z);
}
std::cout << minx << " < x < " << maxx << "\n";
std::cout << miny << " < y < " << maxy << "\n";
std::cout << minz << " < z < " << maxz << "\n";
do {
std::getline(fmesh, line);
} while (line != "4 tet2 # type name");
do {
std::getline(fmesh, line);
} while (!ends_with(line, "# number of elements"));
nElements = readInt(line);
elements.clear();
std::cout << m_className << "::Initialise:\n";
std::cout << " Read " << nElements << " elements from file " << mesh
<< ".\n";
std::getline(fmesh, line);
// elements 6 & 7 are swapped due to differences in COMSOL and ANSYS
// representation
int perm[10] = {0, 1, 2, 3, 4, 5, 7, 6, 8, 9};
for (int i = 0; i < nElements; ++i) {
Element newElement;
newElement.degenerate = false;
for (int j = 0; j < 10; ++j) {
fmesh >> newElement.emap[perm[j]];
}
elements.push_back(newElement);
}
do {
std::getline(fmesh, line);
} while (line != "# Geometric entity indices");
for (int i = 0; i < nElements; ++i) {
int domain;
fmesh >> domain;
elements[i].matmap = domain2material.count(domain) ? domain2material[domain]
: m_nMaterials - 1;
}
fmesh.close();
std::map<Node, std::vector<int>, nodeCmp> nodeIdx;
for (int i = 0; i < nNodes; ++i) {
nodeIdx[nodes[i]].push_back(i);
}
std::cout << "Map size: " << nodeIdx.size() << std::endl;
std::ifstream ffield;
ffield.open(field.c_str(), std::ios::in);
if (ffield.fail()) {
std::cerr << m_className << "::Initialise:\n";
std::cerr << " Could not open field potentials file " << field
<< " for reading.\n";
return false;
}
do {
std::getline(ffield, line);
} while (line.substr(0, 81) !=
"% x y z "
" V (V)");
{
std::istringstream sline(line);
std::string token;
sline >> token; // %
sline >> token; // x
sline >> token; // y
sline >> token; // z
sline >> token; // V
sline >> token; // (V)
while (sline >> token) {
std::cout << m_className << "::Initialise:\n";
std::cout << " Reading data for weighting field " << token << ".\n";
nWeightingFields++;
wfields.push_back(token);
wfieldsOk.push_back(true);
sline >> token; // (V)
}
}
for (int i = 0; i < nNodes; ++i) {
Node tmp;
ffield >> tmp.x >> tmp.y >> tmp.z >> tmp.v;
tmp.x *= unit;
tmp.y *= unit;
tmp.z *= unit;
for (int j = 0; j < nWeightingFields; ++j) {
double w;
ffield >> w;
tmp.w.push_back(w);
}
int closest = -1;
double closestDist = 1;
const unsigned int nIdx = nodeIdx[tmp].size();
// for (int j : nodeIdx[tmp]) {
for (unsigned int k = 0; k < nIdx; ++k) {
int j = nodeIdx[tmp][k];
double dist = (tmp.x - nodes[j].x) * (tmp.x - nodes[j].x) +
(tmp.y - nodes[j].y) * (tmp.y - nodes[j].y) +
(tmp.z - nodes[j].z) * (tmp.z - nodes[j].z);
if (dist < closestDist) {
closestDist = dist;
closest = j;
}
}
if (closest == -1) {
std::cerr << m_className << "::Initialise:\n";
std::cerr << " Could not match the node from field potentials file: "
<< tmp.x << " " << tmp.y << " " << tmp.z << "\n.";
return false;
}
nodes[closest].v = tmp.v;
nodes[closest].w = tmp.w;
}
m_ready = true;
// for (int i = 0; i < nNodes; ++i) {
// double ex, ey, ez, v;
// Medium* m;
// int status;
// ElectricField(nodes[i].x, nodes[i].y, nodes[i].z, ex, ey, ez, v, m,
// status);
// std::cout << "Field at " << nodes[i].x << " " << nodes[i].y << " " <<
// nodes[i].z << ": " << ex << " " << ey << " " << ez << " " << v << "\n";
// }
// Establish the ranges.
SetRange();
UpdatePeriodicity();
return true;
}
bool ComponentComsol::SetWeightingField(std::string field, std::string label) {
double unit = 100.0; // m;
if (!m_ready) {
std::cerr << m_className << "::SetWeightingField:\n";
std::cerr << " No valid field map is present.\n";
std::cerr << " Weighting field cannot be added.\n";
return false;
}
// Open the voltage list.
std::ifstream ffield;
ffield.open(field.c_str(), std::ios::in);
if (ffield.fail()) {
std::cerr << m_className << "::Initialise:\n";
std::cerr << " Could not open field potentials file " << field
<< " for reading.\n";
return false;
}
// Check if a weighting field with the same label alm_ready exists.
int iw = nWeightingFields;
for (int i = nWeightingFields; i--;) {
if (wfields[i] == label) {
iw = i;
break;
}
}
if (iw == nWeightingFields) {
++nWeightingFields;
wfields.resize(nWeightingFields);
wfieldsOk.resize(nWeightingFields);
for (int j = 0; j < nNodes; ++j) {
nodes[j].w.resize(nWeightingFields);
}
} else {
std::cout << m_className << "::SetWeightingField:\n";
std::cout << " Replacing existing weighting field " << label << ".\n";
}
wfields[iw] = label;
wfieldsOk[iw] = false;
std::map<Node, std::vector<int>, nodeCmp> nodeIdx;
for (int i = 0; i < nNodes; ++i) {
nodeIdx[nodes[i]].push_back(i);
}
std::cout << "Map size: " << nodeIdx.size() << std::endl;
std::string line;
do {
std::getline(ffield, line);
} while (line !=
"% x y z "
" V (V)");
for (int i = 0; i < nNodes; ++i) {
Node tmp;
ffield >> tmp.x >> tmp.y >> tmp.z >> tmp.v;
tmp.x *= unit;
tmp.y *= unit;
tmp.z *= unit;
int closest = -1;
double closestDist = 1;
const unsigned int nIdx = nodeIdx[tmp].size();
// for (int j : nodeIdx[tmp]) {
for (unsigned int k = 0; k < nIdx; ++k) {
int j = nodeIdx[tmp][k];
double dist = (tmp.x - nodes[j].x) * (tmp.x - nodes[j].x) +
(tmp.y - nodes[j].y) * (tmp.y - nodes[j].y) +
(tmp.z - nodes[j].z) * (tmp.z - nodes[j].z);
if (dist < closestDist) {
closestDist = dist;
closest = j;
}
}
if (closest == -1) {
std::cerr << m_className << "::Initialise:\n";
std::cerr << " Could not match the node from field potentials file: "
<< tmp.x << " " << tmp.y << " " << tmp.z << "\n.";
return false;
}
nodes[closest].w[iw] = tmp.v;
}
return true;
}
void ComponentComsol::ElectricField(const double x, const double y,
const double z, double& ex, double& ey,
double& ez, Medium*& m, int& status) {
double v = 0.;
ElectricField(x, y, z, ex, ey, ez, v, m, status);
}
void ComponentComsol::ElectricField(const double xin, const double yin,
const double zin, double& ex, double& ey,
double& ez, double& volt, Medium*& m,
int& status) {
// Copy the coordinates
double x = xin, y = yin, z = zin;
// Map the coordinates onto field map coordinates
bool xmirr, ymirr, zmirr;
double rcoordinate, rotation;
MapCoordinates(x, y, z, xmirr, ymirr, zmirr, rcoordinate, rotation);
// Initial values
ex = ey = ez = volt = 0.;
status = 0;
m = NULL;
// Do not proceed if not properly initialised.
if (!m_ready) {
status = -10;
PrintNotReady("ElectricField");
return;
}
if (m_warning) PrintWarning("ElectricField");
// Find the element that contains this point
double t1, t2, t3, t4, jac[4][4], det;
const int imap = FindElement13(x, y, z, t1, t2, t3, t4, jac, det);
if (imap < 0) {
if (m_debug) {
std::cout << m_className << "::ElectricField:\n";
std::cout << " Point (" << x << ", " << y << ", " << z
<< " not in the mesh.\n";
}
status = -6;
return;
}
if (m_debug) {
PrintElement("ElectricField", x, y, z, t1, t2, t3, t4, imap, 10);
}
const Element& element = elements[imap];
const Node& n0 = nodes[element.emap[0]];
const Node& n1 = nodes[element.emap[1]];
const Node& n2 = nodes[element.emap[2]];
const Node& n3 = nodes[element.emap[3]];
const Node& n4 = nodes[element.emap[4]];
const Node& n5 = nodes[element.emap[5]];
const Node& n6 = nodes[element.emap[6]];
const Node& n7 = nodes[element.emap[7]];
const Node& n8 = nodes[element.emap[8]];
const Node& n9 = nodes[element.emap[9]];
// Tetrahedral field
volt = n0.v * t1 * (2 * t1 - 1) + n1.v * t2 * (2 * t2 - 1) +
n2.v * t3 * (2 * t3 - 1) + n3.v * t4 * (2 * t4 - 1) +
4 * n4.v * t1 * t2 + 4 * n5.v * t1 * t3 + 4 * n6.v * t1 * t4 +
4 * n7.v * t2 * t3 + 4 * n8.v * t2 * t4 + 4 * n9.v * t3 * t4;
ex = -(n0.v * (4 * t1 - 1) * jac[0][1] + n1.v * (4 * t2 - 1) * jac[1][1] +
n2.v * (4 * t3 - 1) * jac[2][1] + n3.v * (4 * t4 - 1) * jac[3][1] +
n4.v * (4 * t2 * jac[0][1] + 4 * t1 * jac[1][1]) +
n5.v * (4 * t3 * jac[0][1] + 4 * t1 * jac[2][1]) +
n6.v * (4 * t4 * jac[0][1] + 4 * t1 * jac[3][1]) +
n7.v * (4 * t3 * jac[1][1] + 4 * t2 * jac[2][1]) +
n8.v * (4 * t4 * jac[1][1] + 4 * t2 * jac[3][1]) +
n9.v * (4 * t4 * jac[2][1] + 4 * t3 * jac[3][1])) /
det;
ey = -(n0.v * (4 * t1 - 1) * jac[0][2] + n1.v * (4 * t2 - 1) * jac[1][2] +
n2.v * (4 * t3 - 1) * jac[2][2] + n3.v * (4 * t4 - 1) * jac[3][2] +
n4.v * (4 * t2 * jac[0][2] + 4 * t1 * jac[1][2]) +
n5.v * (4 * t3 * jac[0][2] + 4 * t1 * jac[2][2]) +
n6.v * (4 * t4 * jac[0][2] + 4 * t1 * jac[3][2]) +
n7.v * (4 * t3 * jac[1][2] + 4 * t2 * jac[2][2]) +
n8.v * (4 * t4 * jac[1][2] + 4 * t2 * jac[3][2]) +
n9.v * (4 * t4 * jac[2][2] + 4 * t3 * jac[3][2])) /
det;
ez = -(n0.v * (4 * t1 - 1) * jac[0][3] + n1.v * (4 * t2 - 1) * jac[1][3] +
n2.v * (4 * t3 - 1) * jac[2][3] + n3.v * (4 * t4 - 1) * jac[3][3] +
n4.v * (4 * t2 * jac[0][3] + 4 * t1 * jac[1][3]) +
n5.v * (4 * t3 * jac[0][3] + 4 * t1 * jac[2][3]) +
n6.v * (4 * t4 * jac[0][3] + 4 * t1 * jac[3][3]) +
n7.v * (4 * t3 * jac[1][3] + 4 * t2 * jac[2][3]) +
n8.v * (4 * t4 * jac[1][3] + 4 * t2 * jac[3][3]) +
n9.v * (4 * t4 * jac[2][3] + 4 * t3 * jac[3][3])) /
det;
// Transform field to global coordinates
UnmapFields(ex, ey, ez, x, y, z, xmirr, ymirr, zmirr, rcoordinate, rotation);
// std::cout << "ef @(" << xin << ", " << yin << ", " << zin << ") = " <<
// volt << "\n";
// Drift medium?
if (m_debug) {
std::cout << m_className << "::ElectricField:\n";
std::cout << " Material " << element.matmap << ", drift flag "
<< materials[element.matmap].driftmedium << "\n";
}
m = materials[element.matmap].medium;
status = -5;
if (materials[element.matmap].driftmedium) {
if (m && m->IsDriftable()) status = 0;
}
}
void ComponentComsol::WeightingField(const double xin, const double yin,
const double zin, double& wx, double& wy,
double& wz, const std::string& label) {
// Initial values
wx = wy = wz = 0;
// Do not proceed if not properly initialised.
if (!m_ready) return;
// Look for the label.
int iw = 0;
bool found = false;
for (int i = nWeightingFields; i--;) {
if (wfields[i] == label) {
iw = i;
found = true;
break;
}
}
// Do not proceed if the requested weighting field does not exist.
if (!found) return;
// Check if the weighting field is properly initialised.
if (!wfieldsOk[iw]) return;
// Copy the coordinates.
double x = xin, y = yin, z = zin;
// Map the coordinates onto field map coordinates
bool xmirr, ymirr, zmirr;
double rcoordinate, rotation;
MapCoordinates(x, y, z, xmirr, ymirr, zmirr, rcoordinate, rotation);
if (m_warning) PrintWarning("WeightingField");
// Find the element that contains this point.
double t1, t2, t3, t4, jac[4][4], det;
const int imap = FindElement13(x, y, z, t1, t2, t3, t4, jac, det);
// Check if the point is in the mesh.
if (imap < 0) return;
if (m_debug) {
PrintElement("WeightingField", x, y, z, t1, t2, t3, t4, imap, 10, iw);
}
const Element& element = elements[imap];
const Node& n0 = nodes[element.emap[0]];
const Node& n1 = nodes[element.emap[1]];
const Node& n2 = nodes[element.emap[2]];
const Node& n3 = nodes[element.emap[3]];
const Node& n4 = nodes[element.emap[4]];
const Node& n5 = nodes[element.emap[5]];
const Node& n6 = nodes[element.emap[6]];
const Node& n7 = nodes[element.emap[7]];
const Node& n8 = nodes[element.emap[8]];
const Node& n9 = nodes[element.emap[9]];
// Tetrahedral field
wx = -(n0.w[iw] * (4 * t1 - 1) * jac[0][1] +
n1.w[iw] * (4 * t2 - 1) * jac[1][1] +
n2.w[iw] * (4 * t3 - 1) * jac[2][1] +
n3.w[iw] * (4 * t4 - 1) * jac[3][1] +
n4.w[iw] * (4 * t2 * jac[0][1] + 4 * t1 * jac[1][1]) +
n5.w[iw] * (4 * t3 * jac[0][1] + 4 * t1 * jac[2][1]) +
n6.w[iw] * (4 * t4 * jac[0][1] + 4 * t1 * jac[3][1]) +
n7.w[iw] * (4 * t3 * jac[1][1] + 4 * t2 * jac[2][1]) +
n8.w[iw] * (4 * t4 * jac[1][1] + 4 * t2 * jac[3][1]) +
n9.w[iw] * (4 * t4 * jac[2][1] + 4 * t3 * jac[3][1])) /
det;
wy = -(n0.w[iw] * (4 * t1 - 1) * jac[0][2] +
n1.w[iw] * (4 * t2 - 1) * jac[1][2] +
n2.w[iw] * (4 * t3 - 1) * jac[2][2] +
n3.w[iw] * (4 * t4 - 1) * jac[3][2] +
n4.w[iw] * (4 * t2 * jac[0][2] + 4 * t1 * jac[1][2]) +
n5.w[iw] * (4 * t3 * jac[0][2] + 4 * t1 * jac[2][2]) +
n6.w[iw] * (4 * t4 * jac[0][2] + 4 * t1 * jac[3][2]) +
n7.w[iw] * (4 * t3 * jac[1][2] + 4 * t2 * jac[2][2]) +
n8.w[iw] * (4 * t4 * jac[1][2] + 4 * t2 * jac[3][2]) +
n9.w[iw] * (4 * t4 * jac[2][2] + 4 * t3 * jac[3][2])) /
det;
wz = -(n0.w[iw] * (4 * t1 - 1) * jac[0][3] +
n1.w[iw] * (4 * t2 - 1) * jac[1][3] +
n2.w[iw] * (4 * t3 - 1) * jac[2][3] +
n3.w[iw] * (4 * t4 - 1) * jac[3][3] +
n4.w[iw] * (4 * t2 * jac[0][3] + 4 * t1 * jac[1][3]) +
n5.w[iw] * (4 * t3 * jac[0][3] + 4 * t1 * jac[2][3]) +
n6.w[iw] * (4 * t4 * jac[0][3] + 4 * t1 * jac[3][3]) +
n7.w[iw] * (4 * t3 * jac[1][3] + 4 * t2 * jac[2][3]) +
n8.w[iw] * (4 * t4 * jac[1][3] + 4 * t2 * jac[3][3]) +
n9.w[iw] * (4 * t4 * jac[2][3] + 4 * t3 * jac[3][3])) /
det;
// Transform field to global coordinates
UnmapFields(wx, wy, wz, x, y, z, xmirr, ymirr, zmirr, rcoordinate, rotation);
}
double ComponentComsol::WeightingPotential(const double xin, const double yin,
const double zin,
const std::string& label) {
// Do not proceed if not properly initialised.
if (!m_ready) return 0.;
// Look for the label.
int iw = 0;
bool found = false;
for (int i = nWeightingFields; i--;) {
if (wfields[i] == label) {
iw = i;
found = true;
break;
}
}
// Do not proceed if the requested weighting field does not exist.
if (!found) return 0.;
// Check if the weighting field is properly initialised.
if (!wfieldsOk[iw]) return 0.;
// Copy the coordinates.
double x = xin, y = yin, z = zin;
// Map the coordinates onto field map coordinates.
bool xmirr, ymirr, zmirr;
double rcoordinate, rotation;
MapCoordinates(x, y, z, xmirr, ymirr, zmirr, rcoordinate, rotation);
if (m_warning) PrintWarning("WeightingPotential");
// Find the element that contains this point.
double t1, t2, t3, t4, jac[4][4], det;
const int imap = FindElement13(x, y, z, t1, t2, t3, t4, jac, det);
if (imap < 0) return 0.;
if (m_debug) {
PrintElement("WeightingPotential", x, y, z, t1, t2, t3, t4, imap, 10, iw);
}
const Element& element = elements[imap];
const Node& n0 = nodes[element.emap[0]];
const Node& n1 = nodes[element.emap[1]];
const Node& n2 = nodes[element.emap[2]];
const Node& n3 = nodes[element.emap[3]];
const Node& n4 = nodes[element.emap[4]];
const Node& n5 = nodes[element.emap[5]];
const Node& n6 = nodes[element.emap[6]];
const Node& n7 = nodes[element.emap[7]];
const Node& n8 = nodes[element.emap[8]];
const Node& n9 = nodes[element.emap[9]];
// Tetrahedral field
return n0.w[iw] * t1 * (2 * t1 - 1) + n1.w[iw] * t2 * (2 * t2 - 1) +
n2.w[iw] * t3 * (2 * t3 - 1) + n3.w[iw] * t4 * (2 * t4 - 1) +
4 * n4.w[iw] * t1 * t2 + 4 * n5.w[iw] * t1 * t3 +
4 * n6.w[iw] * t1 * t4 + 4 * n7.w[iw] * t2 * t3 +
4 * n8.w[iw] * t2 * t4 + 4 * n9.w[iw] * t3 * t4;
}
Medium* ComponentComsol::GetMedium(const double xin, const double yin,
const double zin) {
// Copy the coordinates
double x = xin, y = yin, z = zin;
// Map the coordinates onto field map coordinates
bool xmirr, ymirr, zmirr;
double rcoordinate, rotation;
MapCoordinates(x, y, z, xmirr, ymirr, zmirr, rcoordinate, rotation);
// Do not proceed if not properly initialised.
if (!m_ready) {
PrintNotReady("GetMedium");
return nullptr;
}
if (m_warning) PrintWarning("GetMedium");
// Find the element that contains this point
double t1, t2, t3, t4, jac[4][4], det;
const int imap = FindElement13(x, y, z, t1, t2, t3, t4, jac, det);
if (imap < 0) {
if (m_debug) {
std::cout << m_className << "::GetMedium:\n";
std::cout << " Point (" << x << ", " << y << ", " << z
<< ") not in the mesh.\n";
}
return nullptr;
}
const Element& element = elements[imap];
if (element.matmap >= m_nMaterials) {
if (m_debug) {
std::cerr << m_className << "::GetMedium:\n";
std::cerr << " Point (" << x << ", " << y
<< ") has out of range material number " << imap << ".\n";
}
return nullptr;
}
if (m_debug) {
PrintElement("GetMedium", x, y, z, t1, t2, t3, t4, imap, 10);
}
return materials[element.matmap].medium;
}
double ComponentComsol::GetElementVolume(const unsigned int i) {
if (i >= elements.size()) return 0.;
const Element& element = elements[i];
const Node& n0 = nodes[element.emap[0]];
const Node& n1 = nodes[element.emap[1]];
const Node& n2 = nodes[element.emap[2]];
const Node& n3 = nodes[element.emap[3]];
// Uses formula V = |a (dot) b x c|/6
// with a => "3", b => "1", c => "2" and origin "0"
const double vol =
fabs((n3.x - n0.x) *
((n1.y - n0.y) * (n2.z - n0.z) - (n2.y - n0.y) * (n1.z - n0.z)) +
(n3.y - n0.y) *
((n1.z - n0.z) * (n2.x - n0.x) - (n2.z - n0.z) * (n1.x - n0.x)) +
(n3.z - n0.z) * ((n1.x - n0.x) * (n2.y - n0.y) -
(n3.x - n0.x) * (n1.y - n0.y))) /
6.;
return vol;
}
void ComponentComsol::GetAspectRatio(const unsigned int i, double& dmin,
double& dmax) {
if (i >= elements.size()) {
dmin = dmax = 0.;
return;
}
const Element& element = elements[i];
const int np = 4;
// Loop over all pairs of vertices.
for (int j = 0; j < np - 1; ++j) {
const Node& nj = nodes[element.emap[j]];
for (int k = j + 1; k < np; ++k) {
const Node& nk = nodes[element.emap[k]];
// Compute distance.
const double dx = nj.x - nk.x;
const double dy = nj.y - nk.y;
const double dz = nj.z - nk.z;
const double dist = sqrt(dx * dx + dy * dy + dz * dz);
if (k == 1) {
dmin = dmax = dist;
} else {
if (dist < dmin) dmin = dist;
if (dist > dmax) dmax = dist;
}
}
}
}
} // namespace Garfield
| true |
cacba5eb9451e275433a25338f2022bb8e758cdf | C++ | Subzero-10/leetcode | /.history/57.insert-interval_20200728174058.cpp | UTF-8 | 5,174 | 3.15625 | 3 | [] | no_license | /*
* @lc app=leetcode id=57 lang=cpp
*
* [57] Insert Interval
*
* https://leetcode.com/problems/insert-interval/description/
*
* algorithms
* Hard (32.65%)
* Likes: 1657
* Dislikes: 185
* Total Accepted: 254.2K
* Total Submissions: 759.8K
* Testcase Example: '[[1,3],[6,9]]\n[2,5]'
*
* Given a set of non-overlapping intervals, insert a new interval into the
* intervals (merge if necessary).
*
* You may assume that the intervals were initially sorted according to their
* start times.
*
* Example 1:
*
*
* Input: intervals = [[1,3],[6,9]], newInterval = [2,5]
* Output: [[1,5],[6,9]]
*
*
* Example 2:
*
*
* Input: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]
* Output: [[1,2],[3,10],[12,16]]
* Explanation: Because the new interval [4,8] overlaps with
* [3,5],[6,7],[8,10].
*
* NOTE: input types have been changed on April 15, 2019. Please reset to
* default code definition to get new method signature.
*
*/
// @lc code=start
class Solution {
public:
vector<vector<int>> insert(vector<vector<int>>& intervals, vector<int>& newInterval) {
int situation = 0;//0:new interval; 1:connect; 2:include; 3:end
int len = intervals.size();
if (len==0||newInterval.size()<2)
{
return intervals;
}
int newleft = newInterval[0];
int newright = newInterval[1];
int lastpos = 0;
if (newright<intervals[0][0])
{
intervals.insert(intervals.begin(), newInterval);
}
for (int i = 0; i < len; i++)
{
int nowleft = intervals[i][0];
int nowright = intervals[i][1];
if (nowleft<=newleft && nowright>=newright)
{
situation = 3;
break;
}
if (newleft>nowright)
{
situation = 0;
continue;
}
else if (newleft<=nowright && newleft>=nowleft)
{
situation = 1;
lastpos = i;
continue;
}
if (situation == 0 && newleft<=nowleft)
{
lastpos = i;
if (newright<nowleft)
{
intervals.insert(intervals.begin()+i, newInterval);
situation = 3;
break;
}
if (newright>=nowleft&&newright<=nowright)
{
intervals[i][0] = newInterval[0];
situation = 3;
break;
}
if (newright<nowleft)
{
intervals[i][0] = newInterval[0];
intervals[i][1] = newInterval[1];
situation = 3;
break;
}
situation = 2;
}
if (situation == 2)
{
if (newright>=nowleft&&newright<=nowright)
{
intervals[i][0] = newInterval[0];
intervals.erase(intervals.begin()+lastpos+1,intervals.begin()+i);
situation = 3;
break;
}
if (newright<nowleft)
{
intervals[i-1][0] = newInterval[0];
intervals[i-1][1] = newInterval[1];
intervals.erase(intervals.begin()+lastpos+1,intervals.begin()+i-1);
situation = 3;
break;
}
}
if (situation == 1)
{
if (newright<nowleft)
{
if ((i-1)==lastpos)
{
intervals[lastpos][1] = newInterval[1];
situation = 3;
break;
}
else
{
intervals[lastpos][1] = newInterval[1];
intervals.erase(intervals.begin()+lastpos+1,intervals.begin()+i);
situation = 3;
break;
}
}
if (newright>=nowleft && newright<=nowright)
{
intervals[i][0] = intervals[lastpos][0];
intervals.erase(intervals.begin()+lastpos,intervals.begin()+i);
situation = 3;
break;
}
}
}
switch (situation)
{
case 0:
intervals.push_back(newInterval);
break;
case 1:
intervals[len-1][1] = newright;
break;
case 2:
intervals[len-1][1] = newInterval[1];
intervals[len-1][0] = newInterval[0];
intervals.erase(intervals.begin()+lastpos+1,intervals.end()-1);
break;
case 3:
return intervals;
break;
default:
break;
}
return intervals;
}
};
// @lc code=end
| true |
99af6a0e655b7ea821c0fcf995bc834e7565ba1c | C++ | FilipaDurao/Advent-Of-Code-2017 | /Day 4/Day 4 Part 2.cpp | UTF-8 | 1,003 | 3.3125 | 3 | [] | no_license | /*
* Day 4 Part 2.cpp
*
* Created on: 04/12/2017
* Author: filipa
*/
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <sstream>
#include <algorithm>
using namespace std;
bool checkRep(string input){
stringstream ss;
ss << input;
vector<string> words;
string word;
while(!ss.eof()){
ss >> word;
words.push_back(word);
}
for(unsigned int i = 0; i < words.size(); i++){
sort(words.at(i).begin(), words.at(i).end());
}
sort(words.begin(), words.end());
for(unsigned int i = 0; i < words.size()-1; i++){
if(words.at(i) == words.at(i+1))
return false;
}
return true; // Is valid, no repetitions
}
int main(){
ifstream in_stream("Input Day 4.txt");
string input;
vector<string> inputs;
while(!in_stream.eof()){
getline(in_stream, input);
inputs.push_back(input);
}
unsigned int cont = 0;
for(unsigned int i = 0; i < inputs.size(); i++){
if(checkRep(inputs.at(i)))
cont ++;
}
cout << cont;
return 0;
}
| true |
11dbe4fdc17bf1642d2305d592ca1bb47572eb7d | C++ | joepisconte/Envio-y-Recepcion-de-Trama-Serial-Arduino | /ReceptorSerial/ReceptorSerial.ino | UTF-8 | 1,786 | 3.34375 | 3 | [
"MIT"
] | permissive | /* Recepción de Trama Serial de datos separados por comas
* Se espera un mensaje en el formato: -12.5, 15.6, -0.7, 26.0, 3.6, 27.1$
* Este programa requiere un $(dolar) para indicar el final de la trama
*/
const int NUMERO_DE_DATOS = 30; // numero de campos esperados
int fieldIndex = 0; // el actual campo siendo reciBido
String values[NUMERO_DE_DATOS]; // array conteniendo los valores de todos los campos
void setup()
{
Serial.begin(9600); // inicializa el puerto serial a 115200 baudios
}
void loop()
{
if( Serial.available())
{
char ch = Serial.read(); // Lee un caracter el buffer del puerto serial
if(ch >= '0' && ch <= '9' || ch == '-' || ch == '.' || ch == ' ')
// Si ... el dato el caracter esta entre el '0' - '9' y o es '-','.' o ' ' ... entonces
{
values[fieldIndex] = values[fieldIndex] + ch; // acumula el valor en el campo respectivo
}else
if (ch == ',') // si ... detecta coma ...entonces
{
if(fieldIndex < NUMERO_DE_DATOS-1)
fieldIndex++; // incrementa el índice del siguiente campo, siempre que, fieldIndex sea menor que 29
}
else
{
//cualquier caracter diferente (a un número, punto o coma) termina la adquisición
//ese caracter sería el "$"
Serial.println("Datos Recibidos por el Puerto Serial:");
for(int i=0; i <= fieldIndex; i++)
{
//----- Imprime los datos ----
Serial.println(values[i]); //reemplazar por lo que se desee hacer con cada unos de los datos
//----------------------------
values[i] = '0'; // setea los valores a 0 para almacenar nuevo dato
}
fieldIndex = 0; // listo para empezar de nuevo
}
}
}
| true |
309b0851eaf3135527d726580cb03534fa9b85ed | C++ | mnm1021/lz78 | /hw2.cpp | UTF-8 | 630 | 2.859375 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include "lz78.h"
using namespace std;
int main(int argc, char** argv)
{
string input, encoded_string;
ifstream input_file (argv[1]);
ofstream encoded_file (argv[2]);
ofstream decoded_file (argv[3]);
stringstream str_stream;
str_stream << input_file.rdbuf();
input = str_stream.str();
cout << "encoding..." << endl;
encoded_string = lz78_encode (input);
cout << "encoding finished. writing to file..." << endl;
encoded_file << encoded_string;
cout << "decoding..." << endl;
decoded_file << lz78_decode (encoded_string);
return 0;
}
| true |
66fab56f92f0c3191219651dc66988b8f7bc2812 | C++ | vinicius-godoy/Projetos-Faculdade | /teatro-c++/main.cpp | ISO-8859-1 | 4,897 | 3.421875 | 3 | [] | no_license | #include <iostream>
#include <iomanip>
#include <cstdlib>
#include <clocale>
#include "contador.h"
#include "teatro.h"
//Namespaces
using namespace std;
//Prottipos de Funo
void imprimir_teatro(int, int, Teatro&);
void menu_compra(Teatro&, Contador&);
void menu_troca(Teatro&);
void menu_devolucao(Teatro&, Contador&);
void titulo_teatro(Teatro&);
//Funes usam passagem por referncia para que ela no chame o destrutor de Teatro ao final dela
//Variveis Globais
int colunas, linhas;
int main()
{
setlocale(LC_ALL, "portuguese");
int opc;
cout << "================|Teatro Tal|================" << endl;
cout << "Digite o nmero de fileiras: ";
cin >> colunas;
cout << "Digite o nmero de cadeiras por fileira: ";
cin >> linhas;
Teatro t1(linhas, colunas);
Contador c1(colunas*linhas);
/* Menu */
do{
system("cls");
titulo_teatro(t1);
imprimir_teatro(colunas, linhas, t1);
cout << endl << "Lugares Comprados: " << c1.getNum() << endl;
cout << "1 - Comprar Lugar" << endl;
cout << "2 - Trocar Lugar" << endl;
cout << "3 - Devolver Lugar" << endl;
cout << "0 - Sair" << endl;
cout << endl << "Selecione sua opo -> "; cin >> opc;
system("cls"); //Limpa a tela antes de trocar de menu
switch(opc)
{
case 0:
exit(EXIT_SUCCESS);
break;
case 1:
menu_compra(t1, c1);
break;
case 2:
menu_troca(t1);
break;
case 3:
menu_devolucao(t1, c1);
break;
default:
cout << "Digite uma opo vlida!\a";
system("pause");
}
}while(opc != 0);
return 0;
}
//Definies de Funo
void imprimir_teatro(int col, int lin, Teatro& t1)
{
//Espao antes da numerao das fileiras
cout << " ";
//Lao para numerao das fileiras
for(int i = 1; i <= col; i++){
if(i < 10){cout << " " << i << " ";
}else if(i < 100){cout << " " << i;}
}
cout << endl;
//Lao para impresso da matriz e da numerao das cadeiras
for(int i = 0; i < lin; i++){
cout << setw(3) << i + 1;
for(int j = 0; j < col; j++){
cout << "[" << t1.getLugar(i, j) << "]";
}
cout << endl;
}
}
void menu_compra(Teatro& t1, Contador& c1)
{
int col, lin, err;
titulo_teatro(t1);
imprimir_teatro(colunas, linhas, t1);
cout << endl << "Digite a cadeira e a fileira do lugar que deseja comprar: ";
cin >> lin >> col;
lin = lin - 1; col = col - 1; //Remove um pra matriz poder comear com 1, 1 e no 0, 0
err = t1.reservar(lin, col);
if(err == 1){
c1.aumentarNum();
cout << endl << "Lugar Reservado! ";
system("pause");
}else{
cout << endl << "Esse lugar j foi reservado! \a";
system("pause");
}
}
void menu_troca(Teatro& t1)
{
int col, lin, col2, lin2, err;
titulo_teatro(t1);
imprimir_teatro(colunas, linhas, t1);
cout << endl << "Digite a cadeira e a fileira do lugar que deseja trocar: ";
cin >> lin >> col;
cout << "Digite a cadeira e a fileira do lugar que deseja pegar: ";
cin >> lin2 >> col2;
lin = lin - 1; col = col - 1; lin2 = lin2 - 1; col2 = col2 - 1;
err = t1.trocar(lin, col, lin2, col2);
if(err == 0){
cout << endl << "O lugar que voc est tentando trocar no foi reservado ainda! \a";
system("pause");
}else if(err < 0){
cout << endl << "Voc no pode trocar o seu lugar por um que j foi reservado! \a";
system("pause");
}else{
cout << endl << "Lugar Trocado! ";
system("pause");
}
}
void menu_devolucao(Teatro& t1, Contador& c1)
{
int col, lin, err;
titulo_teatro(t1);
imprimir_teatro(colunas, linhas, t1);
cout << endl << "Digite a cadeira e a fileira do lugar que deseja devolver: ";
cin >> lin >> col;
lin = lin - 1; col = col - 1;
err = t1.devolver(lin, col);
if(err == 1){
c1.diminuirNum();
cout << endl << "Lugar Devolvido! ";
system("pause");
}else{
cout << endl << "Esse lugar no foi reservado ainda, portanto no pode ser devolvido! \a";
system("pause");
}
}
void titulo_teatro(Teatro& t1)
{
int tamanhoTitulo;
int numCol = t1.getCol();
if(numCol <= 3){tamanhoTitulo = 2;}
else{tamanhoTitulo = ((numCol*3)- 11)/2;}
//A frmula acima calcula quantos '=' tem que ter de cada lado do ttulo pra cobrir toda a matriz
//Printa um titulo de acordo com o tamanho da matriz apresentada na tela
cout << " " <<
setw(tamanhoTitulo) << setfill('=') << "" <<
setw(0) << "|Teatro Tal|" <<
setw(tamanhoTitulo) << setfill('=') << "" <<
setw(0) << setfill(' ') << endl;
}
| true |
638a3bd651c0e441e346ea0a24d8eee0ec852744 | C++ | Vishal-Maharathy/Hostel-Management-DTU | /student_checkin.h | UTF-8 | 4,752 | 2.90625 | 3 | [] | no_license | #include <stdlib.h>
#include <ctime>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
#include "checkin.h"
using namespace std;
void check_time() {
string branch;
int roll;
cout << "\033[1;33mPlease enter your Branch: \033[0m";
cin >> branch;
cout << "\033[1;33mPlease enter your Roll Number in the format->[123] : "
"\033[0m";
cin >> roll;
cal_time(branch, roll);
return;
}
void set_details() {
string name, branch, visitant_name;
int roll;
cout << "\033[1;33mPlease enter your First Name : "
"\033[0m";
cin >> name;
cout << "\033[1;33mPlease enter your Branch: : "
"\033[0m";
cin >> branch;
cout << "\033[1;33mPlease enter your Roll Number in the format->[123] "
":\033[0m";
cin >> roll;
if (search_dir(branch, roll)) {
visitant temp = r_visitant(branch, roll);
if (!temp.check_out) {
student s(name, branch, roll, temp.visitant);
return;
}
}
cout << "\033[1;33mPlease enter Name, Roll No, and Branch of the visitant "
"in the "
"format 'Name/Branch/RollNo': \033[0m";
cin >> visitant_name;
student s(name, branch, roll, visitant_name);
return;
}
void initialise() {
fstream fin;
fin.open("data.csv", ios::in);
if (fin.is_open()) {
return;
}
fin.open("data.csv", ios::app);
fin << "Visitor"
<< ","
<< "Branch"
<< ","
<< "Roll No."
<< ","
<< "Check In"
<< ","
<< "Check Out"
<< ","
<< "Visitant" << endl;
return;
}
void student_call() {
while (true) {
system("cls");
cout << "\033[1;32m=========.::WELCOME TO HOSTEL MANAGEMENT PROGRAM::.========\n\033[0m"<< endl;
cout << "\033[1;32m============.::DELHI TECHNOLOGICAL UNIVERSITY::.===========\n\033[0m"<< endl;
cout << "\033[1;32mCreated By: Vishal Maharathy\n\033[0m"<< endl;
int choice;
cout << "\033[1;33m\nPlease choose one option\033[0m" << endl;
cout << "\033[1;33m\n1. To Enter/Return from Hostel.\033[0m" << endl;
cout << "\033[1;33m\n2. To Check Time spent in hostel room by "
"visitor.\033[0m"
<< endl;
cout << "\033[1;33m\n3. To Check visitors still in Hostel.\033[0m"
<< endl;
cout << "\033[1;33m\n4. To Exit.\n\n\033[0m" << endl;
cout << "\033[1;33m--> \033[0m";
cin >> choice;
if (choice == 4) {
system("cls");
break;
}
if (choice == -1) {
break;
}
switch (choice) {
case 1:
while (true) {
system("cls");
set_details();
cout
<< "\033[1;35m\n\nEnter 1 To Return To Main Menu\033[0m"
<< endl;
cout << "\033[1;35mEnter 2 To Fill Another Entry\033[0m"
<< endl;
int temp;
cin >> temp;
if (temp == 2) {
continue;
}
if (temp == 1) {
break;
}
}
break;
case 2:
while (true) {
system("cls");
check_time();
cout
<< "\033[1;35m\n\nEnter 1 To Return To Main Menu\033[0m"
<< endl;
cout << "\033[1;35mEnter 2 To Check Another Entry\033[0m"
<< endl;
int temp;
cin >> temp;
if (temp == 2) {
continue;
}
if (temp == 1) {
break;
}
}
break;
case 3:
while (true) {
system("cls");
s_inHostel();
cout
<< "\033[1;35m\n\nEnter 1 To Return To Main Menu\033[0m"
<< endl;
cout << "\033[1;35mEnter 2 To Check Another Entry\033[0m"
<< endl;
int temp;
cin >> temp;
if (temp == 2) {
continue;
}
if (temp == 1) {
break;
}
}
default:
break;
}
}
} | true |
e1f31626ae2ed7d878a5fcf4cda1561e013c279a | C++ | liuzyon/group-project-ctzl | /ConwaysGame_Serial.cpp | UTF-8 | 3,135 | 2.8125 | 3 | [] | no_license | // #include <iostream>
// #include <sstream>
// #include <fstream>
// #include <cstdlib>
// #include <time.h>
// #include <vector>
// #include <chrono>
// using namespace std;
// //Note that this is a serial implementation with a periodic grid
// vector<vector<bool>> grid, new_grid;
// int imax, jmax;
// int max_steps;
// // how to calculate the numbers of neighbours.
// int num_neighbours(int ii, int jj)
// {
// int ix, jx;
// int cnt = 0;
// for (int i = -1; i <= 1; i++)
// for (int j = -1; j <= 1; j++)
// if (i != 0 || j != 0)
// {
// ix = (i + ii + imax) % imax;
// jx = (j + jj + jmax) % jmax;
// if (grid[ix][jx]) cnt++;
// }
// return cnt;
// }
// // write in the status of each cell.
// void grid_to_file(int it)
// {
// stringstream fname;
// fstream f1;
// fname << "output" << "_" << it << ".dat";
// f1.open(fname.str().c_str(), ios_base::out);
// for (int i = 0; i < imax; i++)
// {
// for (int j = 0; j < jmax; j++)
// f1 << grid[i][j] << "\t";
// f1 << endl;
// }
// f1.close();
// }
// // print ppm file for given timestep.
// void grid_to_ppm(int it, int mypit) {
// if (it % mypit != 0 && it != max_steps) {
// }
// else {
// stringstream fname;
// fstream f1;
// fname << "output_image" << "_" << it << ".ppm";
// f1.open(fname.str().c_str(), ios_base::out);
// f1 << "P3" << endl;
// f1 << imax << " " << jmax << endl;
// f1 << "255" << endl;
// int r = 0;
// int g = 0;
// int b = 0;
// for (int i = 0; i < imax; i++) {
// for (int j = 0; j < jmax; j++) {
// g = grid[i][j] * 255;
// f1 << r << " " << g << " " << b << " ";
// }
// f1 << endl;
// }
// f1.close();
// }
// }
// //status of the cell
// void do_iteration(void)
// {
// for (int i = 0; i < imax; i++)
// for (int j = 0; j < jmax; j++)
// {
// new_grid[i][j] = grid[i][j];
// int num_n = num_neighbours(i, j);
// if (grid[i][j])
// {
// if (num_n != 2 && num_n != 3)
// new_grid[i][j] = false;
// }
// else if (num_n == 3) new_grid[i][j] = true;
// }
// grid.swap(new_grid);
// }
// int main(int argc, char *argv[])
// {
// srand(time(NULL));
// imax = 1000;
// jmax = 1000;
// max_steps = 100;
// grid.resize(imax, vector<bool>(jmax));
// new_grid.resize(imax, vector<bool>(jmax));
// clock_t start_serial = clock();
// //set an initial random collection of points - You could set an initial pattern
// for (int i = 0; i < imax; i++)
// for (int j = 0; j < jmax; j++) grid[i][j] = (rand() % 2);
// // print initial status
// grid_to_ppm(0, 1);
// for (int n = 1; n <= max_steps; n++)
// {
// //cout << "it: " << n << endl;
// do_iteration();
// // grid_to_file(n);
// grid_to_ppm(n, int(max_steps / 2));
// }
// clock_t end_serial = clock();
// cerr << "Serial time of " << imax << " x " << jmax << " with " << max_steps << " generations(Seconds): " << (double)(end_serial - start_serial)/CLOCKS_PER_SEC << endl;
// return 0;
// }
// /*
// Team CTZL:
// Zhiyong Liu acse-zl1220
// Ran Tao acse-rt1120
// Yichao Zhou acse-yz220
// Submitted on Feb.17th, 2021
// */ | true |
1b30af208e159d0c1dc53061a87a6e134470f59d | C++ | dyninst/paradyn | /pdutil/h/tunableConst.h | UTF-8 | 4,897 | 2.78125 | 3 | [] | no_license | /*
* tunableConstant - a constant that might be changed during execution.
*
* $Log: tunableConst.h,v $
* Revision 1.10 1994/12/21 07:10:06 tamches
* Made the "allConstants" variable protected and added a few member
* functions to let outside code access it (safely) in a manner useful
* for doing iterations through all tunable-constants.
*
* Revision 1.9 1994/12/21 00:31:44 tamches
* Greatly cleaned up the interface; no data members are public any more.
* Also some minor changes, such as using g++'s built-in "bool" instead
* of "Boolean".
*
* Revision 1.8 1994/11/04 15:52:51 tamches
* setValue() for boolean tc's now correctly invokes its callback function, if any.
*
* Revision 1.7 1994/11/01 16:07:35 markc
* Added Object classes that provide os independent symbol tables.
* Added stl-like container classes with iterators.
*
* Revision 1.6 1994/10/26 22:32:50 tamches
* Defaulted min&max to 0 for floats with no min/max in constructor.
* Wrote min() and max() functions.
* Wrote use() function
* other minor changes to get to work with new tclTunable code
*
* Revision 1.5 1994/09/22 03:15:59 markc
* changed char* to const char *
*
* Revision 1.4 1994/08/05 16:01:55 hollings
* More consistant use of stringHandle vs. char *.
*
* Revision 1.3 1994/08/03 18:37:30 hollings
* split tunable constant into Boolean and Float sub-classes.
*
* Revision 1.2 1994/02/28 23:58:28 hollings
* Changed global list to be a pointer to a list because I couldn't rely on
* the order of global constructors.
*
* Revision 1.1 1994/02/25 00:25:58 hollings
* added tunable constants.
*
*
*/
#ifndef TUNABLE_CONST_H
#define TUNABLE_CONST_H
#include <assert.h>
#include "pdutil/h/stringPool.h"
//#include "pdutil/h/list.h"
typedef enum tunableUse { developerConstant, userConstant };
typedef enum tunableType { tunableBoolean, tunableFloat };
//
// Note: this is an abstract class, and can NOT be directly created.
//
class tunableConstant {
protected:
char *desc;
char *name;
tunableType typeName;
tunableUse use;
static stringPool *pool; // made protected
static List<tunableConstant*> *allConstants; // NEEDS TO BE MADE PROTECTED
public:
tunableConstant() {}
virtual ~tunableConstant() {}
const char *getDesc() const {
return desc;
}
const char *getName() const {
return name;
}
tunableUse getUse() const {
return use;
}
tunableType getType() const {
return typeName;
}
static tunableConstant *findTunableConstant(const char *name);
// returns NULL if not found
static List<tunableConstant *> beginIteration() {
assert(allConstants);
List <tunableConstant *> iterList = *allConstants;
// make a copy of the list for iteration purposes
// (actually, it just copies the head element, which itself
// is merely a pointer)
return iterList;
}
static int numTunables() {
assert(allConstants);
return allConstants->count();
}
virtual void print() = NULL;
};
// Shouldn't the string pools be made part of the base class?
typedef bool (*isValidFunc)(float newVal);
typedef void (*booleanChangeValCallBackFunc)(bool value);
typedef void (*floatChangeValCallBackFunc)(float value);
class tunableBooleanConstant : public tunableConstant {
private:
bool value;
booleanChangeValCallBackFunc newValueCallBack;
public:
tunableBooleanConstant(bool initialValue,
booleanChangeValCallBackFunc cb,
tunableUse type,
const char *name,
const char *desc);
bool getValue() { return value; }
bool setValue(bool newVal) {
value = newVal;
if (newValueCallBack)
newValueCallBack(newVal);
return true;
}
virtual void print();
};
class tunableFloatConstant : public tunableConstant {
private:
float value;
float min, max;
isValidFunc isValidValue;
floatChangeValCallBackFunc newValueCallBack;
bool simpleRangeCheck(float val);
public:
tunableFloatConstant(float initialValue,
float min,
float max,
floatChangeValCallBackFunc cb,
tunableUse type,
const char *name,
const char *desc);
tunableFloatConstant(float initialValue,
isValidFunc,
floatChangeValCallBackFunc cb,
tunableUse type,
const char *name,
const char *desc);
float getValue() { return value; }
bool setValue(float newVal) {
if (isValidValue && isValidValue(newVal)) {
value = newVal;
if (newValueCallBack)
newValueCallBack(newVal);
return true;
}
else if (simpleRangeCheck(newVal)) {
value = newVal;
if (newValueCallBack)
newValueCallBack(newVal);
return true;
}
else
return false;
}
float getMin() {return min;}
float getMax() {return max;}
virtual void print();
};
#endif
| true |
f7879d67df3c8a7d10421851db227ba1ce3bb1ce | C++ | Shahaf11111/Maze_BestFirstSearch_AStar | /vs2017test/cell/cell_group/CellGroup.cpp | UTF-8 | 1,246 | 3.28125 | 3 | [] | no_license | #include "CellGroup.h"
CellGroup::CellGroup(int source, int target, int gray, int black, int path) :
CellContainer::CellContainer(source, target, gray, black, path) {
}
bool CellGroup::doesBelongToTarget(int color) {
return color != this->sourceColor && color != this->targetColor && color != this->grayColor &&
color != this->blackColor && color != this->pathColor && color != WALL;
}
void CellGroup::clear() {
this->cells.clear();
}
void CellGroup::add(Cell* cell) {
this->cells.push_back(cell);
}
void CellGroup::add(int row, int col, Cell* parent) {
this->cells.push_back(new Cell(row, col, parent));
}
void CellGroup::addFirst(int row, int col, Cell* parent) {
this->cells.insert(this->cells.begin(), new Cell(row, col, parent));
}
void CellGroup::removeFirst() {
this->cells.erase(this->cells.begin()); // remove the front element
}
void CellGroup::removeLast() {
this->cells.pop_back(); // remove the front element
}
Cell* CellGroup::get(int index) {
return this->cells.at(index);
}
int CellGroup::size() {
return this->cells.size();
}
Cell* CellGroup::getFirst() {
return this->cells.front();
}
Cell* CellGroup::getLast()
{
return this->cells.back();
}
bool CellGroup::empty() {
return this->cells.empty();
} | true |
395bd9693454e08a1af4569216a3f0c4c6e6656b | C++ | Artanic30/CS171-ASSIGNMENTS | /cs171-assignment3-Artanic30/code/head/shape.hpp | UTF-8 | 420 | 2.78125 | 3 | [] | no_license | #pragma once
#include <utility>
#include "aabb.hpp"
#include "interaction.hpp"
class Shape
{
public:
AABB m_BoundingBox;
Eigen::Vector3f color;
Shape(Eigen::Vector3f color) : color(std::move(color)) {}
Shape(AABB aabb, Eigen::Vector3f color) : m_BoundingBox(std::move(aabb)), color(std::move(color)) {}
virtual ~Shape() = default;
virtual bool rayIntersection(Interaction& interaction, const Ray& ray) = 0;
};
| true |
a71e54a46e7040c93d5deb66359cccc2b10ac5d1 | C++ | lankokelly/qt---shooting-game | /bullet.cpp | UTF-8 | 1,702 | 2.578125 | 3 | [] | no_license | #include "bullet.h"
#include "mainwindow.h"
#include <QGraphicsPixmapItem>
#include <QDebug>
#include <typeinfo>
#include <QList>
#include <QFont>
int count=0;
void increment()
{
count=count+14;
}
void increment2()
{
count=count+88;
}
int enemyhp=100;
void minus2()
{
enemyhp=enemyhp-2;
}
void minus8(){
enemyhp=enemyhp-8;
}
bullet::bullet(){}
//balls
void bullet::fly()
{
QList<QGraphicsItem *> collide_items = collidingItems();
int i = 0;
int n = collide_items.size();
for ( i=0 ; i<n; ++i )
{
//if(collide_items[i]->pos().ry()==0)
if(typeid(*(collide_items[i]))==typeid(QGraphicsPixmapItem))
{
increment ();
emit scoreChanged(count);
minus2();
emit healthbarChange(enemyhp);
scene()->removeItem(this);
delete this;
return;
}
}
setPos(x(), y() - 2);
if(y() < 0)
{
this->scene()->removeItem(this);
delete this;
}
}
//minions
void bullet::fly2()
{
QList<QGraphicsItem *> collide_items = collidingItems();
int i = 0;
int n = collide_items.size();
for ( i=0 ; i<n; ++i )
{
//if(collide_items[i]->pos().ry()==0)
if(typeid(*(collide_items[i]))==typeid(QGraphicsPixmapItem))
{
increment2 ();
emit scoreChanged(count);
minus8();
emit healthbarChange(enemyhp);
scene()->removeItem(this);
delete this;
return;
}
}
setPos(x()+y()*y()/15000-x()/300, y() - x()*x()/30000);
if (y() < 0)
{
this->scene()->removeItem(this);
delete this;
}
}
| true |
12d6f0d7b4f922daff2b1f965866392a4d418f2e | C++ | fanfeng2015/Object-Oriented-Programming | /Demo/LinearDataStructures/cell.hpp | UTF-8 | 1,100 | 3.234375 | 3 | [] | no_license | // ------------------------------------------------------------------------
// A cell contains an Item* and a link. Cells are used to build lists.
// A. Fischer June 13, 2000 file: cell.hpp
// ------------------------------------------------------------------------
#pragma once
#include <iostream>
#include "item.hpp"
using namespace std;
// ------------------------------------------------------------------------
class Cell {
friend class Linear;
friend ostream& operator << ( ostream& out, Cell& c );
private:
Item* data;
Cell* next;
Cell( Item* e = nullptr, Cell* p = nullptr ) : data(e), next(p) {}
~Cell() { cout << "\n Deleting Cell " << this << dec << "..."; }
operator Item*() { return data; } // Cast Cell to Item*. ------------
void print(ostream& out) const { // --------------------------------
if (data) {
out << "Cell " << this;
out << " [" << *data << ", " << next << "]\n";
}
}
};
inline ostream& operator << ( ostream& out, Cell& c ) { c.print(out); return out; }
| true |
fc90324565e3d45359c5e0320b4ce7bf408694b3 | C++ | davidkazlauskas/templatious | /virtual/VirtualCollection.hpp | UTF-8 | 15,718 | 2.53125 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | //==================================================
// Copyright (c) 2015 Deividas Kazlauskas
//
// See the file license.txt for copying permission.
//==================================================
/*
* =====================================================================================
*
* Filename: VirtualCollection.hpp
*
* Description: Virtual collection to be passed around translation units.
*
* Version: 1.0
* Created: 08/19/2014 06:44:42 PM
* Compiler: gcc
*
* Author: David Kazlauskas (dk), david@templatious.org
*
* =====================================================================================
*/
#ifndef VIRTUALCOLLECTION_4I04BTF7
#define VIRTUALCOLLECTION_4I04BTF7
#include <templatious/CollectionAdapter.hpp>
#include <templatious/StaticAdapter.hpp>
#include <templatious/virtual/Iterator.hpp>
namespace templatious {
template <class T>
struct VCollectionBase {
typedef VIterator<T> Iter;
typedef VIterator<const T> CIter;
typedef VCollectionBase<T> ThisCol;
typedef T ValType;
virtual ~VCollectionBase() {}
virtual void add(const T& e) = 0;
virtual void add(T&& e) = 0;
virtual void insert(const Iter& i,const T& t) = 0;
virtual void insert(const Iter& i,T&& t) = 0;
virtual void erase(const Iter& i) = 0;
virtual void erase(const Iter& beg,const Iter& end) = 0;
virtual void clear() = 0;
virtual T& getByIndex(long idx) = 0;
virtual const T& cgetByIndex(long idx) const = 0;
virtual Iter begin() = 0;
virtual Iter end() = 0;
virtual CIter cbegin() const = 0;
virtual CIter cend() const = 0;
virtual Iter iterAt(long idx) = 0;
virtual CIter citerAt(long idx) const = 0;
virtual T& first() = 0;
virtual const T& cfirst() const = 0;
virtual T& last() = 0;
virtual const T& clast() const = 0;
virtual bool canAdd() const = 0;
virtual long size() const = 0;
virtual bool equals(ThisCol* c) const = 0;
protected:
template <class V>
static VIteratorBase<T>* getInternal(V&& v) {
return v._i;
}
};
template <
class T,
template <class> class StoragePolicy
>
struct VCollectionContainerRaw {
typedef typename StoragePolicy<T>::Container ContCol;
template <class A>
VCollectionContainerRaw(A&& col):
_cc(std::forward<A>(col))
{}
auto getColRef()
-> decltype(std::declval<ContCol>().getRef())
{
return _cc.getRef();
}
auto cgetColRef() const
-> decltype(std::declval<ContCol>().cgetRef())
{
return _cc.cgetRef();
}
auto constCpy() const
-> decltype(std::declval<ContCol>().constCpy())
{
return _cc.constCpy();
}
private:
ContCol _cc;
};
template <
class T,class Dtor,
template <class> class StoragePolicy
>
struct VCollectionContainerWDtor {
typedef typename StoragePolicy<T>::Container ContCol;
typedef typename StoragePolicy<Dtor>::Container ContDtor;
template <class A,class B>
VCollectionContainerWDtor(A&& col,B&& dtor):
_cc(std::forward<A>(col)),
_cd(std::forward<B>(dtor))
{}
~VCollectionContainerWDtor() {
// call the destructor
_cd.getRef()();
}
auto getColRef()
-> decltype(std::declval<ContCol>().getRef())
{
return _cc.getRef();
}
auto cgetColRef() const
-> decltype(std::declval<ContCol>().cgetRef())
{
return _cc.cgetRef();
}
auto constCpy() const
-> decltype(std::declval<ContCol>().constCpy())
{
return _cc.constCpy();
}
private:
ContCol _cc;
ContDtor _cd;
};
template <
class T,
class Dtor,
template <class> class StoragePolicy
>
struct VCollectionImpl:
public VCollectionBase< typename templatious::adapters::CollectionAdapter<T>::ValueType >
{
typedef templatious::adapters::CollectionAdapter<T> Ad;
typedef templatious::StaticAdapter SA;
typedef VCollectionBase< typename Ad::ValueType > Super;
static const bool hasDestructor =
!std::is_same< Dtor, void >::value;
typedef typename Ad::ValueType ValType;
typedef typename Ad::ConstValueType CValType;
typedef VCollectionImpl< T, Dtor, StoragePolicy > ThisCol;
typedef typename Super::Iter Iter;
typedef typename Super::CIter CIter;
typedef typename std::conditional<
!hasDestructor,
VCollectionContainerRaw< T, StoragePolicy >,
VCollectionContainerWDtor< T, Dtor, StoragePolicy >
>::type Cont;
typedef typename std::remove_reference<T>::type Deref;
typedef typename templatious::VIteratorImpl<
Deref > IterImpl;
typedef typename templatious::VIteratorImpl<
Deref > CIterImpl;
template <class V, class Enabled = void*>
VCollectionImpl(
V&& c,
typename std::enable_if<
!hasDestructor, Enabled
>::type dummy = nullptr
) : _ref(std::forward<V>(c)) {
static_assert(templatious::util::
DummyResolver<V,!hasDestructor>::val,
"This VCollection imlementation "
"must call the two argument constructor "
"with collection and functor.");
}
template <class V,class D, class Enabled = void* >
VCollectionImpl(
V&& c,D&& d,
typename std::enable_if<
hasDestructor, Enabled
>::type dummy = nullptr
) :
_ref(
std::forward<V>(c),
std::forward<D>(d)
)
{
static_assert(templatious::util::
DummyResolver<V,hasDestructor>::val,
"This VCollection imlementation "
"must call the one argument constructor "
"with collection only.");
}
virtual void add(const ValType& e) {
Ad::add(getColRef(),e);
}
virtual void add(ValType&& e) {
Ad::add(getColRef(),std::move(e));
}
virtual void insert(const Iter& i,const ValType& t) {
IterImpl* impl = static_cast<IterImpl*>(i.getBase());
Ad::insertAt(getColRef(),impl->internal(),t);
}
virtual void insert(const Iter& i,ValType&& t) {
IterImpl* impl = static_cast<IterImpl*>(i.getBase());
Ad::insertAt(getColRef(),impl->internal(),std::move(t));
}
virtual void erase(const Iter& i) {
IterImpl* impl = static_cast<IterImpl*>(i.getBase());
Ad::erase(getColRef(),impl->internal());
}
virtual void erase(const Iter& beg,const Iter& end) {
IterImpl* iBeg = static_cast<IterImpl*>(beg.getBase());
IterImpl* iEnd = static_cast<IterImpl*>(end.getBase());
Ad::erase(getColRef(),iBeg->internal(),iEnd->internal());
}
virtual void clear() {
Ad::clear(getColRef());
}
virtual ValType& getByIndex(long idx) {
return Ad::getByIndex(getColRef(),idx);
}
virtual CValType& cgetByIndex(long idx) const {
return Ad::getByIndex(cgetColRef(),idx);
}
virtual ValType& first() {
return Ad::first(getColRef());
}
virtual CValType& cfirst() const {
return Ad::first(cgetColRef());
}
virtual ValType& last() {
return Ad::last(getColRef());
}
virtual CValType& clast() const {
return Ad::last(cgetColRef());
}
virtual Iter begin() {
return SA::vbegin(getColRef());
}
virtual Iter end() {
return SA::vend(getColRef());
}
virtual CIter cbegin() const {
return SA::vcbegin(cgetColRef());
}
virtual CIter cend() const {
return SA::vcend(cgetColRef());
}
virtual Iter iterAt(long idx) {
return SA::viterAt(getColRef(),idx);
}
virtual CIter citerAt(long idx) const {
return SA::vciterAt(cgetColRef(),idx);
}
virtual bool canAdd() const {
return Ad::canAdd(cgetColRef());
}
virtual long size() const {
return Ad::size(cgetColRef());
}
virtual bool equals(Super* c) const {
if (nullptr == c) {
return false;
}
return comp(*c);
}
private:
auto getColRef()
-> decltype(std::declval<Cont>().getColRef())
{
return _ref.getColRef();
}
auto cgetColRef() const
-> decltype(std::declval<Cont>().cgetColRef())
{
return _ref.cgetColRef();
}
bool comp(Super& c) const {
if (typeid(c) == typeid(*this)) {
ThisCol& ref = static_cast<ThisCol&>(c);
return std::addressof(cgetColRef()) ==
std::addressof(ref.cgetColRef());
}
return false;
}
Cont _ref;
};
template <class T>
struct VCollection {
typedef VCollection<T> ThisCol;
typedef VCollectionBase<T> Base;
typedef typename Base::Iter Iter;
typedef typename Base::CIter CIter;
typedef T ValType;
typedef const ValType CValType;
VCollection(Base* b) : _b(b) {}
VCollection(ThisCol&& o) {
_b = o._b;
o._b = nullptr;
}
// handle cannot be copied, only moved
VCollection(const ThisCol& o) = delete;
ThisCol& operator=(const ThisCol& o) = delete;
ThisCol& operator=(ThisCol&& o) {
delete _b;
_b = o._b;
o._b = nullptr;
return *this;
}
virtual ~VCollection() { delete _b; }
void add(const T& e) {
_b->add(e);
}
void add(T&& e) {
_b->add(std::move(e));
}
void insert(const Iter& i,const T& t) {
_b->insert(i,t);
}
void insert(const Iter& i,T&& t) {
_b->insert(i,std::move(t));
}
void erase(const Iter& i) {
_b->erase(i);
}
void erase(const Iter& beg,const Iter& end) {
_b->erase(beg,end);
}
void clear() {
_b->clear();
}
T& getByIndex(long idx) {
return _b->getByIndex(idx);
}
const T& cgetByIndex(long idx) const {
return _b->cgetByIndex(idx);
}
ValType& first() {
return _b->first();
}
CValType& cfirst() const {
return _b->cfirst();
}
ValType& last() {
return _b->last();
}
CValType& clast() const {
return _b->clast();
}
Iter begin() {
return _b->begin();
}
Iter end() {
return _b->end();
}
CIter cbegin() const {
return _b->cbegin();
}
CIter cend() const {
return _b->cend();
}
Iter iterAt(long idx) {
return _b->iterAt(idx);
}
CIter citerAt(long idx) const {
return _b->citerAt(idx);
}
bool canAdd() const {
return _b->canAdd();
}
long size() const {
return _b->size();
}
bool operator==(const VCollection& vc) const {
if (_b == nullptr) return false;
return _b->equals(vc._b);
}
bool operator!=(const VCollection& vc) const {
return !(*this == vc);
}
private:
Base* _b;
};
namespace adapters {
template <class T>
struct CollectionAdapter< VCollection<T> > {
static const bool is_valid = true;
static const bool floating_iterator = true;
typedef VCollection<T> ThisCol;
typedef const ThisCol ConstCol;
typedef typename ThisCol::Iter Iterator;
typedef typename ThisCol::CIter ConstIterator;
typedef T ValueType;
typedef const T ConstValueType;
template <class V>
static void add(ThisCol& c, V&& i) {
c.add(std::forward<V>(i));
}
template <class V>
static void insertAt(ThisCol& c, const Iterator& at, V&& i) {
c.insert(at,std::forward<V>(i));
}
static ValueType& getByIndex(ThisCol& c, long i) {
return c.getByIndex(i);
}
static ConstValueType& getByIndex(ConstCol& c, long i) {
return c.cgetByIndex(i);
}
static long size(ConstCol& c) {
return c.size();
}
static void erase(ThisCol& c, const Iterator& i) {
c.erase(i);
}
static void erase(ThisCol& c, const Iterator& beg, const Iterator& end) {
c.erase(beg,end);
}
static Iterator begin(ThisCol& c) {
return c.begin();
}
static Iterator end(ThisCol& c) {
return c.end();
}
static Iterator iterAt(ThisCol& c, long i) {
return c.iterAt(i);
}
static ConstIterator begin(ConstCol& c) {
return c.cbegin();
}
static ConstIterator end(ConstCol& c) {
return c.cend();
}
static ConstIterator iterAt(ConstCol& c, long i) {
return c.citerAt(i);
}
static ConstIterator cbegin(ConstCol& c) {
return c.cbegin();
}
static ConstIterator cend(ConstCol& c) {
return c.cend();
}
static ConstIterator citerAt(ConstCol& c, long i) {
return c.citerAt(i);
}
static ValueType& first(ThisCol& c) {
return c.first();
}
static ConstValueType& first(ConstCol& c) {
return c.cfirst();
}
static ValueType& last(ThisCol& c) {
return c.last();
}
static ConstValueType& last(ConstCol& c) {
return c.clast();
}
static void clear(ThisCol& c) {
c.clear();
}
static bool canAdd(ConstCol& c) {
return c.canAdd();
}
};
template <class T>
struct CollectionAdapter< const VCollection<T> > {
static const bool is_valid = true;
static const bool floating_iterator = true;
typedef const VCollection<T> ThisCol;
typedef ThisCol ConstCol;
typedef typename ThisCol::CIter Iterator;
typedef Iterator ConstIterator;
typedef const T ValueType;
typedef ValueType ConstValueType;
template <class V,class U = void>
static void add(ThisCol& c, V&& i) {
static_assert(templatious::util::DummyResolver<U,false>::val,
"Const version of a collection doesn't support this method");
}
template <class V,class U = void>
static void insertAt(ThisCol& c, const Iterator& at, V&& i) {
static_assert(templatious::util::DummyResolver<U,false>::val,
"Const version of a collection doesn't support this method");
}
static ConstValueType& getByIndex(ConstCol& c, long i) {
return c.cgetByIndex(i);
}
static long size(ConstCol& c) {
return c.size();
}
template <class U = void>
static void erase(ThisCol& c, const Iterator& i) {
static_assert(templatious::util::DummyResolver<U,false>::val,
"Const version of a collection doesn't support this method");
}
template <class U = void>
static void erase(ThisCol& c, const Iterator& beg, const Iterator& end) {
static_assert(templatious::util::DummyResolver<U,false>::val,
"Const version of a collection doesn't support this method");
}
static Iterator begin(ConstCol& c) {
return c.cbegin();
}
static Iterator end(ConstCol& c) {
return c.cend();
}
static Iterator iterAt(ConstCol& c, long i) {
return c.citerAt(i);
}
static ConstIterator cbegin(ConstCol& c) {
return c.cbegin();
}
static ConstIterator cend(ConstCol& c) {
return c.cend();
}
static ConstIterator citerAt(ConstCol& c, long i) {
return c.citerAt(i);
}
static ConstValueType& first(ConstCol& c) {
return c.cfirst();
}
static ConstValueType& last(ConstCol& c) {
return c.clast();
}
template <class U = void>
static void clear(ThisCol& c) {
static_assert(templatious::util::DummyResolver<U,false>::val,
"Const version of a collection doesn't support this method");
}
static bool canAdd(ConstCol& c) {
return false;
}
};
}
}
#endif /* end of include guard: VIRTUALCOLLECTION_4I04BTF7 */
| true |
76177ae45d851216c2c0f82a82e1ac42092bea1c | C++ | fmarz96/algo1 | /labo06/ejercicios.cpp | UTF-8 | 2,590 | 3.609375 | 4 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
/********* Ejercicio 1 *********/
vector<vector<int>> mostrarMatriz(vector<vector<int>> m){
for(int i = 0; i < m.size(); i++){
for(int j = 0; j < m[i].size(); j++){
std::cout << m[i][j] << "\t";
}
std::cout << "\n";
}
}
/********* Ejercicio 2 *********/
// 2)a)
int prodEscalar(vector<int> v1, vector<int> v2){
int res = 0;
if(v1.size() == v2.size()){
int i = 0;
while(i < v1.size()){
res += v1[i]*v2[i];
i++;
}
}
return res;
}
// 2)b)
vector<vector<int>> prodTranspuesta(vector<vector<int>> mat){
vector<vector<int>> res(mat[0].size(), vector<int>(mat.size()));
for(int i = 0; i < mat.size(); i++){
for(int j = 0; j < mat[i].size(); j++){
res[i][j] = prodEscalar(mat[i], mat[j]);
}
}
return res;
}
/********* Ejercicio 3 *********/
vector<vector<int>> resizeMatriz(vector<vector<int>> mat, int f, int c){
vector<vector<int>> res;
vector<int> v;
int filasMat = mat.size();
int columnasMat = mat[0].size();
if(f*c == filasMat*columnasMat) {
for (int i = 0; i < mat.size(); i++) {
for (int j = 0; j < mat[i].size(); j++) {
v.push_back(mat[i][j]);
if (v.size() == c) {
if (res.size() < f) {
res.push_back(v);
}
while (v.size() > 0) {
v.pop_back();
}
}
}
}
}
return res;
}
vector<vector<int>> redimMatriz(vector<vector<int>> mat, int f, int c){
vector<vector<int>> res(f, vector<int>(c));
int filasMat = mat.size();
int columnasMat = mat[0].size();
if(f*c == filasMat*columnasMat) {
int k = 0, l = 0;
for (int i = 0; i < mat.size(); i++) {
for (int j = 0; j < mat[i].size(); j++) {
res[k][l] = mat[i][j];
l++;
if(l==c){
l = 0;
k++;
}
}
}
}
return res;
}
/********* Ejercicio 4 *********/
void trasponer(vector<vector<int>>& mat){
vector<vector<int>> transpuesta(mat[0].size(), vector<int>(mat.size()));
for(int i = 0; i < mat.size(); i++){
for(int j = 0; j < mat[i].size(); j++){
transpuesta[i][j] = mat[j][i];
}
}
mat = transpuesta;
}
int main() {
std::cout << "Hello, World!" << std::endl;
return 0;
} | true |
c54d5d12ccb2604cae1c903020043f4f76ba2c54 | C++ | shrutisonone/usual-coding | /stack/Trapping Rain Water .cpp | UTF-8 | 1,341 | 2.90625 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
int maxl[n];
maxl[0]=arr[0];
for(int i=1;i<n;i++)
{
maxl[i]=max(maxl[i-1], arr[i]);
}
int maxr[n];
maxr[n-1]=arr[n-1];
for(int i=n-2;i>=0;i--)
{
maxr[i]=max(maxr[i+1], arr[i]);
}
int water[n];
int ans=0;
for(int i=0;i<n;i++)
{
water[i]=(min(maxr[i], maxl[i]) - arr[i]);
ans+=water[i];
}
cout<<ans<<endl;
return 0;
}
/////////////////////////////////////////////////////////////////////
//uisng two pointers
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin>>n;
int a[n];
for(int i=0;i<n;i++)
{
cin>>a[i];
}
int left_max=0;
int right_max=0;
int l=0;
int r=n-1;
int res=0;
while(l<=r)
{
if(a[l]<a[r])
{
if(a[l]>left_max)
left_max=a[l];
else
res+=left_max-a[l];
l++;
}
else
{
if(a[r]>right_max)
right_max=a[r];
else
res+=right_max-a[r];
r--;
}
}
cout<<res<<endl;
return 0;
}
| true |
299db3fe75ce26752667e91357495ef19d1e3fa6 | C++ | nwkotto/bounded_queue | /boundedQueue.h | UTF-8 | 970 | 3.34375 | 3 | [] | no_license | #ifndef BOUNDEDQUEUE_H
#define BOUNDEDQUEUE_H
/*
Note: If you wanted to make this queue thread-safe, you would (for example)
need to implement an atomic test_and_set function and a clear function, to
manipulate some guard variable and make all public functions accessing the queue
(in this case, enqueue and dequeue) atomic. Not having access to a thread
library here, I have not made these member functions atomic. My apologies :( .
*/
class BoundedQueue{
int *theQueue;
int start, end;
unsigned int size;
bool full, empty;
public:
BoundedQueue(unsigned int length); //Constructor - sets queue size to length.
BoundedQueue(); //Default constructor - sets queue size to 3.
~BoundedQueue();
void enqueue(int value); //Enqueues "value". If full, throws an instance of QueueIsFull
int dequeue(); //Dequeues a value. If empty, throws an instance of QueueIsEmpty
};
//Exception classes
class QueueIsFull{};
class QueueIsEmpty{};
#endif | true |
0eb45255e5cc5a9737a6588580d00e13c29312b1 | C++ | FeibHwang/OJ-Leetcode | /Code/311_Sparse_Matrix_Multiplication.cpp | UTF-8 | 1,543 | 3.515625 | 4 | [] | no_license | /*
Given two sparse matrices A and B, return the result of AB.
You may assume that A's column number is equal to B's row number.
Example:
A = [
[ 1, 0, 0],
[-1, 0, 3]
]
B = [
[ 7, 0, 0 ],
[ 0, 0, 0 ],
[ 0, 0, 1 ]
]
| 1 0 0 | | 7 0 0 | | 7 0 0 |
AB = | -1 0 3 | x | 0 0 0 | = | -7 0 3 |
| 0 0 1 |
*/
/*
direct calculate by definition
there is a faster way in Introduction to Algorithm
*/
class Solution {
public:
vector<vector<int>> multiply(vector<vector<int>>& A, vector<vector<int>>& B) {
if(A[0].size()!=B.size() || A.empty() || A[0].empty() || B.empty() || B[0].empty()) return {};
vector<vector<int>> Btrans = transmatrix(B);
vector<vector<int>> res(A.size(),vector<int>(B[0].size(),0));
for(int i = 0; i < res.size(); ++i)
{
for(int j = 0; j < res[0].size(); ++j)
{
res[i][j] = vector_time(A[i],Btrans[j]);
}
}
return res;
}
vector<vector<int>> transmatrix(vector<vector<int>>& B)
{
vector<vector<int>> res;
for(int i = 0; i < B[0].size(); ++i)
{
vector<int> row;
for(int j = 0; j < B.size(); ++j)
{
row.push_back(B[j][i]);
}
res.push_back(row);
}
return res;
}
int vector_time(vector<int> &al, vector<int> &bl)
{
int res = 0;
for(int i = 0; i < al.size(); ++i) res += al[i]*bl[i];
return res;
}
};
| true |
d18193891a4f1c4c5f6ab5b4b581e5ca1fc3ce3b | C++ | vincent-weber/Generateur-Carreaux-De-Bezier | /mainwindow.cpp | UTF-8 | 5,325 | 2.84375 | 3 | [] | no_license | /* R. Raffin
* M1 Informatique, Aix-Marseille Université
* Fenêtre principale
* Au cas où, l'UI contient une barre de menu, une barre de status, une barre d'outils (cf QMainWindow).
* Une zone est laissée libre à droite du Widget OpenGL pour mettre de futurs contrôles ou informations.
*/
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "point.h"
#include "segment.h"
#include "discretisation.h"
#include "carreaubezier.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
connect(ui->slider_u, SIGNAL(valueChanged(int)), this, SLOT(onSliderU(int)));
connect(ui->slider_v, SIGNAL(valueChanged(int)), this, SLOT(onSliderV(int)));
connect(ui->slider_pt_ctrl_1, SIGNAL(valueChanged(int)), this, SLOT(onSliderPtsCtrl1(int)));
connect(ui->slider_pt_ctrl_2, SIGNAL(valueChanged(int)), this, SLOT(onSliderPtsCtrl2(int)));
connect(ui->slider_param_u, SIGNAL(valueChanged(int)), this, SLOT(onSliderParamU(int)));
connect(ui->slider_param_v, SIGNAL(valueChanged(int)), this, SLOT(onSliderParamV(int)));
}
MainWindow::~MainWindow()
{
delete ui;
}
inline QTextStream& qStdout()
{
static QTextStream r{stdout};
return r;
}
void debugAfficherPoints(vector<Point> points) {
for (int i = 0 ; i < points.size() ; ++i) {
qDebug() << "[ " << points[i].getX() << " " << points[i].getY() << " " << points[i].getZ() << " ]";
}
}
vector<Point> convertToUniArray(vector<vector<Point>> points) {
vector<Point> result;
for (int i = 0 ; i < points.size() ; ++i) {
for (int j = 0 ; j < points[0].size() ; ++j) {
result.push_back(points[i][j]);
}
}
return result;
}
/**
* @brief genererPointsControle Méthode pour générer des points de contrôle de manière
* aléatoire en faisant en sorte que le polygône de contrôle formé ne soit pas "emmêlé",
* pour que le carreau ne le soit pas non plus.
* @param n
* @param m
* @return
*/
vector<vector<Point>> genererPointsControle(int n, int m) {
srand (static_cast <unsigned> (time(0)));
float xOffset = static_cast <float> (rand()) /( static_cast <float> (RAND_MAX));
float yOffset = static_cast <float> (rand()) /( static_cast <float> (RAND_MAX));
float yPas = 0.2;
float xPas = 0.8;
vector<vector<Point>> result;
for (int i = 0 ; i < n ; ++i) {
vector<Point> ligne;
for (int j = 0 ; j < m ; ++j) {
float x = -2 + static_cast <float> (rand()) /( static_cast <float> (RAND_MAX/(4))) / 20 + xOffset;
float y = -2 + static_cast <float> (rand()) /( static_cast <float> (RAND_MAX/(4))) / 20 + yOffset;
float z = -1 + static_cast <float> (rand()) /( static_cast <float> (RAND_MAX/(2))) * 0.5;
Point p; p.setX(x); p.setY(y); p.setZ(z);
ligne.push_back(p);
yOffset += yPas;
}
result.push_back(ligne);
xOffset += xPas;
yOffset = 0;
}
return result;
}
/**
* @brief MainWindow::on_crea_points_clicked : génère les points de contrôle du
* carreau de Bézier en fonction des valeurs des sliders et appelle le code de rendu
* pour l'afficher.
*/
void MainWindow::on_crea_points_clicked()
{
Discretisation disc;
vector<vector<Point>> controlPoints;
controlPoints = genererPointsControle(slider_pt_ctrl_1_value, slider_pt_ctrl_2_value);
carreau = new CarreauBezier(controlPoints, slider_pt_ctrl_1_value, slider_pt_ctrl_2_value);
vector<Point> points_surface = disc.discretiser_carreau_bezier(*carreau,param_u_value,param_v_value);
ui->openGLWidget->setData(param_u_value, param_v_value, points_surface, controlPoints);
ui->openGLWidget->update();
}
/**
* @brief MainWindow::on_pts_ctrl_clicked action liée au bouton des points de contôle
* qui permet d'afficher ou pas les points de contrôle
*/
void MainWindow::on_pts_ctrl_clicked()
{
ui->openGLWidget->inverserRenduPointsControle();
ui->openGLWidget->update();
}
/**
* @brief MainWindow::onSliderU : les sliders ayant une range entre 0 et 100, leur valeur
* est divisée par 100 pour rentrer entre 0 et 1 pour l'évaluation.
* @param value
*/
void MainWindow::onSliderU(int value) {
slider_u_value = value;
if (carreau != nullptr) {
Point point = carreau->eval((float)slider_u_value / 100, (float)slider_v_value / 100);
ui->openGLWidget->setPointUV(point);
ui->openGLWidget->update();
}
}
void MainWindow::onSliderV(int value) {
slider_v_value = value;
if (carreau != nullptr) {
Point point = carreau->eval((float)slider_u_value / 100, (float)slider_v_value / 100);
ui->openGLWidget->setPointUV(point);
ui->openGLWidget->update();
}
}
void MainWindow::onSliderPtsCtrl1(int value) {
slider_pt_ctrl_1_value = value;
ui->label_pt_ctrl_1->setText(QString::number(value));
}
void MainWindow::onSliderPtsCtrl2(int value){
slider_pt_ctrl_2_value = value;
ui->label_pt_ctrl_2->setText(QString::number(value));
}
void MainWindow::onSliderParamU(int value){
param_u_value = value;
ui->label_param_u->setText(QString::number(value));
}
void MainWindow::onSliderParamV(int value){
param_v_value = value;
ui->label_param_v->setText(QString::number(value));
}
| true |
5dce2260cc4f86039df3d755ef2f22f4c907255b | C++ | weimingtom/eepp | /include/eepp/graphics/cscrollparallax.hpp | UTF-8 | 3,447 | 2.765625 | 3 | [
"MIT"
] | permissive | #ifndef EE_GRAPHICSCSCROLLPARALLAX_H
#define EE_GRAPHICSCSCROLLPARALLAX_H
#include <eepp/graphics/base.hpp>
#include <eepp/graphics/ctexture.hpp>
#include <eepp/graphics/csubtexture.hpp>
namespace EE { namespace Graphics {
/** @brief The scroll parallax renders a SubTexture to the screen from a position and a size specified. If the size is bigger than the SubTexture, the SubTexture is rendered as a repeated SubTexture until it covers all the size of the parallax, adding movement to more than one Scroll Parallax will generate the ilusion of depth.
** More info in wikipedia: http://en.wikipedia.org/wiki/Parallax_scrolling
*/
class EE_API cScrollParallax {
public:
cScrollParallax();
~cScrollParallax();
/** Constructor that create's the Scroll Parallax
* @param SubTexture The SubTexture to Draw
* @param Position The position of the parallax
* @param Size The size of the parallax
* @param Speed Speed of movement ( in Pixels Per Second )
* @param Color The Texture Color
* @param Blend The Blend Mode ( default ALPHA_NORMAL ) */
cScrollParallax( cSubTexture * SubTexture, const eeVector2f& Position = eeVector2f(), const eeSizef& Size = eeSizef(), const eeVector2f& Speed = eeVector2f(), const eeColorA& Color = eeColorA(), const EE_BLEND_MODE& Blend = ALPHA_NORMAL );
/** Create's the Scroll Parallax
* @param SubTexture The SubTexture to Draw
* @param Position The position of the parallax
* @param Size The size of the parallax
* @param Speed Speed of movement ( in Pixels Per Second )
* @param Color The Texture Color
* @param Blend The Blend Mode ( default ALPHA_NORMAL )
* @return True if success
*/
bool Create( cSubTexture * SubTexture, const eeVector2f& Position = eeVector2f(), const eeSizef& Size = eeSizef(), const eeVector2f& Speed = eeVector2f(), const eeColorA& Color = eeColorA(), const EE_BLEND_MODE& Blend = ALPHA_NORMAL );
/** Set the parallax texture color. */
void Color( const eeColorA& Color ) { mColor = Color; }
/** Get the parallax texture color. */
eeColorA Color() const { return mColor; }
/** Set the Blend Mode used. */
void BlendMode( const EE_BLEND_MODE& Blend ) { mBlend = Blend; }
/** @return The Blend Mode used for the parallax. */
const EE_BLEND_MODE& BlendMode() const { return mBlend; }
/** Draw the Scroll Parallax. */
void Draw();
/** Change the size of the current parallax
* @param size The new size */
void Size( const eeSizef& size );
/** @return Size */
const eeSizef& Size() const;
/** Change the Parallax position
* @param Pos The new parallax position */
void Position( const eeVector2f& Pos );
/** @return The parallax position */
const eeVector2f& Position() const;
/** @return The SubTexture used for the parallax.*/
cSubTexture * SubTexture() const;
/** Set Change the SubTexture used for the parallax. */
void SubTexture( cSubTexture * subTexture );
/** Set the parallax speed movement. */
void Speed( const eeVector2f& speed );
/** @return The parallax movement speed. */
const eeVector2f& Speed() const;
private:
cSubTexture * mSubTexture;
EE_BLEND_MODE mBlend;
eeColorA mColor;
eeVector2f mInitPos;
eeVector2f mPos;
eeVector2f mSpeed;
eeSizef mSize;
eeRecti mRect;
cClock mElapsed;
eeVector2i mTiles;
eeRectf mAABB;
eeSizef mRealSize;
void SetSubTexture();
void SetAABB();
};
}}
#endif
| true |
811121946d8d859d396e8ced2b4900ed9e5dd04e | C++ | victoreuceda/Lab7_Victor | /vector01/main.cpp | UTF-8 | 665 | 2.859375 | 3 | [] | no_license | #include "vector.h"
#include <iostream>
using std::cout;
using std::endl;
void wapa(Vector, char);
int main(int argc, char* argv[]){
cout << "Iniciando el main" << endl;
Vector a(3), b(3), c(2);
a.set(2.5,0);
a.set(-4,1);
a.set(0,2);
b.set(5,0);
b.set(2,1);
b.set(-1.1,2);
cout << a.toString() << endl << b.toString() << endl << c.toString() << endl;
wapa(a, 'a');
wapa(b, 'b');
wapa(c, 'c');
c.assign(a.suma(b));
Vector d(a);
cout << a.toString() << endl << b.toString() << endl << c.toString() << endl;
return 0;
}
void wapa(Vector v, char var){
cout << "Entrando a wapa con variable: " << var << endl;
cout << v.toString() << endl;
}
| true |
d8aff6befedb4f166efc218cdccfdf081f2bb8ef | C++ | nikisonowal4899/codes | /structures/demo1.cpp | UTF-8 | 315 | 3.65625 | 4 | [] | no_license | #include <iostream>
using namespace std;
//Defining a structure
struct student {
int rollNo;
char sex;
};
int main()
{
struct student Niki; //Declaring a variable
Niki.rollNo = 170108026;
Niki.sex = 'M';
cout << "Roll Number: " << Niki.rollNo << endl;
cout << "Sex: " << Niki.sex << endl;
return 0;
} | true |
c4965788e7d1e0eb408f3792e15d882aa9bdb86e | C++ | rahilmalhotra001/Competitve-programming | /C++ data structures.cpp | UTF-8 | 10,883 | 3.046875 | 3 | [] | no_license | Struct in c++ -
struct B
{
int x,y;
B() {}
B (int x, int y) : x(x), y(y){}
bool operator<(const B &num) const
{
if(x==num.x)
return y<num.y;
return x<num.x;
}
};
set- (distinct elements, sorted)
set <int> s;
s.insert(k);
s.erase(k);
auto it=s.lower_bound(k); (lowerbound :>=k ; upperbound: >k)
if(it!=s.end())
cout<<*it (is the value)
for(auto &it:s);
auto it=s.find(k); (if found then it contains k, else it reaches s.end())
multiset -(multiple elements, sorted)
multiset <int> s;
s.insert(k);
if(s.find(k)!=s.end())
s.erase(k);//erases all k values
if(s.find(k)!=s.end())
s.erase(s.find(k)); //removes one occurence of k
auto it=s.lower_bound(k); (lowerbound :>=k ; upperbound: >k)
if(it!=s.end())
cout<<*it (is the value)
for(auto &it:s);
cout<<it;
auto it=s.find(k); (if found then it contains k, else it reaches s.end())
map -(<key,value>, sorted by key)
map <int,int> hm;
hm[key]=val;
if(hm.find(key)!=hm.end())
cout<<hm[key];
//DONT USE
if(!hm[key]) // this will insert a key key with default value(here 0)
auto it=hm.lower_bound(key);
cout<<it->first // will give key
cout<<it->second //will give value
for(auto &it:hm);
it.first, it.second;
if(hm.find(key)!=hm.end())
hm.erase(key);
priority_queue(sorted by comparator , log n insertions/deletions ; cant find)
priority_queue<type,vector<type>,pqsort> pq;//default is decreasing order
priority_queue<type,vector<type>,greater<type>> pq;//inc sorted
pq.push(type);
element = pq.top();
pq.pop();
unordered_set ; unordered_map;
vector(dynamic array)
vector<int> v;
v.push_back(value);
v.back(); or v[v.size()-1];//for lastelement
sort(v.begin(),v.end(),comparator);
sort(v.begin()+l,v.begin()+r,comparator); //l to r-1
auto it=lower_bound(v.begin(),v.end(),value);
int index=it-v.begin();
vector<int> g[1000];
g[a].push_back(b);
for(auto &it:g[pos])
dfs(it);
stack -
stack<int> st;
st.push(a);
st.pop(); //does not return anything
st.top();
-
queue<int> q;
q.push(a);
q.pop(); //does not return anything
q.front();
deque -
deque<int> q;
q.push_front(a);
q.push_back(a);
q.pop_front();
q.pop_back();
q.front();
q.back();
//return only 0 or 1
bool comparator(int &num1,int &num2)
{
// ascending order
if(num1<num2)
return 1;
return 0;
}
pair-
pair<int ,int> p;
p.first=a;
p.second=b;
or
p={a,b};
class pqsort
{
public: bool operator() (pair<int,int> &a,pair<int,int> &b)
{
if(a.second-a.first<b.second-b.first)
return 0;
return 1;
}
};
----------------------------------------------
sort(arr,arr+arr.size(),comparator);
bool comparator(int &num1,int &num2)
{
// descending order
if(num1>num2)
return 1;
return 0;
}
reverse(arr,arr+size());
random_shuffle(arr,arr+size());
do
{
}
while(next_permutation(arr,arr+size()));
string s;
sort(s.begin(),s.end());
reverse(s.begin(),s.end());
//s = hello
string temp=s.substr(2,2); //ll
//for files
freopen("input file name","r",stdin);
freopen("out file name","w",stdout);
------
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
#define endl '\n'
---------
isalpha(ch); //if ch is alphabet
isdigit(ch);
isalnum(ch);
http://www.cplusplus.com/reference/cctype/isdigit/
getline(cin,str); //line input
getline(ss, num, ',');// delimiter ,
stringstream ss(str); //string tokenizer
string word;
while(ss>>word)
cout<<word;
stoi(a);//String to int
stoll(b);//String to long long
string a=to_string(num)//num to string
__builtin_popcount(a);
__gcd(a,b);
lcm(a,b);
Debug -
template <typename T> void debug(T t) { cout<<t<<endl; }
template<typename T, typename... Args> void debug(T t, Args... args) { cout<<t<<" "; debug(args...); }
-----------------------------------------TRIES----------------------------------------------
typedef struct data
{
data* bit[2];
int cnt=0;
}trie;
trie* head;
void insert(int x)
{
trie* node = head;
for(int i=30;i>=0;i--)
{
int curbit=(x>>i)&1;
if(node->bit[curbit]==NULL)
{
node->bit[curbit]=new trie();
}
node=node->bit[curbit];
node->cnt++;
}
}
void remove(int x)
{
trie* node = head;
for(int i=30;i>=0;i--)
{
int curbit=(x>>i)&1;
node=node->bit[curbit];
node->cnt--;
}
}
int maxxor(int x)
{
trie* node = head;
int ans=0;
for(int i=30;i>=0;i--)
{
int curbit=(x>>i)&1;
if(node->bit[curbit^1]!=NULL && node->bit[curbit^1]->cnt>0)
{
ans+=(1LL<<i);
node=node->bit[curbit^1];
}
else
node=node->bit[curbit];
}
return ans;
}
int main()
{
head=new trie();
insert(0);
}
-----------------------------------------------------------------------------------------------------------------
for map optimizations-
m.reserve(2^15)
m.max_load_factor(0.25)
...............................................................
Never use __builtin_popcount
Always use __builtin_popcountll
...............................................................
BIT----
int tree[300005];
int sum(int i)
{
int sum = 0;
while(i>0)
{
sum+=tree[i];
i-=i&(-i);
}
return sum;
}
void update(int i, int val)
{
while(i<300005)
{
tree[i]+=val;
i+=i&(-i);
}
}
................................................................
int mod=1000000007;
int inv(int x)
{
int r,y;
for(r=1,y=mod-2;y>0;x=(x*x)%mod,y/=2)
if(y%2==1)
r=r*x%mod;
return r;
}
int nCr(int n, int m)
{
return fact[n] *inv(fact[m])%mod *inv(fact[n-m])%mod ;
}
................................................................
int power(int x,int y,int p)
{
int res = 1;
x = x % p;
while (y > 0)
{
if((y & 1)==1)
res = (res * x) % p;
y = y >> 1;
x = (x * x) % p;
}
return res;
}
................................................................
DSU
int n;
int rt[200005],sizee[200005];
void initialize()
{
for(int i=0;i<n;i++)
{
rt[i]=i;
sizee[i]=1;
}
}
int root(int i)
{
while(rt[i]!= i)
{
rt[i]=rt[rt[i]];
i=rt[i];
}
return i;
}
void merge(int A,int B)
{
int root_A = root(A);
int root_B = root(B);
if(rt[root_A]==rt[root_B])
return;
if(sizee[root_A] < sizee[root_B])
{
rt[root_A] = rt[root_B];
sizee[root_B] += sizee[root_A];
}
else
{
rt[root_B] = rt[root_A];
sizee[root_A] += sizee[root_B];
}
}
...............................................
Sparse Table
int tablemin[(int)log2(150005)+2][150005];
int floorlog[150005];
int maxi(int start,int end)
{
int p=floorlog[end-start+1];
return max(tablemin[p][start],tablemin[p][end-(1<<p)+1]);
}
for(int i=0;(1<<i)<150005;i++)
{
for(int j=(1<<i);j<150005 && j<(1<<(i+1)); j++)
floorlog[j]=i;
}
for(int i=1;i<=n;i++)
tablemin[0][i]=arr[i];
for (int j=1;(1<<j)<=n;j++)
for (int i=1;(i+(1<<j)-1)<=n;i++)
tablemin[j][i]=max(tablemin[j-1][i],tablemin[j-1][i+(1<<(j - 1))]);
...............................................
Segment tree
int tree[1000005];
int lazy[1000005];
void propogate(int i,int l,int r)
{
tree[i]+=(r-l+1)*lazy[i];
if(l!=r)
lazy[i*2]+=lazy[i],lazy[i*2+1]+=lazy[i];
lazy[i]=0;
}
void build(int i,int l,int r)
{
if(l==r)
{
tree[i]=arr[l];
return;
}
int mid=(l+r)/2;
build(i*2,l,mid);
build(i*2+1,mid+1,r);
tree[i]=tree[i*2]+tree[i*2+1];
}
void update(int i,int l,int r,int l1,int r1,int val)
{
if(lazy[i])
propogate(i,l,r);
if(l1>r1 || l>r1 || l1>r)
return;
if(l1<=l && r<=r1)
{
tree[i]+=(r-l+1)*val;
if(l!=r)
lazy[i*2]+=val,lazy[i*2+1]+=val;
return;
}
int mid=(l+r)/2;
update(i*2,l,mid,l1,r1,val);
update(i*2+1,mid+1,r,l1,r1,val);
tree[i]=tree[i*2]+tree[i*2+1];
}
int query(int i,int l,int r,int l1,int r1)
{
if(l1>r1 || l>r1 || l1>r)
return 0;
if(lazy[i])
propogate(i,l,r);
if(l1<=l && r<=r1)
return tree[i];
int mid=(l+r)/2;
return query(i*2,l,mid,l1,r1)+query(i*2+1,mid+1,r,l1,r1);
}
......................................................................
bool isVowel(char ch)
{
if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' ||ch=='y'|| ch=='A'|| ch=='E'|| ch=='I'|| ch=='O'|| ch=='U'||ch=='Y')
return true;
else
return false;
}
.......................................................................
rand
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
int rand(int l, int r)
{
uniform_int_distribution<int> uid(l, r);
return uid(rng);
}
.......................................................................
LCA
int lvl[1000005],par[22][1000005];
bool vis[1000005];
int tim[2][1000005];
int ct=0;
int dfs(int i,int p,int l)
{
par[0][i]=p;
lvl[i]=l;
tim[0][i]=++ct;
for(auto j:v[i])
if(j!=p)
dfs(j,i,l+1);
tim[1][i]=ct;
}
void compute()
{
for(int i=1;i<22;i++)
for(int j=1;j<=n;j++)
if(par[i-1][j])
par[i][j]=par[i-1][par[i-1][j]];
}
int LCA(int a,int b)
{
if(lvl[a]<lvl[b])
swap(a,b);
int diff=lvl[a]-lvl[b];
for(int i=21;i>=0;i--)
if((1<<i)&diff)
a=par[i][a];
if(a==b)
return a;
for(int i=21;i>=0;i--)
if(par[i][a] && par[i][a]!=par[i][b])
a=par[i][a],b=par[i][b];
return par[0][a];
}
int path(int a,int h)
{
for(int i=21;i>=0;i--)if((1<<i)&h)a=par[i][a];
return a;
}
..........................................................................
FFT template - https://www.codechef.com/viewsolution/19136345
..........................................................................
Centroid Decomposition -
set<int>v[1000005];
int subtree[1000005],partree[1000005];
int dfsSubtree(int i,int p)
{
int sum=0;
for(auto j:v[i])
if(j!=p)
sum+=dfsSubtree(j,i);
sum++;
subtree[i]=sum;
return sum;
}
int centroid(int i,int p,int sz)
{
for(auto j:v[i])
if(j!=p && subtree[j]>sz/2)
return centroid(j,i,sz);
return i;
}
void decompose(int i,int p)
{
dfsSubtree(i,p);
int cent = centroid(i,p,subtree[i]);
partree[cent]=p;
for(auto j:v[cent])
{
v[j].erase(cent);
decompose(j,cent);
}
}
https://codeforces.com/contest/342/problem/E
.......................................................................
| true |
beec08bf692a2aa23a66a11ac9989ba8717e440f | C++ | xiaohuanlin/nand2tetris | /projects/07/vmtranslator/test/code_writer/code_writer_test.cpp | UTF-8 | 1,722 | 2.5625 | 3 | [
"MIT"
] | permissive |
#include <string>
#include "gtest/gtest.h"
#include "code_writer.hpp"
namespace vmtranslator
{
TEST(CodeWriterTest, OstreamToFile) {
std::stringbuf sb("");
std::ostream output(&sb);
CodeWriter code_writer(&output);
code_writer.WritePushpop(COMMAND::C_PUSH, "constant", 1);
std::string file_name = "./test.txt";
code_writer.SetFileName(file_name);
code_writer.Close();
std::ifstream file(file_name);
EXPECT_TRUE(file.is_open());
std::streambuf *buf = file.rdbuf();
std::streamsize size = buf->pubseekoff(0, file.end);
buf->pubseekoff(0, file.beg);
char* contents = new char [size + 1];
contents[size] = '\0';
buf->sgetn(contents, size);
ASSERT_STREQ("@1\nD=A\n@0\nA=M\nM=D\n@0\nM=M+1\n", contents);
file.close();
unlink(file_name.c_str());
}
TEST(CodeWriterTest, WriteArithmeticCommand) {
std::stringbuf sb("");
std::ostream output(&sb);
CodeWriter code_writer(&output);
code_writer.WriteArithmetic("add");
std::string file_name = "./test.txt";
code_writer.SetFileName(file_name);
code_writer.Close();
std::ifstream file(file_name);
EXPECT_TRUE(file.is_open());
std::streambuf *buf = file.rdbuf();
std::streamsize size = buf->pubseekoff(0, file.end);
buf->pubseekoff(0, file.beg);
char* contents = new char [size + 1];
contents[size] = '\0';
buf->sgetn(contents, size);
ASSERT_STREQ("@0\nA=M-1\nD=M\n@0\nM=M-1\nA=M-1\nM=M+D\n", contents);
file.close();
unlink(file_name.c_str());
}
} // namespace compiler
| true |
a19451320c5e9fe97edb5a8f379597455adf33b1 | C++ | Aaditya-Singh78/Competitive-Programming-June-Course- | /Keshav Mishra/Array and Strings/Max No of vowels in a substring of given length.cpp | UTF-8 | 427 | 2.625 | 3 | [] | no_license | class Solution {
public:
int maxVowels(string s, int k) {
int i=0,j=0,mx=0,cnt=0;
while(j < s.length())
{
if(s[j]=='a' || s[j] == 'e' || s[j] == 'i' || s[j] == 'o' || s[j] == 'u')
cnt++;
if(j-i+1<k)
j++;
else if(j-i+1 == k)
{
mx = max(mx,cnt);
if(s[i]=='a' || s[i] == 'e' || s[i] == 'i' || s[i] == 'o' || s[i] =='u')
cnt--;
i++;j++;
}
}
return mx;
}
}; | true |
ca82b868472dd910055791beb9402ac87fa0ad2f | C++ | lhalam/firstProject1415 | /firstProject1415/main.cpp | UTF-8 | 1,031 | 2.90625 | 3 | [] | no_license | #define DLL_IMPORT
#include <iostream>
#include "UI/UI.h"
using std::cout;
using std::cerr;
using std::cin;
using std::endl;
int main()
{
cout << "Welcome to our shop!" << endl;
cout << "Type 'help' for list of available commands" << endl;
cout << "________________________________________________________________________________" << endl;
while (true)
{
cout << Message("Execute", CONTEXT_MSG);
string userCommand;
getline(cin, userCommand, '\n');
toLowercase(userCommand);
if (userCommand == "exit")
{
break;
}
bool foundCommand = false;
for (int i = 0; i < numOfCommands; i++)
{
if (commands[i].getName() == userCommand)
{
foundCommand = true;
Result executionResult = commands[i].execute();
if (executionResult.getId() != SUCCESSFUL)
{
cerr << executionResult << endl;
}
}
}
if (foundCommand == false)
{
cout << Message("Unknown command, please try again. You can type 'help' to see the list of available commands.", ALERT_MSG);
}
}
return 0;
}
| true |
beead408abbc03a21d36f05fd303c2b59beff4c2 | C++ | idumenskyi/learn_cpp | /variables.cpp | UTF-8 | 521 | 3.171875 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
//int a;
//a = 5;
//int name var; wrong declaration variable, using whitespase in name of variable
//int a = 7;
//cout << a << endl;
//a = 108;
//cout << a << endl;
int Age, a, b; // int Age = 26, a = 2, b = 5;
double e = 2.72;
char s = 'f';
bool tr = true, fl = false;
Age = 26;
a = 2;
b = 5;
cout << Age << " " << a << " " << b << " " << e << " " << s << " " << tr << " " << fl << endl;
return 0;
}
| true |
145f0e70747b6a910668f88290fcc8428b3a638b | C++ | edodo1337/BoxPacking3 | /abstract_box.cpp | UTF-8 | 3,349 | 2.71875 | 3 | [] | no_license | #include <iostream>
#include <array>
#include <vector>
#include "abstract_box.h"
#include "utils.h"
#include <iterator>
#include <algorithm>
// #include <boost/lambda/lambda.hpp>
// #include <boost/numeric/ublas/vector.hpp>
// #include <boost/numeric/ublas/matrix.hpp>
// #include <boost/numeric/ublas/io.hpp>
// #include <boost/numeric/ublas/assignment.hpp>
#include <time.h>
// using namespace boost::numeric::ublas;
int AbstractBox::boxes_count = 0;
std::array<int,3> AbstractBox::get_position()
{
return this->position;
}
std::array<int,3> AbstractBox::get_diag()
{
return this->diag;
}
std::array<int,3> AbstractBox::get_size()
{
return this->size;
}
int AbstractBox::get_id()
{
return this->id;
}
void AbstractBox::set_position(std::array<int,3> &position)
{
this->position = position;
}
void AbstractBox::set_diag(std::array<int,3> &diag)
{
this->diag = diag;
}
void AbstractBox::set_size(std::array<int,3> &size)
{
this->size = size;
}
void AbstractBox::putOnPos(std::array<int,3> &pos)
{
this->set_position(pos);
}
AbstractBox::AbstractBox(std::array<int,3> &size, std::array<bool,3> &is_rotatableXYZ)
{
this->size = size;
this->diag = {0,0,0};
this->is_rotatableX = is_rotatableXYZ.at(0);
this->is_rotatableY = is_rotatableXYZ.at(1);
this->is_rotatableZ = is_rotatableXYZ.at(2);
this->rotation_sate = 0;
this->id = ++this->boxes_count;
}
void AbstractBox::rotateX()
{
auto d = this->get_diag();
std::array<int,3> diag = prod(Rx, d);
this->diag = diag;
auto s = this->size;
this->size = {s[0], s[2], s[1]};
}
void AbstractBox::rotateY()
{
auto d = this->get_diag();
std::array<int,3> diag = prod(Ry, d);
this->diag = diag;
auto s = this->size;
this->size = {s[2], s[1], s[0]};
}
void AbstractBox::rotateZ()
{
auto d = this->get_diag();
std::array<int,3> diag = prod(Rz, d);
this->diag = diag;
auto s = this->size;
this->size = {s[1], s[0], s[2]};
}
void AbstractBox::rotateXi()
{
auto d = this->get_diag();
std::array<int,3> diag = prod(Qx, d);
this->diag = diag;
auto s = this->size;
this->size = {s[0], s[2], s[1]};
}
void AbstractBox::rotateYi()
{
auto d = this->get_diag();
std::array<int,3> diag = prod(Qy, d);
this->diag = diag;
auto s = this->size;
this->size = {s[2], s[1], s[0]};
}
void AbstractBox::rotateZi()
{
auto d = this->get_diag();
std::array<int,3> diag = prod(Qz, d);
this->diag = diag;
auto s = this->size;
this->size = {s[1], s[0], s[2]};
}
AbstractBox::AbstractBox()
{
this->id = ++this->boxes_count;
}
// int main()
// {
// std::array<int,3> diag{1,2,3};
// std::array<bool,3> is_rotatableXYZ{true, true, true};
// std::array<int,3> pos{5,5,5};
// auto box = AbstractBox(diag, is_rotatableXYZ);
// box.rotateY();
// box.set_position(pos);
// for (auto i:box.get_diag())
// std::cout<<i<< " ";
// return 0;
// } | true |
31718ca40cb3503878f6eb4e1056fe694f850b2a | C++ | WalkervilleElementary/robot | /src/hardware/encoder.cpp | UTF-8 | 1,684 | 2.703125 | 3 | [] | no_license | #include "hardware/encoder.h"
#include "utils/encoderinterrupts.h"
#include "math.h"
namespace hardware {
float Encoder::distance_to_ticks = GEAR_RATIO() * ENCODER_TICKS_PER_REVOLUTION() / (WHEEL_DIAMETER() * M_PI);
float Encoder::degrees_to_ticks = AXLE_LENGTH() * M_PI / 180.0;
int32_t Encoder::cmToTicks(float cm) {
return cm * distance_to_ticks;
}
int32_t Encoder::degToTicks(float deg) {
return cmToTicks(deg * degrees_to_ticks);
}
Encoder::Encoder(uint8_t encoderId, bool reverse) {
m_encoderId = encoderId;
m_reverse = reverse;
setEncoderCount(m_encoderId, 0);
m_previousPosition = getPositionPrivate();
m_currentPosition = getPositionPrivate();
for (int i = 0; i < m_numVelocitySamples; i++) {
m_velocitySamples[i] = 0;
}
}
int32_t Encoder::getPosition() const {
return m_currentPosition;
}
int16_t Encoder::getVelocity() const {
int16_t velocity = 0;
for (int i = 0; i < m_numVelocitySamples; i++) velocity += m_velocitySamples[i];
return velocity;
}
void Encoder::tick() {
m_previousPosition = m_currentPosition;
m_currentPosition = getPositionPrivate();
m_velocitySamples[m_currentVelocitySample++] = m_currentPosition - m_previousPosition;
if (m_currentVelocitySample >= m_numVelocitySamples) m_currentVelocitySample = 0;
}
#if DEBUG()
void Encoder::printTo(Print& p) {
p.print(getEncoderPin(m_encoderId, 0));
p.print(getEncoderPin(m_encoderId, 1));
p.print(' ');
p.print(getPosition());
p.print(' ');
p.print(getVelocity());
}
#endif // DEBUG
int32_t Encoder::getPositionPrivate() {
if (m_reverse) return -getEncoderCount(m_encoderId);
else return getEncoderCount(m_encoderId);
}
} // namespace hardawre
| true |
d9eba7ddb5f5630245ca237403c95913a03bfe3c | C++ | BarryChenZ/LeetCode2 | /P232_Implement_Queue_usingStacks.cpp | UTF-8 | 702 | 3.75 | 4 | [] | no_license | class MyQueue {
public:
/** Initialize your data structure here. */
vector<int> stack;
MyQueue() {
stack.clear();
}
/** Push element x to the back of queue. */
void push(int x) {
stack.push_back(x);
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
int tmp = stack.front();
stack.erase(stack.begin());
return tmp;
}
/** Get the front element. */
int peek() {
int tmp = stack.front();
return tmp;
}
/** Returns whether the queue is empty. */
bool empty() {
if(stack.empty()) return true;
return false;
}
};
| true |
072e020ec98ede67cceee453537afb3281b1bcbf | C++ | giuinktse7/vulkan-learning | /vulkan-tutorial/map_io.cpp | UTF-8 | 8,449 | 2.6875 | 3 | [] | no_license | #include "map_io.h"
#include <iostream>
#include "debug.h"
#include "version.h"
#include "definitions.h"
#include "tile.h"
#include <string>
enum NodeType
{
NODE_START = 0xFE,
NODE_END = 0xFF,
ESCAPE_CHAR = 0xFD,
};
constexpr uint32_t DEFAULT_BUFFER_SIZE = 0xFFFF;
SaveBuffer::SaveBuffer(std::ofstream &stream)
: maxBufferSize(DEFAULT_BUFFER_SIZE), stream(stream)
{
buffer.reserve(DEFAULT_BUFFER_SIZE);
}
void SaveBuffer::writeBytes(const uint8_t *cursor, size_t amount)
{
while (amount > 0)
{
if (*cursor == NODE_START || *cursor == NODE_END || *cursor == ESCAPE_CHAR)
{
if (buffer.size() + 1 >= maxBufferSize)
{
flushToFile();
}
buffer.emplace_back(ESCAPE_CHAR);
std::cout << std::hex << static_cast<int>(buffer.back()) << std::endl;
}
if (buffer.size() + 1 >= maxBufferSize)
{
flushToFile();
}
buffer.emplace_back(*cursor);
std::cout << std::hex << static_cast<int>(buffer.back()) << std::endl;
++cursor;
--amount;
}
}
void SaveBuffer::startNode(OTBM_NodeTypes_t nodeType)
{
if (buffer.size() + 2 >= maxBufferSize)
{
flushToFile();
}
buffer.emplace_back(NODE_START);
std::cout << std::hex << static_cast<int>(NODE_START) << std::endl;
buffer.emplace_back(nodeType);
std::cout << std::hex << static_cast<int>(nodeType) << std::endl;
}
void SaveBuffer::endNode()
{
if (buffer.size() + 1 >= maxBufferSize)
{
flushToFile();
}
buffer.emplace_back(NODE_END);
std::cout << std::hex << static_cast<int>(NODE_END) << std::endl;
}
void SaveBuffer::writeU8(uint8_t value)
{
writeBytes(&value, 1);
}
void SaveBuffer::writeU16(uint16_t value)
{
writeBytes(reinterpret_cast<uint8_t *>(&value), 2);
}
void SaveBuffer::writeU32(uint32_t value)
{
writeBytes(reinterpret_cast<uint8_t *>(&value), 4);
}
void SaveBuffer::writeU64(uint64_t value)
{
writeBytes(reinterpret_cast<uint8_t *>(&value), 8);
}
void SaveBuffer::writeString(const std::string &s)
{
if (s.size() > UINT16_MAX)
{
ABORT_PROGRAM("OTBM does not support strings larger than 65535 bytes.");
}
writeU16(s.size());
writeBytes(reinterpret_cast<uint8_t *>(const_cast<char *>(s.data())), s.size());
}
void SaveBuffer::writeRawString(const std::string &s)
{
writeBytes(reinterpret_cast<uint8_t *>(const_cast<char *>(s.data())), s.size());
}
void SaveBuffer::writeLongString(const std::string &s)
{
writeU32(s.size());
writeBytes(reinterpret_cast<uint8_t *>(const_cast<char *>(s.data())), s.size());
}
void SaveBuffer::flushToFile()
{
std::cout << "flushToFile()" << std::endl;
stream.write(reinterpret_cast<const char *>(buffer.data()), buffer.size());
buffer.clear();
}
void SaveBuffer::finish()
{
flushToFile();
}
void MapIO::saveMap(Map &map)
{
std::ofstream stream;
SaveBuffer buffer = SaveBuffer(stream);
stream.open("map2.otbm", std::ofstream::out | std::ios::binary | std::ofstream::trunc);
buffer.writeRawString("OTBM");
buffer.startNode(OTBM_ROOT);
{
OTBMVersion otbmVersion = map.getMapVersion().otbmVersion;
buffer.writeU32(static_cast<uint32_t>(otbmVersion));
buffer.writeU16(map.getWidth());
buffer.writeU16(map.getHeight());
buffer.writeU32(Items::items.getOtbVersionInfo().majorVersion);
buffer.writeU32(Items::items.getOtbVersionInfo().minorVersion);
buffer.startNode(OTBM_MAP_DATA);
{
buffer.writeU8(OTBM_ATTR_DESCRIPTION);
buffer.writeString("Saved by VME (Vulkan Map Editor)" + __VME_VERSION__);
buffer.writeU8(OTBM_ATTR_DESCRIPTION);
buffer.writeString(map.getDescription());
buffer.writeU8(OTBM_ATTR_EXT_SPAWN_FILE);
buffer.writeString("map.spawn.xml");
buffer.writeU8(OTBM_ATTR_EXT_HOUSE_FILE);
buffer.writeString("map.house.xml");
// Tiles
uint32_t savedTiles = 0;
int x = -1;
int y = -1;
int z = -1;
bool emptyMap = true;
Serializer serializer(buffer, map.getMapVersion());
for (const auto &location : map.begin())
{
++savedTiles;
Tile *tile = location->getTile();
// We can skip the tile if it has no entities
if (!tile || tile->getEntityCount() == 0)
{
continue;
}
const Position &pos = location->getPosition();
// Need new node?
if (pos.x < x || pos.x > x + 0xFF || pos.y < y || pos.y > y + 0xFF || pos.z != z)
{
if (!emptyMap)
{
buffer.endNode();
}
emptyMap = false;
buffer.startNode(OTBM_TILE_AREA);
x = pos.x & 0xFF00;
buffer.writeU16(x);
y = pos.y & 0xFF00;
buffer.writeU16(y);
z = pos.z;
buffer.writeU8(z);
}
bool isHouseTile = false;
buffer.startNode(isHouseTile ? OTBM_HOUSETILE : OTBM_TILE);
buffer.writeU8(location->getX() & 0xFF);
buffer.writeU8(location->getY() & 0xFF);
if (isHouseTile)
{
uint32_t houseId = 0;
buffer.writeU32(houseId);
}
if (tile->getMapFlags())
{
buffer.writeU8(OTBM_ATTR_TILE_FLAGS);
buffer.writeU32(tile->getMapFlags());
}
if (tile->getGround())
{
Item *ground = tile->getGround();
if (ground->hasAttributes())
{
serializer.serializeItem(*ground);
}
else
{
buffer.writeU16(ground->getId());
}
}
for (const Item &item : tile->getItems())
{
serializer.serializeItem(item);
}
buffer.endNode();
}
// Close the last node
if (!emptyMap)
{
buffer.endNode();
}
buffer.startNode(OTBM_TOWNS);
for (auto &townEntry : map.getTowns())
{
Town &town = townEntry.second;
const Position &townPos = town.getTemplePosition();
buffer.startNode(OTBM_TOWN);
buffer.writeU32(town.getID());
buffer.writeString(town.getName());
buffer.writeU16(townPos.x);
buffer.writeU16(townPos.y);
buffer.writeU8(townPos.z);
buffer.endNode();
}
buffer.endNode();
if (otbmVersion >= OTBMVersion::MAP_OTBM_3)
{
// TODO write waypoints
// TODO See RME: iomap_otb.cpp line 1415
}
}
buffer.endNode();
}
buffer.endNode();
buffer.finish();
stream.close();
}
void MapIO::Serializer::serializeItem(const Item &item)
{
buffer.startNode(OTBM_ITEM);
buffer.writeU16(item.getId());
serializeItemAttributes(item);
buffer.endNode();
}
void MapIO::Serializer::serializeItemAttributes(const Item &item)
{
if (mapVersion.otbmVersion >= OTBMVersion::MAP_OTBM_2)
{
const ItemType &itemType = *item.itemType;
if (itemType.usesSubType())
{
buffer.writeU8(OTBM_ATTR_COUNT);
buffer.writeU8(item.getSubtype());
}
}
if (mapVersion.otbmVersion >= OTBMVersion::MAP_OTBM_4)
{
if (item.hasAttributes())
{
buffer.writeU8(OTBM_ATTR_ATTRIBUTE_MAP);
serializeItemAttributeMap(item.getAttributes());
}
}
}
void MapIO::Serializer::serializeItemAttributeMap(const std::unordered_map<ItemAttribute_t, ItemAttribute> &attributes)
{
// Can not have more than UINT16_MAX items
buffer.writeU16(std::min((size_t)UINT16_MAX, attributes.size()));
auto entry = attributes.begin();
int i = 0;
while (entry != attributes.end() && i <= UINT16_MAX)
{
const ItemAttribute_t &attributeType = entry->first;
std::stringstream attributeTypeString;
attributeTypeString << attributeType;
std::string s = attributeTypeString.str();
if (s.size() > UINT16_MAX)
{
buffer.writeString(s.substr(0, UINT16_MAX));
}
else
{
buffer.writeString(s);
}
auto attribute = entry->second;
serializeItemAttribute(attribute);
++entry;
++i;
}
}
void MapIO::Serializer::serializeItemAttribute(ItemAttribute &attribute)
{
buffer.writeU8(static_cast<uint8_t>(attribute.type));
if (attribute.holds<std::string>())
{
buffer.writeLongString(attribute.get<std::string>().value());
}
else if (attribute.holds<int>())
{
buffer.writeU32(static_cast<uint32_t>(attribute.get<int>().value()));
}
else if (attribute.holds<double>())
{
buffer.writeU64(static_cast<uint64_t>(attribute.get<double>().value()));
}
}
| true |